blob: 3fdc2a71bc6f50f67bfe852e810c335a504e52a1 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton24bc5d92011-03-30 18:16:51 +000043void
Greg Claytonb72d0f02011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000066 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000068 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000070 }
71 }
Greg Claytonb72d0f02011-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 Claytonff39f742011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Claytonb72d0f02011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000090 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000093 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000095 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000098 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000100 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000103 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000105 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000113{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Claytonff39f742011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000130}
131
132void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-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 Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Claytonff39f742011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000148
Greg Claytonb72d0f02011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000154
Greg Claytonb72d0f02011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000160
Greg Claytonb72d0f02011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000177 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000195 }
196}
197
Greg Claytonb72d0f02011-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 Clayton24bc5d92011-03-30 18:16:51 +0000227bool
Greg Claytonb72d0f02011-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 Clayton143fcc32011-04-13 00:18:08 +0000350ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-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 Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000466ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000479 if (m_match_info.UserIDIsValid () &&
480 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000481 return false;
482
Greg Claytonb72d0f02011-04-12 05:54:46 +0000483 if (m_match_info.GroupIDIsValid () &&
484 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000502ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000513 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000514 return false;
515
Greg Claytonb72d0f02011-04-12 05:54:46 +0000516 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000536ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-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 Claytonfd119992011-01-07 06:08:19 +0000542
Chris Lattner24943d22010-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 Clayton8d2ea282011-07-17 20:36:25 +0000553 if (debugger_ap->CanDebug(target, true))
Chris Lattner24943d22010-06-08 16:52:24 +0000554 return debugger_ap.release();
555 }
556 }
557 else
558 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000559 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000560 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000561 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton8d2ea282011-07-17 20:36:25 +0000562 if (debugger_ap->CanDebug(target, false))
Greg Clayton54e7afa2010-07-09 20:39:50 +0000563 return debugger_ap.release();
Chris Lattner24943d22010-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 Clayton49ce6822010-10-31 03:01:06 +0000575 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000576 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000577 m_target (target),
Chris Lattner24943d22010-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 Ingham21f37ad2011-08-09 02:12:22 +0000585 m_mod_id (),
Chris Lattner24943d22010-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 Clayton20d338f2010-11-18 05:57:03 +0000591 m_image_tokens (),
592 m_listener (listener),
593 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000594 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000595 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000596 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000597 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000598 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000599 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000600 m_stdout_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000601 m_memory_cache (*this),
602 m_allocated_memory_cache (*this),
Jim Inghamc0c53242011-09-15 21:36:42 +0000603 m_attached_to_process (false),
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000604 m_next_event_action_ap()
Chris Lattner24943d22010-06-08 16:52:24 +0000605{
Caroline Tice1ebef442010-09-27 00:30:10 +0000606 UpdateInstanceName();
607
Greg Claytone005f2c2010-11-06 01:53:30 +0000608 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000609 if (log)
610 log->Printf ("%p Process::Process()", this);
611
Greg Clayton49ce6822010-10-31 03:01:06 +0000612 SetEventName (eBroadcastBitStateChanged, "state-changed");
613 SetEventName (eBroadcastBitInterrupt, "interrupt");
614 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
615 SetEventName (eBroadcastBitSTDERR, "stderr-available");
616
Chris Lattner24943d22010-06-08 16:52:24 +0000617 listener.StartListeningForEvents (this,
618 eBroadcastBitStateChanged |
619 eBroadcastBitInterrupt |
620 eBroadcastBitSTDOUT |
621 eBroadcastBitSTDERR);
622
623 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
624 eBroadcastBitStateChanged);
625
626 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
627 eBroadcastInternalStateControlStop |
628 eBroadcastInternalStateControlPause |
629 eBroadcastInternalStateControlResume);
630}
631
632//----------------------------------------------------------------------
633// Destructor
634//----------------------------------------------------------------------
635Process::~Process()
636{
Greg Claytone005f2c2010-11-06 01:53:30 +0000637 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000638 if (log)
639 log->Printf ("%p Process::~Process()", this);
640 StopPrivateStateThread();
641}
642
643void
644Process::Finalize()
645{
646 // Do any cleanup needed prior to being destructed... Subclasses
647 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000648
649 // We need to destroy the loader before the derived Process class gets destroyed
650 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton37f962e2011-08-22 02:49:39 +0000651 m_dyld_ap.reset();
652 m_os_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000653}
654
655void
656Process::RegisterNotificationCallbacks (const Notifications& callbacks)
657{
658 m_notifications.push_back(callbacks);
659 if (callbacks.initialize != NULL)
660 callbacks.initialize (callbacks.baton, this);
661}
662
663bool
664Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
665{
666 std::vector<Notifications>::iterator pos, end = m_notifications.end();
667 for (pos = m_notifications.begin(); pos != end; ++pos)
668 {
669 if (pos->baton == callbacks.baton &&
670 pos->initialize == callbacks.initialize &&
671 pos->process_state_changed == callbacks.process_state_changed)
672 {
673 m_notifications.erase(pos);
674 return true;
675 }
676 }
677 return false;
678}
679
680void
681Process::SynchronouslyNotifyStateChanged (StateType state)
682{
683 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
684 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
685 {
686 if (notification_pos->process_state_changed)
687 notification_pos->process_state_changed (notification_pos->baton, this, state);
688 }
689}
690
691// FIXME: We need to do some work on events before the general Listener sees them.
692// For instance if we are continuing from a breakpoint, we need to ensure that we do
693// the little "insert real insn, step & stop" trick. But we can't do that when the
694// event is delivered by the broadcaster - since that is done on the thread that is
695// waiting for new events, so if we needed more than one event for our handling, we would
696// stall. So instead we do it when we fetch the event off of the queue.
697//
698
699StateType
700Process::GetNextEvent (EventSP &event_sp)
701{
702 StateType state = eStateInvalid;
703
704 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
705 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
706
707 return state;
708}
709
710
711StateType
712Process::WaitForProcessToStop (const TimeValue *timeout)
713{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000714 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
715 // We have to actually check each event, and in the case of a stopped event check the restarted flag
716 // on the event.
717 EventSP event_sp;
718 StateType state = GetState();
719 // If we are exited or detached, we won't ever get back to any
720 // other valid state...
721 if (state == eStateDetached || state == eStateExited)
722 return state;
723
724 while (state != eStateInvalid)
725 {
726 state = WaitForStateChangedEvents (timeout, event_sp);
727 switch (state)
728 {
729 case eStateCrashed:
730 case eStateDetached:
731 case eStateExited:
732 case eStateUnloaded:
733 return state;
734 case eStateStopped:
735 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
736 continue;
737 else
738 return state;
739 default:
740 continue;
741 }
742 }
743 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000744}
745
746
747StateType
748Process::WaitForState
749(
750 const TimeValue *timeout,
751 const StateType *match_states, const uint32_t num_match_states
752)
753{
754 EventSP event_sp;
755 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000756 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000757 while (state != eStateInvalid)
758 {
Greg Claytond8c62532010-10-07 04:19:01 +0000759 // If we are exited or detached, we won't ever get back to any
760 // other valid state...
761 if (state == eStateDetached || state == eStateExited)
762 return state;
763
Chris Lattner24943d22010-06-08 16:52:24 +0000764 state = WaitForStateChangedEvents (timeout, event_sp);
765
766 for (i=0; i<num_match_states; ++i)
767 {
768 if (match_states[i] == state)
769 return state;
770 }
771 }
772 return state;
773}
774
Jim Ingham63e24d72010-10-11 23:53:14 +0000775bool
776Process::HijackProcessEvents (Listener *listener)
777{
778 if (listener != NULL)
779 {
780 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
781 }
782 else
783 return false;
784}
785
786void
787Process::RestoreProcessEvents ()
788{
789 RestoreBroadcaster();
790}
791
Jim Inghamf9f40c22011-02-08 05:20:59 +0000792bool
793Process::HijackPrivateProcessEvents (Listener *listener)
794{
795 if (listener != NULL)
796 {
797 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
798 }
799 else
800 return false;
801}
802
803void
804Process::RestorePrivateProcessEvents ()
805{
806 m_private_state_broadcaster.RestoreBroadcaster();
807}
808
Chris Lattner24943d22010-06-08 16:52:24 +0000809StateType
810Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
811{
Greg Claytone005f2c2010-11-06 01:53:30 +0000812 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000813
814 if (log)
815 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
816
817 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000818 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
819 this,
820 eBroadcastBitStateChanged,
821 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000822 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
823
824 if (log)
825 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
826 __FUNCTION__,
827 timeout,
828 StateAsCString(state));
829 return state;
830}
831
832Event *
833Process::PeekAtStateChangedEvents ()
834{
Greg Claytone005f2c2010-11-06 01:53:30 +0000835 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000836
837 if (log)
838 log->Printf ("Process::%s...", __FUNCTION__);
839
840 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000841 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
842 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000843 if (log)
844 {
845 if (event_ptr)
846 {
847 log->Printf ("Process::%s (event_ptr) => %s",
848 __FUNCTION__,
849 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
850 }
851 else
852 {
853 log->Printf ("Process::%s no events found",
854 __FUNCTION__);
855 }
856 }
857 return event_ptr;
858}
859
860StateType
861Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
862{
Greg Claytone005f2c2010-11-06 01:53:30 +0000863 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000864
865 if (log)
866 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
867
868 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000869 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
870 &m_private_state_broadcaster,
871 eBroadcastBitStateChanged,
872 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000873 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
874
875 // This is a bit of a hack, but when we wait here we could very well return
876 // to the command-line, and that could disable the log, which would render the
877 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000878 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000879 {
880 if (state == eStateInvalid)
881 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
882 else
883 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
884 }
Chris Lattner24943d22010-06-08 16:52:24 +0000885 return state;
886}
887
888bool
889Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
890{
Greg Claytone005f2c2010-11-06 01:53:30 +0000891 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000892
893 if (log)
894 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
895
896 if (control_only)
897 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
898 else
899 return m_private_state_listener.WaitForEvent(timeout, event_sp);
900}
901
902bool
903Process::IsRunning () const
904{
905 return StateIsRunningState (m_public_state.GetValue());
906}
907
908int
909Process::GetExitStatus ()
910{
911 if (m_public_state.GetValue() == eStateExited)
912 return m_exit_status;
913 return -1;
914}
915
Greg Clayton638351a2010-12-04 00:10:17 +0000916
917void
918Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
919{
920 if (m_inherit_host_env && !m_got_host_env)
921 {
922 m_got_host_env = true;
923 StringList host_env;
924 const size_t host_env_count = Host::GetEnvironment (host_env);
925 for (size_t idx=0; idx<host_env_count; idx++)
926 {
927 const char *env_entry = host_env.GetStringAtIndex (idx);
928 if (env_entry)
929 {
Greg Clayton1f3dd642010-12-15 20:52:40 +0000930 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +0000931 if (equal_pos)
932 {
933 std::string key (env_entry, equal_pos - env_entry);
934 std::string value (equal_pos + 1);
935 if (m_env_vars.find (key) == m_env_vars.end())
936 m_env_vars[key] = value;
937 }
938 }
939 }
940 }
941}
942
943
944size_t
945Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
946{
947 GetHostEnvironmentIfNeeded ();
948
949 dictionary::const_iterator pos, end = m_env_vars.end();
950 for (pos = m_env_vars.begin(); pos != end; ++pos)
951 {
952 std::string env_var_equal_value (pos->first);
953 env_var_equal_value.append(1, '=');
954 env_var_equal_value.append (pos->second);
955 env.AppendArgument (env_var_equal_value.c_str());
956 }
957 return env.GetArgumentCount();
958}
959
960
Chris Lattner24943d22010-06-08 16:52:24 +0000961const char *
962Process::GetExitDescription ()
963{
964 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
965 return m_exit_string.c_str();
966 return NULL;
967}
968
Greg Clayton72e1c782011-01-22 23:43:18 +0000969bool
Chris Lattner24943d22010-06-08 16:52:24 +0000970Process::SetExitStatus (int status, const char *cstr)
971{
Greg Clayton68ca8232011-01-25 02:58:48 +0000972 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
973 if (log)
974 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
975 status, status,
976 cstr ? "\"" : "",
977 cstr ? cstr : "NULL",
978 cstr ? "\"" : "");
979
Greg Clayton72e1c782011-01-22 23:43:18 +0000980 // We were already in the exited state
981 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +0000982 {
Greg Clayton644ddfb2011-01-26 23:47:29 +0000983 if (log)
984 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +0000985 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +0000986 }
Greg Clayton72e1c782011-01-22 23:43:18 +0000987
988 m_exit_status = status;
989 if (cstr)
990 m_exit_string = cstr;
991 else
992 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +0000993
Greg Clayton72e1c782011-01-22 23:43:18 +0000994 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +0000995
Greg Clayton72e1c782011-01-22 23:43:18 +0000996 SetPrivateState (eStateExited);
997 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000998}
999
1000// This static callback can be used to watch for local child processes on
1001// the current host. The the child process exits, the process will be
1002// found in the global target list (we want to be completely sure that the
1003// lldb_private::Process doesn't go away before we can deliver the signal.
1004bool
1005Process::SetProcessExitStatus
1006(
1007 void *callback_baton,
1008 lldb::pid_t pid,
1009 int signo, // Zero for no signal
1010 int exit_status // Exit value of process if signal is zero
1011)
1012{
1013 if (signo == 0 || exit_status)
1014 {
Greg Clayton63094e02010-06-23 01:19:29 +00001015 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001016 if (target_sp)
1017 {
1018 ProcessSP process_sp (target_sp->GetProcessSP());
1019 if (process_sp)
1020 {
1021 const char *signal_cstr = NULL;
1022 if (signo)
1023 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1024
1025 process_sp->SetExitStatus (exit_status, signal_cstr);
1026 }
1027 }
1028 return true;
1029 }
1030 return false;
1031}
1032
1033
Greg Clayton37f962e2011-08-22 02:49:39 +00001034void
1035Process::UpdateThreadListIfNeeded ()
1036{
1037 const uint32_t stop_id = GetStopID();
1038 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1039 {
1040 Mutex::Locker locker (m_thread_list.GetMutex ());
1041 ThreadList new_thread_list(this);
1042 // Always update the thread list with the protocol specific
1043 // thread list
1044 UpdateThreadList (m_thread_list, new_thread_list);
1045 OperatingSystem *os = GetOperatingSystem ();
1046 if (os)
1047 os->UpdateThreadList (m_thread_list, new_thread_list);
1048 m_thread_list.Update (new_thread_list);
1049 m_thread_list.SetStopID (stop_id);
1050 }
1051}
1052
Chris Lattner24943d22010-06-08 16:52:24 +00001053uint32_t
1054Process::GetNextThreadIndexID ()
1055{
1056 return ++m_thread_index_id;
1057}
1058
1059StateType
1060Process::GetState()
1061{
1062 // If any other threads access this we will need a mutex for it
1063 return m_public_state.GetValue ();
1064}
1065
1066void
1067Process::SetPublicState (StateType new_state)
1068{
Greg Clayton68ca8232011-01-25 02:58:48 +00001069 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001070 if (log)
1071 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1072 m_public_state.SetValue (new_state);
1073}
1074
1075StateType
1076Process::GetPrivateState ()
1077{
1078 return m_private_state.GetValue();
1079}
1080
1081void
1082Process::SetPrivateState (StateType new_state)
1083{
Greg Clayton68ca8232011-01-25 02:58:48 +00001084 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001085 bool state_changed = false;
1086
1087 if (log)
1088 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1089
1090 Mutex::Locker locker(m_private_state.GetMutex());
1091
1092 const StateType old_state = m_private_state.GetValueNoLock ();
1093 state_changed = old_state != new_state;
1094 if (state_changed)
1095 {
1096 m_private_state.SetValueNoLock (new_state);
1097 if (StateIsStoppedState(new_state))
1098 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001099 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001100 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001101 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001102 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001103 }
1104 // Use our target to get a shared pointer to ourselves...
1105 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1106 }
1107 else
1108 {
1109 if (log)
1110 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
1111 }
1112}
1113
Chris Lattner24943d22010-06-08 16:52:24 +00001114addr_t
1115Process::GetImageInfoAddress()
1116{
1117 return LLDB_INVALID_ADDRESS;
1118}
1119
Greg Clayton0baa3942010-11-04 01:54:29 +00001120//----------------------------------------------------------------------
1121// LoadImage
1122//
1123// This function provides a default implementation that works for most
1124// unix variants. Any Process subclasses that need to do shared library
1125// loading differently should override LoadImage and UnloadImage and
1126// do what is needed.
1127//----------------------------------------------------------------------
1128uint32_t
1129Process::LoadImage (const FileSpec &image_spec, Error &error)
1130{
1131 DynamicLoader *loader = GetDynamicLoader();
1132 if (loader)
1133 {
1134 error = loader->CanLoadImage();
1135 if (error.Fail())
1136 return LLDB_INVALID_IMAGE_TOKEN;
1137 }
1138
1139 if (error.Success())
1140 {
1141 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001142
1143 if (thread_sp)
1144 {
1145 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1146
1147 if (frame_sp)
1148 {
1149 ExecutionContext exe_ctx;
1150 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001151 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001152 StreamString expr;
1153 char path[PATH_MAX];
1154 image_spec.GetPath(path, sizeof(path));
1155 expr.Printf("dlopen (\"%s\", 2)", path);
1156 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001157 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan47dc4572011-09-15 02:13:07 +00001158 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001159 error = result_valobj_sp->GetError();
1160 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001161 {
1162 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001163 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001164 {
1165 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1166 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1167 {
1168 uint32_t image_token = m_image_tokens.size();
1169 m_image_tokens.push_back (image_ptr);
1170 return image_token;
1171 }
1172 }
1173 }
1174 }
1175 }
1176 }
1177 return LLDB_INVALID_IMAGE_TOKEN;
1178}
1179
1180//----------------------------------------------------------------------
1181// UnloadImage
1182//
1183// This function provides a default implementation that works for most
1184// unix variants. Any Process subclasses that need to do shared library
1185// loading differently should override LoadImage and UnloadImage and
1186// do what is needed.
1187//----------------------------------------------------------------------
1188Error
1189Process::UnloadImage (uint32_t image_token)
1190{
1191 Error error;
1192 if (image_token < m_image_tokens.size())
1193 {
1194 const addr_t image_addr = m_image_tokens[image_token];
1195 if (image_addr == LLDB_INVALID_ADDRESS)
1196 {
1197 error.SetErrorString("image already unloaded");
1198 }
1199 else
1200 {
1201 DynamicLoader *loader = GetDynamicLoader();
1202 if (loader)
1203 error = loader->CanLoadImage();
1204
1205 if (error.Success())
1206 {
1207 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001208
1209 if (thread_sp)
1210 {
1211 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1212
1213 if (frame_sp)
1214 {
1215 ExecutionContext exe_ctx;
1216 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001217 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001218 StreamString expr;
1219 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1220 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001221 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan47dc4572011-09-15 02:13:07 +00001222 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001223 if (result_valobj_sp->GetError().Success())
1224 {
1225 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001226 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001227 {
1228 if (scalar.UInt(1))
1229 {
1230 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1231 }
1232 else
1233 {
1234 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1235 }
1236 }
1237 }
1238 else
1239 {
1240 error = result_valobj_sp->GetError();
1241 }
1242 }
1243 }
1244 }
1245 }
1246 }
1247 else
1248 {
1249 error.SetErrorString("invalid image token");
1250 }
1251 return error;
1252}
1253
Greg Clayton75906e42011-05-11 18:39:18 +00001254const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001255Process::GetABI()
1256{
Greg Clayton75906e42011-05-11 18:39:18 +00001257 if (!m_abi_sp)
1258 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1259 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001260}
1261
Jim Ingham642036f2010-09-23 02:01:19 +00001262LanguageRuntime *
1263Process::GetLanguageRuntime(lldb::LanguageType language)
1264{
1265 LanguageRuntimeCollection::iterator pos;
1266 pos = m_language_runtimes.find (language);
1267 if (pos == m_language_runtimes.end())
1268 {
1269 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1270
1271 m_language_runtimes[language]
1272 = runtime;
1273 return runtime.get();
1274 }
1275 else
1276 return (*pos).second.get();
1277}
1278
1279CPPLanguageRuntime *
1280Process::GetCPPLanguageRuntime ()
1281{
1282 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1283 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1284 return static_cast<CPPLanguageRuntime *> (runtime);
1285 return NULL;
1286}
1287
1288ObjCLanguageRuntime *
1289Process::GetObjCLanguageRuntime ()
1290{
1291 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1292 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1293 return static_cast<ObjCLanguageRuntime *> (runtime);
1294 return NULL;
1295}
1296
Chris Lattner24943d22010-06-08 16:52:24 +00001297BreakpointSiteList &
1298Process::GetBreakpointSiteList()
1299{
1300 return m_breakpoint_site_list;
1301}
1302
1303const BreakpointSiteList &
1304Process::GetBreakpointSiteList() const
1305{
1306 return m_breakpoint_site_list;
1307}
1308
1309
1310void
1311Process::DisableAllBreakpointSites ()
1312{
1313 m_breakpoint_site_list.SetEnabledForAll (false);
1314}
1315
1316Error
1317Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1318{
1319 Error error (DisableBreakpointSiteByID (break_id));
1320
1321 if (error.Success())
1322 m_breakpoint_site_list.Remove(break_id);
1323
1324 return error;
1325}
1326
1327Error
1328Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1329{
1330 Error error;
1331 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1332 if (bp_site_sp)
1333 {
1334 if (bp_site_sp->IsEnabled())
1335 error = DisableBreakpoint (bp_site_sp.get());
1336 }
1337 else
1338 {
1339 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1340 }
1341
1342 return error;
1343}
1344
1345Error
1346Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1347{
1348 Error error;
1349 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1350 if (bp_site_sp)
1351 {
1352 if (!bp_site_sp->IsEnabled())
1353 error = EnableBreakpoint (bp_site_sp.get());
1354 }
1355 else
1356 {
1357 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1358 }
1359 return error;
1360}
1361
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001362lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +00001363Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1364{
Greg Clayton265ab332011-05-19 18:17:41 +00001365 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001366 if (load_addr != LLDB_INVALID_ADDRESS)
1367 {
1368 BreakpointSiteSP bp_site_sp;
1369
1370 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1371 // create a new breakpoint site and add it.
1372
1373 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1374
1375 if (bp_site_sp)
1376 {
1377 bp_site_sp->AddOwner (owner);
1378 owner->SetBreakpointSite (bp_site_sp);
1379 return bp_site_sp->GetID();
1380 }
1381 else
1382 {
1383 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1384 if (bp_site_sp)
1385 {
1386 if (EnableBreakpoint (bp_site_sp.get()).Success())
1387 {
1388 owner->SetBreakpointSite (bp_site_sp);
1389 return m_breakpoint_site_list.Add (bp_site_sp);
1390 }
1391 }
1392 }
1393 }
1394 // We failed to enable the breakpoint
1395 return LLDB_INVALID_BREAK_ID;
1396
1397}
1398
1399void
1400Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1401{
1402 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1403 if (num_owners == 0)
1404 {
1405 DisableBreakpoint(bp_site_sp.get());
1406 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1407 }
1408}
1409
1410
1411size_t
1412Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1413{
1414 size_t bytes_removed = 0;
1415 addr_t intersect_addr;
1416 size_t intersect_size;
1417 size_t opcode_offset;
1418 size_t idx;
1419 BreakpointSiteSP bp;
Jim Ingham82820f92011-06-29 19:42:28 +00001420 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001421
Jim Ingham82820f92011-06-29 19:42:28 +00001422 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001423 {
Jim Ingham82820f92011-06-29 19:42:28 +00001424 for (idx = 0; (bp = bp_sites_in_range.GetByIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001425 {
Jim Ingham82820f92011-06-29 19:42:28 +00001426 if (bp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001427 {
Jim Ingham82820f92011-06-29 19:42:28 +00001428 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1429 {
1430 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1431 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1432 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1433 size_t buf_offset = intersect_addr - bp_addr;
1434 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1435 }
Chris Lattner24943d22010-06-08 16:52:24 +00001436 }
1437 }
1438 }
1439 return bytes_removed;
1440}
1441
1442
Greg Claytonb1888f22011-03-19 01:12:21 +00001443
1444size_t
1445Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1446{
1447 PlatformSP platform_sp (m_target.GetPlatform());
1448 if (platform_sp)
1449 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1450 return 0;
1451}
1452
Chris Lattner24943d22010-06-08 16:52:24 +00001453Error
1454Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1455{
1456 Error error;
1457 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001458 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001459 const addr_t bp_addr = bp_site->GetLoadAddress();
1460 if (log)
1461 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1462 if (bp_site->IsEnabled())
1463 {
1464 if (log)
1465 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1466 return error;
1467 }
1468
1469 if (bp_addr == LLDB_INVALID_ADDRESS)
1470 {
1471 error.SetErrorString("BreakpointSite contains an invalid load address.");
1472 return error;
1473 }
1474 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1475 // trap for the breakpoint site
1476 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1477
1478 if (bp_opcode_size == 0)
1479 {
1480 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1481 }
1482 else
1483 {
1484 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1485
1486 if (bp_opcode_bytes == NULL)
1487 {
1488 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1489 return error;
1490 }
1491
1492 // Save the original opcode by reading it
1493 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1494 {
1495 // Write a software breakpoint in place of the original opcode
1496 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1497 {
1498 uint8_t verify_bp_opcode_bytes[64];
1499 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1500 {
1501 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1502 {
1503 bp_site->SetEnabled(true);
1504 bp_site->SetType (BreakpointSite::eSoftware);
1505 if (log)
1506 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1507 bp_site->GetID(),
1508 (uint64_t)bp_addr);
1509 }
1510 else
1511 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1512 }
1513 else
1514 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1515 }
1516 else
1517 error.SetErrorString("Unable to write breakpoint trap to memory.");
1518 }
1519 else
1520 error.SetErrorString("Unable to read memory at breakpoint address.");
1521 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001522 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001523 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1524 bp_site->GetID(),
1525 (uint64_t)bp_addr,
1526 error.AsCString());
1527 return error;
1528}
1529
1530Error
1531Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1532{
1533 Error error;
1534 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001535 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001536 addr_t bp_addr = bp_site->GetLoadAddress();
1537 lldb::user_id_t breakID = bp_site->GetID();
1538 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001539 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001540
1541 if (bp_site->IsHardware())
1542 {
1543 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1544 }
1545 else if (bp_site->IsEnabled())
1546 {
1547 const size_t break_op_size = bp_site->GetByteSize();
1548 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1549 if (break_op_size > 0)
1550 {
1551 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001552 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001553 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001554 bool break_op_found = false;
1555
1556 // Read the breakpoint opcode
1557 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1558 {
1559 bool verify = false;
1560 // Make sure we have the a breakpoint opcode exists at this address
1561 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1562 {
1563 break_op_found = true;
1564 // We found a valid breakpoint opcode at this address, now restore
1565 // the saved opcode.
1566 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1567 {
1568 verify = true;
1569 }
1570 else
1571 error.SetErrorString("Memory write failed when restoring original opcode.");
1572 }
1573 else
1574 {
1575 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1576 // Set verify to true and so we can check if the original opcode has already been restored
1577 verify = true;
1578 }
1579
1580 if (verify)
1581 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001582 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001583 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001584 // Verify that our original opcode made it back to the inferior
1585 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1586 {
1587 // compare the memory we just read with the original opcode
1588 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1589 {
1590 // SUCCESS
1591 bp_site->SetEnabled(false);
1592 if (log)
1593 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1594 return error;
1595 }
1596 else
1597 {
1598 if (break_op_found)
1599 error.SetErrorString("Failed to restore original opcode.");
1600 }
1601 }
1602 else
1603 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1604 }
1605 }
1606 else
1607 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1608 }
1609 }
1610 else
1611 {
1612 if (log)
1613 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1614 return error;
1615 }
1616
1617 if (log)
1618 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1619 bp_site->GetID(),
1620 (uint64_t)bp_addr,
1621 error.AsCString());
1622 return error;
1623
1624}
1625
Greg Claytonfd119992011-01-07 06:08:19 +00001626// Comment out line below to disable memory caching
1627#define ENABLE_MEMORY_CACHING
1628// Uncomment to verify memory caching works after making changes to caching code
1629//#define VERIFY_MEMORY_READS
1630
1631#if defined (ENABLE_MEMORY_CACHING)
1632
1633#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001634
1635size_t
1636Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1637{
Greg Claytonfd119992011-01-07 06:08:19 +00001638 // Memory caching is enabled, with debug verification
1639 if (buf && size)
1640 {
1641 // Uncomment the line below to make sure memory caching is working.
1642 // I ran this through the test suite and got no assertions, so I am
1643 // pretty confident this is working well. If any changes are made to
1644 // memory caching, uncomment the line below and test your changes!
1645
1646 // Verify all memory reads by using the cache first, then redundantly
1647 // reading the same memory from the inferior and comparing to make sure
1648 // everything is exactly the same.
1649 std::string verify_buf (size, '\0');
1650 assert (verify_buf.size() == size);
1651 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1652 Error verify_error;
1653 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1654 assert (cache_bytes_read == verify_bytes_read);
1655 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1656 assert (verify_error.Success() == error.Success());
1657 return cache_bytes_read;
1658 }
1659 return 0;
1660}
1661
1662#else // #if defined (VERIFY_MEMORY_READS)
1663
1664size_t
1665Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1666{
1667 // Memory caching enabled, no verification
Greg Clayton613b8732011-05-17 03:37:42 +00001668 return m_memory_cache.Read (addr, buf, size, error);
Greg Claytonfd119992011-01-07 06:08:19 +00001669}
1670
1671#endif // #else for #if defined (VERIFY_MEMORY_READS)
1672
1673#else // #if defined (ENABLE_MEMORY_CACHING)
1674
1675size_t
1676Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1677{
1678 // Memory caching is disabled
1679 return ReadMemoryFromInferior (addr, buf, size, error);
1680}
1681
1682#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1683
1684
1685size_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001686Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1687{
1688 size_t total_cstr_len = 0;
1689 if (dst && dst_max_len)
1690 {
1691 // NULL out everything just to be safe
1692 memset (dst, 0, dst_max_len);
1693 Error error;
1694 addr_t curr_addr = addr;
1695 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1696 size_t bytes_left = dst_max_len - 1;
1697 char *curr_dst = dst;
1698
1699 while (bytes_left > 0)
1700 {
1701 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1702 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1703 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1704
1705 if (bytes_read == 0)
1706 {
1707 dst[total_cstr_len] = '\0';
1708 break;
1709 }
1710 const size_t len = strlen(curr_dst);
1711
1712 total_cstr_len += len;
1713
1714 if (len < bytes_to_read)
1715 break;
1716
1717 curr_dst += bytes_read;
1718 curr_addr += bytes_read;
1719 bytes_left -= bytes_read;
1720 }
1721 }
1722 return total_cstr_len;
1723}
1724
1725size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001726Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1727{
Chris Lattner24943d22010-06-08 16:52:24 +00001728 if (buf == NULL || size == 0)
1729 return 0;
1730
1731 size_t bytes_read = 0;
1732 uint8_t *bytes = (uint8_t *)buf;
1733
1734 while (bytes_read < size)
1735 {
1736 const size_t curr_size = size - bytes_read;
1737 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1738 bytes + bytes_read,
1739 curr_size,
1740 error);
1741 bytes_read += curr_bytes_read;
1742 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1743 break;
1744 }
1745
1746 // Replace any software breakpoint opcodes that fall into this range back
1747 // into "buf" before we return
1748 if (bytes_read > 0)
1749 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1750 return bytes_read;
1751}
1752
Greg Claytonf72fdee2010-12-16 20:01:20 +00001753uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00001754Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00001755{
Greg Claytonc0fa5332011-05-22 22:46:53 +00001756 Scalar scalar;
1757 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1758 return scalar.ULongLong(fail_value);
1759 return fail_value;
1760}
1761
1762addr_t
1763Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1764{
1765 Scalar scalar;
1766 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1767 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1768 return LLDB_INVALID_ADDRESS;
1769}
1770
1771
1772bool
1773Process::WritePointerToMemory (lldb::addr_t vm_addr,
1774 lldb::addr_t ptr_value,
1775 Error &error)
1776{
1777 Scalar scalar;
1778 const uint32_t addr_byte_size = GetAddressByteSize();
1779 if (addr_byte_size <= 4)
1780 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001781 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00001782 scalar = ptr_value;
1783 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001784}
1785
Chris Lattner24943d22010-06-08 16:52:24 +00001786size_t
1787Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1788{
1789 size_t bytes_written = 0;
1790 const uint8_t *bytes = (const uint8_t *)buf;
1791
1792 while (bytes_written < size)
1793 {
1794 const size_t curr_size = size - bytes_written;
1795 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1796 bytes + bytes_written,
1797 curr_size,
1798 error);
1799 bytes_written += curr_bytes_written;
1800 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1801 break;
1802 }
1803 return bytes_written;
1804}
1805
1806size_t
1807Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1808{
Greg Claytonfd119992011-01-07 06:08:19 +00001809#if defined (ENABLE_MEMORY_CACHING)
1810 m_memory_cache.Flush (addr, size);
1811#endif
1812
Chris Lattner24943d22010-06-08 16:52:24 +00001813 if (buf == NULL || size == 0)
1814 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00001815
Jim Ingham21f37ad2011-08-09 02:12:22 +00001816 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00001817
Chris Lattner24943d22010-06-08 16:52:24 +00001818 // We need to write any data that would go where any current software traps
1819 // (enabled software breakpoints) any software traps (breakpoints) that we
1820 // may have placed in our tasks memory.
1821
1822 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1823 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1824
1825 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001826 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00001827
1828 BreakpointSiteList::collection::const_iterator pos;
1829 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001830 addr_t intersect_addr = 0;
1831 size_t intersect_size = 0;
1832 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001833 const uint8_t *ubuf = (const uint8_t *)buf;
1834
1835 for (pos = iter; pos != end; ++pos)
1836 {
1837 BreakpointSiteSP bp;
1838 bp = pos->second;
1839
1840 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1841 assert(addr <= intersect_addr && intersect_addr < addr + size);
1842 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1843 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1844
1845 // Check for bytes before this breakpoint
1846 const addr_t curr_addr = addr + bytes_written;
1847 if (intersect_addr > curr_addr)
1848 {
1849 // There are some bytes before this breakpoint that we need to
1850 // just write to memory
1851 size_t curr_size = intersect_addr - curr_addr;
1852 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1853 ubuf + bytes_written,
1854 curr_size,
1855 error);
1856 bytes_written += curr_bytes_written;
1857 if (curr_bytes_written != curr_size)
1858 {
1859 // We weren't able to write all of the requested bytes, we
1860 // are done looping and will return the number of bytes that
1861 // we have written so far.
1862 break;
1863 }
1864 }
1865
1866 // Now write any bytes that would cover up any software breakpoints
1867 // directly into the breakpoint opcode buffer
1868 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1869 bytes_written += intersect_size;
1870 }
1871
1872 // Write any remaining bytes after the last breakpoint if we have any left
1873 if (bytes_written < size)
1874 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1875 ubuf + bytes_written,
1876 size - bytes_written,
1877 error);
Jim Inghame41494a2011-04-16 00:01:13 +00001878
Chris Lattner24943d22010-06-08 16:52:24 +00001879 return bytes_written;
1880}
Greg Claytonc0fa5332011-05-22 22:46:53 +00001881
1882size_t
1883Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1884{
1885 if (byte_size == UINT32_MAX)
1886 byte_size = scalar.GetByteSize();
1887 if (byte_size > 0)
1888 {
1889 uint8_t buf[32];
1890 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1891 if (mem_size > 0)
1892 return WriteMemory(addr, buf, mem_size, error);
1893 else
1894 error.SetErrorString ("failed to get scalar as memory data");
1895 }
1896 else
1897 {
1898 error.SetErrorString ("invalid scalar value");
1899 }
1900 return 0;
1901}
1902
1903size_t
1904Process::ReadScalarIntegerFromMemory (addr_t addr,
1905 uint32_t byte_size,
1906 bool is_signed,
1907 Scalar &scalar,
1908 Error &error)
1909{
1910 uint64_t uval;
1911
1912 if (byte_size <= sizeof(uval))
1913 {
1914 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1915 if (bytes_read == byte_size)
1916 {
1917 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1918 uint32_t offset = 0;
1919 if (byte_size <= 4)
1920 scalar = data.GetMaxU32 (&offset, byte_size);
1921 else
1922 scalar = data.GetMaxU64 (&offset, byte_size);
1923
1924 if (is_signed)
1925 scalar.SignExtend(byte_size * 8);
1926 return bytes_read;
1927 }
1928 }
1929 else
1930 {
1931 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1932 }
1933 return 0;
1934}
1935
Greg Clayton613b8732011-05-17 03:37:42 +00001936#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00001937addr_t
1938Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1939{
Jim Inghame6bd1422011-06-20 17:32:44 +00001940 if (GetPrivateState() != eStateStopped)
1941 return LLDB_INVALID_ADDRESS;
1942
Greg Clayton613b8732011-05-17 03:37:42 +00001943#if defined (USE_ALLOCATE_MEMORY_CACHE)
1944 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1945#else
Greg Clayton2860ba92011-01-23 19:58:49 +00001946 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1947 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1948 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001949 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001950 size,
Greg Clayton613b8732011-05-17 03:37:42 +00001951 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00001952 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00001953 m_mod_id.GetStopID(),
1954 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00001955 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00001956#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001957}
1958
1959Error
1960Process::DeallocateMemory (addr_t ptr)
1961{
Greg Clayton613b8732011-05-17 03:37:42 +00001962 Error error;
1963#if defined (USE_ALLOCATE_MEMORY_CACHE)
1964 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
1965 {
1966 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
1967 }
1968#else
1969 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00001970
1971 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1972 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001973 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001974 ptr,
1975 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00001976 m_mod_id.GetStopID(),
1977 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00001978#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00001979 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00001980}
1981
1982
1983Error
1984Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1985{
1986 Error error;
1987 error.SetErrorString("watchpoints are not supported");
1988 return error;
1989}
1990
1991Error
1992Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1993{
1994 Error error;
1995 error.SetErrorString("watchpoints are not supported");
1996 return error;
1997}
1998
1999StateType
2000Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2001{
2002 StateType state;
2003 // Now wait for the process to launch and return control to us, and then
2004 // call DidLaunch:
2005 while (1)
2006 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002007 event_sp.reset();
2008 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2009
2010 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00002011 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002012
2013 // If state is invalid, then we timed out
2014 if (state == eStateInvalid)
2015 break;
2016
2017 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002018 HandlePrivateEvent (event_sp);
2019 }
2020 return state;
2021}
2022
2023Error
2024Process::Launch
2025(
2026 char const *argv[],
2027 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00002028 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00002029 const char *stdin_path,
2030 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00002031 const char *stderr_path,
2032 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00002033)
2034{
2035 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002036 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002037 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002038 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002039 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002040
Greg Clayton5beb99d2011-08-11 02:48:45 +00002041 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002042 if (exe_module)
2043 {
Greg Clayton180546b2011-04-30 01:09:13 +00002044 char local_exec_file_path[PATH_MAX];
2045 char platform_exec_file_path[PATH_MAX];
2046 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2047 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002048 if (exe_module->GetFileSpec().Exists())
2049 {
Greg Claytona2f74232011-02-24 22:24:29 +00002050 if (PrivateStateThreadIsValid ())
2051 PausePrivateStateThread ();
2052
Chris Lattner24943d22010-06-08 16:52:24 +00002053 error = WillLaunch (exe_module);
2054 if (error.Success())
2055 {
Greg Claytond8c62532010-10-07 04:19:01 +00002056 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00002057 // The args coming in should not contain the application name, the
2058 // lldb_private::Process class will add this in case the executable
2059 // gets resolved to a different file than was given on the command
2060 // line (like when an applicaiton bundle is specified and will
2061 // resolve to the contained exectuable file, or the file given was
2062 // a symlink or other file system link that resolves to a different
2063 // file).
2064
2065 // Get the resolved exectuable path
2066
2067 // Make a new argument vector
2068 std::vector<const char *> exec_path_plus_argv;
2069 // Append the resolved executable path
Greg Clayton180546b2011-04-30 01:09:13 +00002070 exec_path_plus_argv.push_back (platform_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002071
2072 // Push all args if there are any
2073 if (argv)
2074 {
2075 for (int i = 0; argv[i]; ++i)
2076 exec_path_plus_argv.push_back(argv[i]);
2077 }
2078
2079 // Push a NULL to terminate the args.
2080 exec_path_plus_argv.push_back(NULL);
2081
2082 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00002083 error = DoLaunch (exe_module,
2084 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
2085 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00002086 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00002087 stdin_path,
2088 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00002089 stderr_path,
2090 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00002091
2092 if (error.Fail())
2093 {
2094 if (GetID() != LLDB_INVALID_PROCESS_ID)
2095 {
2096 SetID (LLDB_INVALID_PROCESS_ID);
2097 const char *error_string = error.AsCString();
2098 if (error_string == NULL)
2099 error_string = "launch failed";
2100 SetExitStatus (-1, error_string);
2101 }
2102 }
2103 else
2104 {
2105 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002106 TimeValue timeout_time;
2107 timeout_time = TimeValue::Now();
2108 timeout_time.OffsetWithSeconds(10);
2109 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002110
Greg Clayton49859592011-06-22 01:42:17 +00002111 if (state == eStateInvalid || event_sp.get() == NULL)
2112 {
2113 // We were able to launch the process, but we failed to
2114 // catch the initial stop.
2115 SetExitStatus (0, "failed to catch stop after launch");
2116 Destroy();
2117 }
2118 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002119 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002120
Chris Lattner24943d22010-06-08 16:52:24 +00002121 DidLaunch ();
2122
Greg Clayton37f962e2011-08-22 02:49:39 +00002123 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002124 if (m_dyld_ap.get())
2125 m_dyld_ap->DidLaunch();
2126
Greg Clayton37f962e2011-08-22 02:49:39 +00002127 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002128 // This delays passing the stopped event to listeners till DidLaunch gets
2129 // a chance to complete...
2130 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002131
2132 if (PrivateStateThreadIsValid ())
2133 ResumePrivateStateThread ();
2134 else
2135 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002136 }
2137 else if (state == eStateExited)
2138 {
2139 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2140 // not likely to work, and return an invalid pid.
2141 HandlePrivateEvent (event_sp);
2142 }
2143 }
2144 }
2145 }
2146 else
2147 {
Greg Clayton180546b2011-04-30 01:09:13 +00002148 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002149 }
2150 }
2151 return error;
2152}
2153
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002154Process::NextEventAction::EventActionResult
2155Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002156{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002157 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2158 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002159 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002160 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002161 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002162 return eEventActionRetry;
2163
2164 case eStateStopped:
2165 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00002166 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002167 // During attach, prior to sending the eStateStopped event,
2168 // lldb_private::Process subclasses must set the process must set
2169 // the new process ID.
2170 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00002171 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002172 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00002173 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002174
2175
2176 break;
2177 default:
2178 case eStateExited:
2179 case eStateInvalid:
2180 m_exit_string.assign ("No valid Process");
2181 return eEventActionExit;
2182 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002183 }
2184}
Chris Lattner24943d22010-06-08 16:52:24 +00002185
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002186Process::NextEventAction::EventActionResult
2187Process::AttachCompletionHandler::HandleBeingInterrupted()
2188{
2189 return eEventActionSuccess;
2190}
2191
2192const char *
2193Process::AttachCompletionHandler::GetExitString ()
2194{
2195 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002196}
2197
2198Error
2199Process::Attach (lldb::pid_t attach_pid)
2200{
2201
Chris Lattner24943d22010-06-08 16:52:24 +00002202 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002203 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002204
Greg Clayton75c703d2011-02-16 04:46:07 +00002205 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002206 m_os_ap.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002207
Greg Clayton54e7afa2010-07-09 20:39:50 +00002208 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00002209 if (error.Success())
2210 {
Greg Claytond8c62532010-10-07 04:19:01 +00002211 SetPublicState (eStateAttaching);
2212
Greg Clayton54e7afa2010-07-09 20:39:50 +00002213 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00002214 if (error.Success())
2215 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002216 SetNextEventAction(new Process::AttachCompletionHandler(this));
2217 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00002218 }
2219 else
2220 {
2221 if (GetID() != LLDB_INVALID_PROCESS_ID)
2222 {
2223 SetID (LLDB_INVALID_PROCESS_ID);
2224 const char *error_string = error.AsCString();
2225 if (error_string == NULL)
2226 error_string = "attach failed";
2227
2228 SetExitStatus(-1, error_string);
2229 }
2230 }
2231 }
2232 return error;
2233}
2234
2235Error
2236Process::Attach (const char *process_name, bool wait_for_launch)
2237{
Chris Lattner24943d22010-06-08 16:52:24 +00002238 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002239 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002240
2241 // Find the process and its architecture. Make sure it matches the architecture
2242 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002243 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00002244
Jim Inghamea294182010-08-17 21:54:19 +00002245 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00002246 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002247 ProcessInstanceInfoList process_infos;
Jim Ingham0d7f7772011-09-15 01:10:17 +00002248 PlatformSP platform_sp (m_target.GetPlatform ());
2249 assert (platform_sp.get());
2250
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002251 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00002252 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002253 ProcessInstanceInfoMatch match_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002254 match_info.GetProcessInfo().SetName(process_name);
2255 match_info.SetNameMatchType (eNameMatchEquals);
2256 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002257 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002258 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002259 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
2260 }
2261 else if (process_infos.GetSize() == 0)
2262 {
2263 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
2264 }
Chris Lattner24943d22010-06-08 16:52:24 +00002265 }
2266 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002267 {
2268 error.SetErrorString ("Invalid platform");
2269 }
2270 }
2271
2272 if (error.Success())
2273 {
2274 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002275 m_os_ap.reset();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002276
2277 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2278 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002279 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002280 SetPublicState (eStateAttaching);
2281 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2282 if (error.Fail())
2283 {
2284 if (GetID() != LLDB_INVALID_PROCESS_ID)
2285 {
2286 SetID (LLDB_INVALID_PROCESS_ID);
2287 const char *error_string = error.AsCString();
2288 if (error_string == NULL)
2289 error_string = "attach failed";
2290
2291 SetExitStatus(-1, error_string);
2292 }
2293 }
2294 else
2295 {
2296 SetNextEventAction(new Process::AttachCompletionHandler(this));
2297 StartPrivateStateThread();
2298 }
Chris Lattner24943d22010-06-08 16:52:24 +00002299 }
2300 }
2301 return error;
2302}
2303
Greg Clayton75c703d2011-02-16 04:46:07 +00002304void
2305Process::CompleteAttach ()
2306{
2307 // Let the process subclass figure out at much as it can about the process
2308 // before we go looking for a dynamic loader plug-in.
Jim Inghamc0c53242011-09-15 21:36:42 +00002309 m_attached_to_process = true;
Greg Clayton75c703d2011-02-16 04:46:07 +00002310 DidAttach();
2311
Jim Ingham0d7f7772011-09-15 01:10:17 +00002312 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2313 // the same as the one we've already set, switch architectures.
2314 PlatformSP platform_sp (m_target.GetPlatform ());
2315 assert (platform_sp.get());
2316 if (platform_sp)
2317 {
2318 ProcessInstanceInfo process_info;
2319 platform_sp->GetProcessInfo (GetID(), process_info);
2320 const ArchSpec &process_arch = process_info.GetArchitecture();
2321 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2322 m_target.SetArchitecture (process_arch);
2323 }
2324
2325 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002326 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00002327 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002328 if (m_dyld_ap.get())
2329 m_dyld_ap->DidAttach();
2330
Greg Clayton37f962e2011-08-22 02:49:39 +00002331 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002332 // Figure out which one is the executable, and set that in our target:
2333 ModuleList &modules = m_target.GetImages();
2334
2335 size_t num_modules = modules.GetSize();
2336 for (int i = 0; i < num_modules; i++)
2337 {
2338 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002339 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002340 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002341 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002342 m_target.SetExecutableModule (module_sp, false);
2343 break;
2344 }
2345 }
2346}
2347
Chris Lattner24943d22010-06-08 16:52:24 +00002348Error
Greg Claytone71e2582011-02-04 01:58:07 +00002349Process::ConnectRemote (const char *remote_url)
2350{
Greg Claytone71e2582011-02-04 01:58:07 +00002351 m_abi_sp.reset();
2352 m_process_input_reader.reset();
2353
2354 // Find the process and its architecture. Make sure it matches the architecture
2355 // of the current Target, and if not adjust it.
2356
2357 Error error (DoConnectRemote (remote_url));
2358 if (error.Success())
2359 {
Greg Claytona2f74232011-02-24 22:24:29 +00002360 if (GetID() != LLDB_INVALID_PROCESS_ID)
2361 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002362 EventSP event_sp;
2363 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2364
2365 if (state == eStateStopped || state == eStateCrashed)
2366 {
2367 // If we attached and actually have a process on the other end, then
2368 // this ended up being the equivalent of an attach.
2369 CompleteAttach ();
2370
2371 // This delays passing the stopped event to listeners till
2372 // CompleteAttach gets a chance to complete...
2373 HandlePrivateEvent (event_sp);
2374
2375 }
Greg Claytona2f74232011-02-24 22:24:29 +00002376 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002377
2378 if (PrivateStateThreadIsValid ())
2379 ResumePrivateStateThread ();
2380 else
2381 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002382 }
2383 return error;
2384}
2385
2386
2387Error
Chris Lattner24943d22010-06-08 16:52:24 +00002388Process::Resume ()
2389{
Greg Claytone005f2c2010-11-06 01:53:30 +00002390 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002391 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002392 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002393 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002394 StateAsCString(m_public_state.GetValue()),
2395 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002396
2397 Error error (WillResume());
2398 // Tell the process it is about to resume before the thread list
2399 if (error.Success())
2400 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002401 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002402 // can let all of our threads know that they are about to be
2403 // resumed. Threads will each be called with
2404 // Thread::WillResume(StateType) where StateType contains the state
2405 // that they are supposed to have when the process is resumed
2406 // (suspended/running/stepping). Threads should also check
2407 // their resume signal in lldb::Thread::GetResumeSignal()
2408 // to see if they are suppoed to start back up with a signal.
2409 if (m_thread_list.WillResume())
2410 {
2411 error = DoResume();
2412 if (error.Success())
2413 {
2414 DidResume();
2415 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002416 if (log)
2417 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002418 }
2419 }
2420 else
2421 {
Jim Inghamac959662011-01-24 06:34:17 +00002422 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002423 }
2424 }
Jim Inghamac959662011-01-24 06:34:17 +00002425 else if (log)
2426 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002427 return error;
2428}
2429
2430Error
2431Process::Halt ()
2432{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002433 // Pause our private state thread so we can ensure no one else eats
2434 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002435 Listener halt_listener ("lldb.process.halt_listener");
2436 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002437
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002438 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002439 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002440
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002441 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002442 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002443
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002444 bool caused_stop = false;
2445
2446 // Ask the process subclass to actually halt our process
2447 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002448 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002449 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002450 if (m_public_state.GetValue() == eStateAttaching)
2451 {
2452 SetExitStatus(SIGKILL, "Cancelled async attach.");
2453 Destroy ();
2454 }
2455 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002456 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002457 // If "caused_stop" is true, then DoHalt stopped the process. If
2458 // "caused_stop" is false, the process was already stopped.
2459 // If the DoHalt caused the process to stop, then we want to catch
2460 // this event and set the interrupted bool to true before we pass
2461 // this along so clients know that the process was interrupted by
2462 // a halt command.
2463 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002464 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002465 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002466 TimeValue timeout_time;
2467 timeout_time = TimeValue::Now();
2468 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002469 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2470 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002471
Jim Inghamf9f40c22011-02-08 05:20:59 +00002472 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002473 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002474 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002475 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002476 }
2477 else
2478 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002479 if (StateIsStoppedState (state))
2480 {
2481 // We caused the process to interrupt itself, so mark this
2482 // as such in the stop event so clients can tell an interrupted
2483 // process from a natural stop
2484 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2485 }
2486 else
2487 {
2488 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2489 if (log)
2490 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2491 error.SetErrorString ("Did not get stopped event after halt.");
2492 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002493 }
2494 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002495 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002496 }
2497 }
Chris Lattner24943d22010-06-08 16:52:24 +00002498 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002499 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002500 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002501
2502 // Post any event we might have consumed. If all goes well, we will have
2503 // stopped the process, intercepted the event and set the interrupted
2504 // bool in the event. Post it to the private event queue and that will end up
2505 // correctly setting the state.
2506 if (event_sp)
2507 m_private_state_broadcaster.BroadcastEvent(event_sp);
2508
Chris Lattner24943d22010-06-08 16:52:24 +00002509 return error;
2510}
2511
2512Error
2513Process::Detach ()
2514{
2515 Error error (WillDetach());
2516
2517 if (error.Success())
2518 {
2519 DisableAllBreakpointSites();
2520 error = DoDetach();
2521 if (error.Success())
2522 {
2523 DidDetach();
2524 StopPrivateStateThread();
2525 }
2526 }
2527 return error;
2528}
2529
2530Error
2531Process::Destroy ()
2532{
2533 Error error (WillDestroy());
2534 if (error.Success())
2535 {
2536 DisableAllBreakpointSites();
2537 error = DoDestroy();
2538 if (error.Success())
2539 {
2540 DidDestroy();
2541 StopPrivateStateThread();
2542 }
Caroline Tice861efb32010-11-16 05:07:41 +00002543 m_stdio_communication.StopReadThread();
2544 m_stdio_communication.Disconnect();
2545 if (m_process_input_reader && m_process_input_reader->IsActive())
2546 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2547 if (m_process_input_reader)
2548 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002549 }
2550 return error;
2551}
2552
2553Error
2554Process::Signal (int signal)
2555{
2556 Error error (WillSignal());
2557 if (error.Success())
2558 {
2559 error = DoSignal(signal);
2560 if (error.Success())
2561 DidSignal();
2562 }
2563 return error;
2564}
2565
Greg Clayton395fc332011-02-15 21:59:32 +00002566lldb::ByteOrder
2567Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002568{
Greg Clayton395fc332011-02-15 21:59:32 +00002569 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002570}
2571
2572uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002573Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002574{
Greg Clayton395fc332011-02-15 21:59:32 +00002575 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002576}
2577
Greg Clayton395fc332011-02-15 21:59:32 +00002578
Chris Lattner24943d22010-06-08 16:52:24 +00002579bool
2580Process::ShouldBroadcastEvent (Event *event_ptr)
2581{
2582 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2583 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002584 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002585
2586 switch (state)
2587 {
Greg Claytone71e2582011-02-04 01:58:07 +00002588 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002589 case eStateAttaching:
2590 case eStateLaunching:
2591 case eStateDetached:
2592 case eStateExited:
2593 case eStateUnloaded:
2594 // These events indicate changes in the state of the debugging session, always report them.
2595 return_value = true;
2596 break;
2597 case eStateInvalid:
2598 // We stopped for no apparent reason, don't report it.
2599 return_value = false;
2600 break;
2601 case eStateRunning:
2602 case eStateStepping:
2603 // If we've started the target running, we handle the cases where we
2604 // are already running and where there is a transition from stopped to
2605 // running differently.
2606 // running -> running: Automatically suppress extra running events
2607 // stopped -> running: Report except when there is one or more no votes
2608 // and no yes votes.
2609 SynchronouslyNotifyStateChanged (state);
2610 switch (m_public_state.GetValue())
2611 {
2612 case eStateRunning:
2613 case eStateStepping:
2614 // We always suppress multiple runnings with no PUBLIC stop in between.
2615 return_value = false;
2616 break;
2617 default:
2618 // TODO: make this work correctly. For now always report
2619 // run if we aren't running so we don't miss any runnning
2620 // events. If I run the lldb/test/thread/a.out file and
2621 // break at main.cpp:58, run and hit the breakpoints on
2622 // multiple threads, then somehow during the stepping over
2623 // of all breakpoints no run gets reported.
2624 return_value = true;
2625
2626 // This is a transition from stop to run.
2627 switch (m_thread_list.ShouldReportRun (event_ptr))
2628 {
2629 case eVoteYes:
2630 case eVoteNoOpinion:
2631 return_value = true;
2632 break;
2633 case eVoteNo:
2634 return_value = false;
2635 break;
2636 }
2637 break;
2638 }
2639 break;
2640 case eStateStopped:
2641 case eStateCrashed:
2642 case eStateSuspended:
2643 {
2644 // We've stopped. First see if we're going to restart the target.
2645 // If we are going to stop, then we always broadcast the event.
2646 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00002647 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002648 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002649 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002650 if (log)
2651 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002652 return true;
2653 }
2654 else
2655 {
Chris Lattner24943d22010-06-08 16:52:24 +00002656 RefreshStateAfterStop ();
2657
2658 if (m_thread_list.ShouldStop (event_ptr) == false)
2659 {
2660 switch (m_thread_list.ShouldReportStop (event_ptr))
2661 {
2662 case eVoteYes:
2663 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002664 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002665 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002666 case eVoteNo:
2667 return_value = false;
2668 break;
2669 }
2670
2671 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002672 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002673 Resume ();
2674 }
2675 else
2676 {
2677 return_value = true;
2678 SynchronouslyNotifyStateChanged (state);
2679 }
2680 }
2681 }
2682 }
2683
2684 if (log)
2685 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2686 return return_value;
2687}
2688
Chris Lattner24943d22010-06-08 16:52:24 +00002689
2690bool
2691Process::StartPrivateStateThread ()
2692{
Greg Claytone005f2c2010-11-06 01:53:30 +00002693 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002694
Greg Claytonb72d0f02011-04-12 05:54:46 +00002695 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00002696 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002697 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2698
2699 if (already_running)
2700 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00002701
2702 // Create a thread that watches our internal state and controls which
2703 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002704 char thread_name[1024];
2705 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2706 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002707 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002708}
2709
2710void
2711Process::PausePrivateStateThread ()
2712{
2713 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2714}
2715
2716void
2717Process::ResumePrivateStateThread ()
2718{
2719 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2720}
2721
2722void
2723Process::StopPrivateStateThread ()
2724{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002725 if (PrivateStateThreadIsValid ())
2726 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00002727}
2728
2729void
2730Process::ControlPrivateStateThread (uint32_t signal)
2731{
Greg Claytone005f2c2010-11-06 01:53:30 +00002732 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002733
2734 assert (signal == eBroadcastInternalStateControlStop ||
2735 signal == eBroadcastInternalStateControlPause ||
2736 signal == eBroadcastInternalStateControlResume);
2737
2738 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002739 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002740
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002741 // Signal the private state thread. First we should copy this is case the
2742 // thread starts exiting since the private state thread will NULL this out
2743 // when it exits
2744 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002745 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002746 {
2747 TimeValue timeout_time;
2748 bool timed_out;
2749
2750 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2751
2752 timeout_time = TimeValue::Now();
2753 timeout_time.OffsetWithSeconds(2);
2754 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2755 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2756
2757 if (signal == eBroadcastInternalStateControlStop)
2758 {
2759 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002760 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002761
2762 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002763 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002764 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002765 }
2766 }
2767}
2768
2769void
2770Process::HandlePrivateEvent (EventSP &event_sp)
2771{
Greg Claytone005f2c2010-11-06 01:53:30 +00002772 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002773
Greg Clayton68ca8232011-01-25 02:58:48 +00002774 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002775
2776 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002777 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002778 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002779 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002780 switch (action_result)
2781 {
2782 case NextEventAction::eEventActionSuccess:
2783 SetNextEventAction(NULL);
2784 break;
2785 case NextEventAction::eEventActionRetry:
2786 break;
2787 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002788 // Handle Exiting Here. If we already got an exited event,
2789 // we should just propagate it. Otherwise, swallow this event,
2790 // and set our state to exit so the next event will kill us.
2791 if (new_state != eStateExited)
2792 {
2793 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002794 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002795 SetNextEventAction(NULL);
2796 return;
2797 }
2798 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002799 break;
2800 }
2801 }
2802
Chris Lattner24943d22010-06-08 16:52:24 +00002803 // See if we should broadcast this state to external clients?
2804 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002805
2806 if (should_broadcast)
2807 {
2808 if (log)
2809 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002810 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2811 __FUNCTION__,
2812 GetID(),
2813 StateAsCString(new_state),
2814 StateAsCString (GetState ()),
2815 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002816 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00002817 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00002818 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002819 PushProcessInputReader ();
2820 else
2821 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00002822
Chris Lattner24943d22010-06-08 16:52:24 +00002823 BroadcastEvent (event_sp);
2824 }
2825 else
2826 {
2827 if (log)
2828 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002829 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2830 __FUNCTION__,
2831 GetID(),
2832 StateAsCString(new_state),
2833 StateAsCString (GetState ()),
2834 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002835 }
2836 }
2837}
2838
2839void *
2840Process::PrivateStateThread (void *arg)
2841{
2842 Process *proc = static_cast<Process*> (arg);
2843 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002844 return result;
2845}
2846
2847void *
2848Process::RunPrivateStateThread ()
2849{
2850 bool control_only = false;
2851 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2852
Greg Claytone005f2c2010-11-06 01:53:30 +00002853 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002854 if (log)
2855 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2856
2857 bool exit_now = false;
2858 while (!exit_now)
2859 {
2860 EventSP event_sp;
2861 WaitForEventsPrivate (NULL, event_sp, control_only);
2862 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2863 {
2864 switch (event_sp->GetType())
2865 {
2866 case eBroadcastInternalStateControlStop:
2867 exit_now = true;
2868 continue; // Go to next loop iteration so we exit without
2869 break; // doing any internal state managment below
2870
2871 case eBroadcastInternalStateControlPause:
2872 control_only = true;
2873 break;
2874
2875 case eBroadcastInternalStateControlResume:
2876 control_only = false;
2877 break;
2878 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002879
Jim Ingham3ae449a2010-11-17 02:32:00 +00002880 if (log)
2881 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2882
Chris Lattner24943d22010-06-08 16:52:24 +00002883 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002884 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002885 }
2886
2887
2888 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2889
2890 if (internal_state != eStateInvalid)
2891 {
2892 HandlePrivateEvent (event_sp);
2893 }
2894
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002895 if (internal_state == eStateInvalid ||
2896 internal_state == eStateExited ||
2897 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002898 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002899 if (log)
2900 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2901
Chris Lattner24943d22010-06-08 16:52:24 +00002902 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002903 }
Chris Lattner24943d22010-06-08 16:52:24 +00002904 }
2905
Caroline Tice926060e2010-10-29 21:48:37 +00002906 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002907 if (log)
2908 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2909
Greg Claytona4881d02011-01-22 07:12:45 +00002910 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2911 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002912 return NULL;
2913}
2914
Chris Lattner24943d22010-06-08 16:52:24 +00002915//------------------------------------------------------------------
2916// Process Event Data
2917//------------------------------------------------------------------
2918
2919Process::ProcessEventData::ProcessEventData () :
2920 EventData (),
2921 m_process_sp (),
2922 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002923 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002924 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002925 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002926{
2927}
2928
2929Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2930 EventData (),
2931 m_process_sp (process_sp),
2932 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002933 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002934 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002935 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002936{
2937}
2938
2939Process::ProcessEventData::~ProcessEventData()
2940{
2941}
2942
2943const ConstString &
2944Process::ProcessEventData::GetFlavorString ()
2945{
2946 static ConstString g_flavor ("Process::ProcessEventData");
2947 return g_flavor;
2948}
2949
2950const ConstString &
2951Process::ProcessEventData::GetFlavor () const
2952{
2953 return ProcessEventData::GetFlavorString ();
2954}
2955
Chris Lattner24943d22010-06-08 16:52:24 +00002956void
2957Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2958{
2959 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002960 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2961 // the public event queue, then other times when we're pretending that this is where we stopped at the
2962 // end of expression evaluation. m_update_state is used to distinguish these
2963 // three cases; it is 0 when we're just pulling it off for private handling,
2964 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00002965
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002966 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002967 return;
2968
2969 m_process_sp->SetPublicState (m_state);
2970
2971 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2972 if (m_state == eStateStopped && ! m_restarted)
2973 {
2974 int num_threads = m_process_sp->GetThreadList().GetSize();
2975 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002976
Jim Ingham21f37ad2011-08-09 02:12:22 +00002977 // The actions might change one of the thread's stop_info's opinions about whether we should
2978 // stop the process, so we need to query that as we go.
2979 bool still_should_stop = true;
2980
Chris Lattner24943d22010-06-08 16:52:24 +00002981 for (idx = 0; idx < num_threads; ++idx)
2982 {
2983 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2984
Jim Ingham6297a3a2010-10-20 00:39:53 +00002985 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2986 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002987 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002988 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00002989 // The stop action might restart the target. If it does, then we want to mark that in the
2990 // event so that whoever is receiving it will know to wait for the running event and reflect
2991 // that state appropriately.
2992 // We also need to stop processing actions, since they aren't expecting the target to be running.
2993 if (m_process_sp->GetPrivateState() == eStateRunning)
2994 {
2995 SetRestarted (true);
2996 break;
2997 }
2998 else if (!stop_info_sp->ShouldStop(event_ptr))
2999 {
3000 still_should_stop = false;
3001 }
Chris Lattner24943d22010-06-08 16:52:24 +00003002 }
3003 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003004
Jim Ingham21f37ad2011-08-09 02:12:22 +00003005
3006 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003007 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003008 if (!still_should_stop)
3009 {
3010 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003011 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003012 m_process_sp->Resume();
3013 }
3014 else
3015 {
3016 // If we didn't restart, run the Stop Hooks here:
3017 // They might also restart the target, so watch for that.
3018 m_process_sp->GetTarget().RunStopHooks();
3019 if (m_process_sp->GetPrivateState() == eStateRunning)
3020 SetRestarted(true);
3021 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003022 }
3023
Chris Lattner24943d22010-06-08 16:52:24 +00003024 }
3025}
3026
3027void
3028Process::ProcessEventData::Dump (Stream *s) const
3029{
3030 if (m_process_sp)
3031 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
3032
Greg Claytonb72d0f02011-04-12 05:54:46 +00003033 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003034}
3035
3036const Process::ProcessEventData *
3037Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3038{
3039 if (event_ptr)
3040 {
3041 const EventData *event_data = event_ptr->GetData();
3042 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3043 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3044 }
3045 return NULL;
3046}
3047
3048ProcessSP
3049Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3050{
3051 ProcessSP process_sp;
3052 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3053 if (data)
3054 process_sp = data->GetProcessSP();
3055 return process_sp;
3056}
3057
3058StateType
3059Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3060{
3061 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3062 if (data == NULL)
3063 return eStateInvalid;
3064 else
3065 return data->GetState();
3066}
3067
3068bool
3069Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3070{
3071 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3072 if (data == NULL)
3073 return false;
3074 else
3075 return data->GetRestarted();
3076}
3077
3078void
3079Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3080{
3081 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3082 if (data != NULL)
3083 data->SetRestarted(new_value);
3084}
3085
3086bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003087Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3088{
3089 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3090 if (data == NULL)
3091 return false;
3092 else
3093 return data->GetInterrupted ();
3094}
3095
3096void
3097Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3098{
3099 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3100 if (data != NULL)
3101 data->SetInterrupted(new_value);
3102}
3103
3104bool
Chris Lattner24943d22010-06-08 16:52:24 +00003105Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3106{
3107 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3108 if (data)
3109 {
3110 data->SetUpdateStateOnRemoval();
3111 return true;
3112 }
3113 return false;
3114}
3115
Chris Lattner24943d22010-06-08 16:52:24 +00003116void
Greg Claytona830adb2010-10-04 01:05:56 +00003117Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003118{
3119 exe_ctx.target = &m_target;
3120 exe_ctx.process = this;
3121 exe_ctx.thread = NULL;
3122 exe_ctx.frame = NULL;
3123}
3124
3125lldb::ProcessSP
3126Process::GetSP ()
3127{
3128 return GetTarget().GetProcessSP();
3129}
3130
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003131//uint32_t
3132//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3133//{
3134// return 0;
3135//}
3136//
3137//ArchSpec
3138//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3139//{
3140// return Host::GetArchSpecForExistingProcess (pid);
3141//}
3142//
3143//ArchSpec
3144//Process::GetArchSpecForExistingProcess (const char *process_name)
3145//{
3146// return Host::GetArchSpecForExistingProcess (process_name);
3147//}
3148//
Caroline Tice861efb32010-11-16 05:07:41 +00003149void
3150Process::AppendSTDOUT (const char * s, size_t len)
3151{
Greg Clayton20d338f2010-11-18 05:57:03 +00003152 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003153 m_stdout_data.append (s, len);
3154
Greg Claytonb3781332010-12-05 19:16:56 +00003155 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003156}
3157
3158void
3159Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3160{
3161 Process *process = (Process *) baton;
3162 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3163}
3164
3165size_t
3166Process::ProcessInputReaderCallback (void *baton,
3167 InputReader &reader,
3168 lldb::InputReaderAction notification,
3169 const char *bytes,
3170 size_t bytes_len)
3171{
3172 Process *process = (Process *) baton;
3173
3174 switch (notification)
3175 {
3176 case eInputReaderActivate:
3177 break;
3178
3179 case eInputReaderDeactivate:
3180 break;
3181
3182 case eInputReaderReactivate:
3183 break;
3184
Caroline Tice4a348082011-05-02 20:41:46 +00003185 case eInputReaderAsynchronousOutputWritten:
3186 break;
3187
Caroline Tice861efb32010-11-16 05:07:41 +00003188 case eInputReaderGotToken:
3189 {
3190 Error error;
3191 process->PutSTDIN (bytes, bytes_len, error);
3192 }
3193 break;
3194
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003195 case eInputReaderInterrupt:
3196 process->Halt ();
3197 break;
3198
3199 case eInputReaderEndOfFile:
3200 process->AppendSTDOUT ("^D", 2);
3201 break;
3202
Caroline Tice861efb32010-11-16 05:07:41 +00003203 case eInputReaderDone:
3204 break;
3205
3206 }
3207
3208 return bytes_len;
3209}
3210
3211void
3212Process::ResetProcessInputReader ()
3213{
3214 m_process_input_reader.reset();
3215}
3216
3217void
3218Process::SetUpProcessInputReader (int file_descriptor)
3219{
3220 // First set up the Read Thread for reading/handling process I/O
3221
3222 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3223
3224 if (conn_ap.get())
3225 {
3226 m_stdio_communication.SetConnection (conn_ap.release());
3227 if (m_stdio_communication.IsConnected())
3228 {
3229 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3230 m_stdio_communication.StartReadThread();
3231
3232 // Now read thread is set up, set up input reader.
3233
3234 if (!m_process_input_reader.get())
3235 {
3236 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3237 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3238 this,
3239 eInputReaderGranularityByte,
3240 NULL,
3241 NULL,
3242 false));
3243
3244 if (err.Fail())
3245 m_process_input_reader.reset();
3246 }
3247 }
3248 }
3249}
3250
3251void
3252Process::PushProcessInputReader ()
3253{
3254 if (m_process_input_reader && !m_process_input_reader->IsActive())
3255 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3256}
3257
3258void
3259Process::PopProcessInputReader ()
3260{
3261 if (m_process_input_reader && m_process_input_reader->IsActive())
3262 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3263}
3264
Greg Claytond284b662011-02-18 01:44:25 +00003265// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003266void
Caroline Tice2a456812011-03-10 22:14:10 +00003267Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003268{
Greg Claytonb3448432011-03-24 21:19:54 +00003269 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003270
3271 int i=0;
3272 const char *name;
3273 OptionEnumValueElement option_enum;
3274 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3275 {
3276 if (name)
3277 {
3278 option_enum.value = i;
3279 option_enum.string_value = name;
3280 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3281 g_plugins.push_back (option_enum);
3282 }
3283 ++i;
3284 }
3285 option_enum.value = 0;
3286 option_enum.string_value = NULL;
3287 option_enum.usage = NULL;
3288 g_plugins.push_back (option_enum);
3289
3290 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3291 {
3292 if (::strcmp (name, "plugin") == 0)
3293 {
3294 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3295 break;
3296 }
3297 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003298 UserSettingsControllerSP &usc = GetSettingsController();
3299 usc.reset (new SettingsController);
3300 UserSettingsController::InitializeSettingsController (usc,
3301 SettingsController::global_settings_table,
3302 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003303
3304 // Now call SettingsInitialize() for each 'child' of Process settings
3305 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003306}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003307
Greg Clayton990de7b2010-11-18 23:32:35 +00003308void
Caroline Tice2a456812011-03-10 22:14:10 +00003309Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003310{
Caroline Tice2a456812011-03-10 22:14:10 +00003311 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3312
3313 Thread::SettingsTerminate ();
3314
3315 // Now terminate Process Settings.
3316
Greg Clayton990de7b2010-11-18 23:32:35 +00003317 UserSettingsControllerSP &usc = GetSettingsController();
3318 UserSettingsController::FinalizeSettingsController (usc);
3319 usc.reset();
3320}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003321
Greg Clayton990de7b2010-11-18 23:32:35 +00003322UserSettingsControllerSP &
3323Process::GetSettingsController ()
3324{
3325 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003326 return g_settings_controller;
3327}
3328
Caroline Tice1ebef442010-09-27 00:30:10 +00003329void
3330Process::UpdateInstanceName ()
3331{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003332 Module *module = GetTarget().GetExecutableModulePointer();
3333 if (module)
Caroline Tice1ebef442010-09-27 00:30:10 +00003334 {
3335 StreamString sstr;
Greg Clayton5beb99d2011-08-11 02:48:45 +00003336 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003337
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003338 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytonb72d0f02011-04-12 05:54:46 +00003339 sstr.GetData());
Caroline Tice1ebef442010-09-27 00:30:10 +00003340 }
3341}
3342
Greg Clayton427f2902010-12-14 02:59:59 +00003343ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003344Process::RunThreadPlan (ExecutionContext &exe_ctx,
3345 lldb::ThreadPlanSP &thread_plan_sp,
3346 bool stop_others,
3347 bool try_all_threads,
3348 bool discard_on_error,
3349 uint32_t single_thread_timeout_usec,
3350 Stream &errors)
3351{
3352 ExecutionResults return_value = eExecutionSetupError;
3353
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003354 if (thread_plan_sp.get() == NULL)
3355 {
3356 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003357 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003358 }
3359
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003360 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3361 // For that to be true the plan can't be private - since private plans suppress themselves in the
3362 // GetCompletedPlan call.
3363
3364 bool orig_plan_private = thread_plan_sp->GetPrivate();
3365 thread_plan_sp->SetPrivate(false);
3366
Jim Inghamac959662011-01-24 06:34:17 +00003367 if (m_private_state.GetValue() != eStateStopped)
3368 {
3369 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003370 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003371 }
3372
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003373 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton265ab332011-05-19 18:17:41 +00003374 const uint32_t thread_idx_id = exe_ctx.thread->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003375 StackID ctx_frame_id = exe_ctx.thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003376
3377 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3378 // so we should arrange to reset them as well.
3379
3380 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003381
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003382 uint32_t selected_tid;
3383 StackID selected_stack_id;
Jim Ingham360f53f2010-11-30 02:22:11 +00003384 if (selected_thread_sp != NULL)
3385 {
3386 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003387 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003388 }
3389 else
3390 {
3391 selected_tid = LLDB_INVALID_THREAD_ID;
3392 }
3393
3394 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
3395
Jim Ingham6ae318c2011-01-23 21:14:08 +00003396 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003397
3398 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3399 // restored on exit to the function.
3400
3401 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003402
Jim Ingham6ae318c2011-01-23 21:14:08 +00003403 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003404 if (log)
3405 {
3406 StreamString s;
3407 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003408 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
3409 exe_ctx.thread->GetIndexID(),
3410 exe_ctx.thread->GetID(),
3411 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003412 }
3413
Jim Inghamf9f40c22011-02-08 05:20:59 +00003414 bool got_event;
3415 lldb::EventSP event_sp;
3416 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003417
3418 TimeValue* timeout_ptr = NULL;
3419 TimeValue real_timeout;
3420
Jim Inghamf9f40c22011-02-08 05:20:59 +00003421 bool first_timeout = true;
3422 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003423
Jim Ingham360f53f2010-11-30 02:22:11 +00003424 while (1)
3425 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003426 // We usually want to resume the process if we get to the top of the loop.
3427 // The only exception is if we get two running events with no intervening
3428 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003429
Jim Inghamf9f40c22011-02-08 05:20:59 +00003430 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003431 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003432 // Do the initial resume and wait for the running event before going further.
3433
3434 Error resume_error = exe_ctx.process->Resume ();
3435 if (!resume_error.Success())
3436 {
3437 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003438 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003439 break;
3440 }
3441
3442 real_timeout = TimeValue::Now();
3443 real_timeout.OffsetWithMicroSeconds(500000);
3444 timeout_ptr = &real_timeout;
3445
3446 got_event = listener.WaitForEvent(NULL, event_sp);
3447 if (!got_event)
3448 {
3449 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003450 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003451
3452 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003453 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003454 break;
3455 }
3456
3457 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3458 if (stop_state != eStateRunning)
3459 {
3460 if (log)
3461 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3462
3463 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003464 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003465 break;
3466 }
3467
3468 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003469 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003470 // We need to call the function synchronously, so spin waiting for it to return.
3471 // If we get interrupted while executing, we're going to lose our context, and
3472 // won't be able to gather the result at this point.
3473 // We set the timeout AFTER the resume, since the resume takes some time and we
3474 // don't want to charge that to the timeout.
3475
3476 if (single_thread_timeout_usec != 0)
3477 {
3478 real_timeout = TimeValue::Now();
3479 if (first_timeout)
3480 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3481 else
3482 real_timeout.OffsetWithSeconds(10);
3483
3484 timeout_ptr = &real_timeout;
3485 }
3486 }
3487 else
3488 {
3489 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003490 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003491 do_resume = true;
3492 }
3493
3494 // Now wait for the process to stop again:
3495 stop_state = lldb::eStateInvalid;
3496 event_sp.reset();
3497 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3498
3499 if (got_event)
3500 {
3501 if (event_sp.get())
3502 {
3503 bool keep_going = false;
3504 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3505 if (log)
3506 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3507
3508 switch (stop_state)
3509 {
3510 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00003511 {
Greg Clayton43994462011-06-03 22:12:42 +00003512 // Yay, we're done. Now make sure that our thread plan actually completed.
3513 ThreadSP thread_sp = exe_ctx.process->GetThreadList().FindThreadByIndexID (thread_idx_id);
3514 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00003515 {
Greg Clayton43994462011-06-03 22:12:42 +00003516 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00003517 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00003518 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3519 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00003520 }
3521 else
3522 {
Greg Clayton43994462011-06-03 22:12:42 +00003523 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3524 StopReason stop_reason = eStopReasonInvalid;
3525 if (stop_info_sp)
3526 stop_reason = stop_info_sp->GetStopReason();
3527 if (stop_reason == eStopReasonPlanComplete)
3528 {
3529 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003530 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00003531 // Now mark this plan as private so it doesn't get reported as the stop reason
3532 // after this point.
3533 if (thread_plan_sp)
3534 thread_plan_sp->SetPrivate (orig_plan_private);
3535 return_value = eExecutionCompleted;
3536 }
3537 else
3538 {
3539 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003540 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00003541
3542 return_value = eExecutionInterrupted;
3543 }
Jim Ingham2370a972011-05-17 01:10:11 +00003544 }
Greg Clayton43994462011-06-03 22:12:42 +00003545 }
3546 break;
3547
Jim Inghamf9f40c22011-02-08 05:20:59 +00003548 case lldb::eStateCrashed:
3549 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003550 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003551 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003552 break;
Greg Clayton43994462011-06-03 22:12:42 +00003553
Jim Inghamf9f40c22011-02-08 05:20:59 +00003554 case lldb::eStateRunning:
3555 do_resume = false;
3556 keep_going = true;
3557 break;
Greg Clayton43994462011-06-03 22:12:42 +00003558
Jim Inghamf9f40c22011-02-08 05:20:59 +00003559 default:
3560 if (log)
3561 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00003562
3563 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00003564 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003565 break;
3566 }
3567 if (keep_going)
3568 continue;
3569 else
3570 break;
3571 }
3572 else
3573 {
3574 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003575 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003576 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003577 break;
3578 }
3579 }
3580 else
3581 {
3582 // If we didn't get an event that means we've timed out...
3583 // We will interrupt the process here. Depending on what we were asked to do we will
3584 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003585 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003586
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003587 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003588 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003589 {
3590 if (first_timeout)
3591 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3592 "trying with all threads enabled.",
3593 single_thread_timeout_usec);
3594 else
3595 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3596 "and timeout: %d timed out.",
3597 single_thread_timeout_usec);
3598 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003599 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003600 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3601 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003602 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003603 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003604
Jim Inghamc556b462011-01-22 01:30:53 +00003605 Error halt_error = exe_ctx.process->Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003606 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003607 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003608 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003609 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003610
Jim Inghamf9f40c22011-02-08 05:20:59 +00003611 // If halt succeeds, it always produces a stopped event. Wait for that:
3612
3613 real_timeout = TimeValue::Now();
3614 real_timeout.OffsetWithMicroSeconds(500000);
3615
3616 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003617
3618 if (got_event)
3619 {
3620 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3621 if (log)
3622 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003623 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003624 if (stop_state == lldb::eStateStopped
3625 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00003626 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003627 }
3628
Jim Inghamf9f40c22011-02-08 05:20:59 +00003629 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003630 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003631 // Between the time we initiated the Halt and the time we delivered it, the process could have
3632 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003633
Jim Inghamf9f40c22011-02-08 05:20:59 +00003634 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3635 {
3636 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003637 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003638 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003639 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003640 break;
3641 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003642
Jim Inghamf9f40c22011-02-08 05:20:59 +00003643 if (!try_all_threads)
3644 {
3645 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003646 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003647 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003648 break;
3649 }
3650
3651 if (first_timeout)
3652 {
3653 // Set all the other threads to run, and return to the top of the loop, which will continue;
3654 first_timeout = false;
3655 thread_plan_sp->SetStopOthers (false);
3656 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003657 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003658
3659 continue;
3660 }
3661 else
3662 {
3663 // Running all threads failed, so return Interrupted.
3664 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003665 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003666 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003667 break;
3668 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003669 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003670 }
3671 else
3672 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003673 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003674 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00003675 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003676 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003677 }
3678 }
Jim Inghamc556b462011-01-22 01:30:53 +00003679 else
3680 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003681 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3682 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003683 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003684 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.",
3685 halt_error.AsCString());
3686 real_timeout = TimeValue::Now();
3687 real_timeout.OffsetWithMicroSeconds(500000);
3688 timeout_ptr = &real_timeout;
3689 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3690 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003691 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003692 // This is not going anywhere, bag out.
3693 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003694 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003695 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003696 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003697 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003698 else
3699 {
3700 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3701 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003702 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003703 if (stop_state == lldb::eStateStopped)
3704 {
3705 // Between the time we initiated the Halt and the time we delivered it, the process could have
3706 // already finished its job. Check that here:
3707
3708 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3709 {
3710 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003711 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003712 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003713 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003714 break;
3715 }
3716
3717 if (first_timeout)
3718 {
3719 // Set all the other threads to run, and return to the top of the loop, which will continue;
3720 first_timeout = false;
3721 thread_plan_sp->SetStopOthers (false);
3722 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003723 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003724
3725 continue;
3726 }
3727 else
3728 {
3729 // Running all threads failed, so return Interrupted.
3730 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003731 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003732 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003733 break;
3734 }
3735 }
3736 else
3737 {
Sean Callananed3f86b2011-08-09 22:07:08 +00003738 if (log)
3739 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3740 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003741 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003742 break;
3743 }
3744 }
Jim Inghamc556b462011-01-22 01:30:53 +00003745 }
3746
Jim Ingham360f53f2010-11-30 02:22:11 +00003747 }
3748
Jim Inghamf9f40c22011-02-08 05:20:59 +00003749 } // END WAIT LOOP
3750
3751 // Now do some processing on the results of the run:
3752 if (return_value == eExecutionInterrupted)
3753 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003754 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003755 {
3756 StreamString s;
3757 if (event_sp)
3758 event_sp->Dump (&s);
3759 else
3760 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00003761 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003762 }
3763
3764 StreamString ts;
3765
Jim Inghamf6d3d792011-08-09 22:24:33 +00003766 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003767
3768 do
3769 {
3770 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3771
3772 if (!event_data)
3773 {
3774 event_explanation = "<no event data>";
3775 break;
3776 }
3777
3778 Process *process = event_data->GetProcessSP().get();
3779
3780 if (!process)
3781 {
3782 event_explanation = "<no process>";
3783 break;
3784 }
3785
3786 ThreadList &thread_list = process->GetThreadList();
3787
3788 uint32_t num_threads = thread_list.GetSize();
3789 uint32_t thread_index;
3790
3791 ts.Printf("<%u threads> ", num_threads);
3792
3793 for (thread_index = 0;
3794 thread_index < num_threads;
3795 ++thread_index)
3796 {
3797 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3798
3799 if (!thread)
3800 {
3801 ts.Printf("<?> ");
3802 continue;
3803 }
3804
3805 ts.Printf("<0x%4.4x ", thread->GetID());
3806 RegisterContext *register_context = thread->GetRegisterContext().get();
3807
3808 if (register_context)
3809 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3810 else
3811 ts.Printf("[ip unknown] ");
3812
3813 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3814 if (stop_info_sp)
3815 {
3816 const char *stop_desc = stop_info_sp->GetDescription();
3817 if (stop_desc)
3818 ts.PutCString (stop_desc);
3819 }
3820 ts.Printf(">");
3821 }
3822
3823 event_explanation = ts.GetData();
3824 } while (0);
3825
3826 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003827 {
3828 if (event_explanation)
3829 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3830 else
3831 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3832 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003833
3834 if (discard_on_error && thread_plan_sp)
3835 {
3836 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003837 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003838 }
3839 }
3840 }
3841 else if (return_value == eExecutionSetupError)
3842 {
3843 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003844 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003845
3846 if (discard_on_error && thread_plan_sp)
3847 {
3848 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003849 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003850 }
3851 }
3852 else
3853 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003854 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3855 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003856 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003857 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00003858 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003859 }
3860 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3861 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003862 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003863 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00003864 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003865 }
3866 else
3867 {
3868 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003869 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003870 if (discard_on_error && thread_plan_sp)
3871 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003872 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003873 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003874 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003875 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00003876 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003877 }
3878 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003879
Jim Ingham360f53f2010-11-30 02:22:11 +00003880 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003881 // Check that it's still there, and if it is put it back in the context. Also restore the
3882 // frame in the context if it is still present.
Greg Clayton265ab332011-05-19 18:17:41 +00003883 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
Jim Ingham360f53f2010-11-30 02:22:11 +00003884 if (exe_ctx.thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003885 {
3886 exe_ctx.frame = exe_ctx.thread->GetFrameWithStackID (ctx_frame_id).get();
3887 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003888
3889 // Also restore the current process'es selected frame & thread, since this function calling may
3890 // be done behind the user's back.
3891
3892 if (selected_tid != LLDB_INVALID_THREAD_ID)
3893 {
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003894 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00003895 {
3896 // We were able to restore the selected thread, now restore the frame:
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003897 StackFrameSP old_frame_sp = exe_ctx.process->GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
3898 if (old_frame_sp)
3899 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00003900 }
3901 }
3902
3903 return return_value;
3904}
3905
3906const char *
3907Process::ExecutionResultAsCString (ExecutionResults result)
3908{
3909 const char *result_name;
3910
3911 switch (result)
3912 {
Greg Claytonb3448432011-03-24 21:19:54 +00003913 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003914 result_name = "eExecutionCompleted";
3915 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003916 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003917 result_name = "eExecutionDiscarded";
3918 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003919 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003920 result_name = "eExecutionInterrupted";
3921 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003922 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003923 result_name = "eExecutionSetupError";
3924 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003925 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003926 result_name = "eExecutionTimedOut";
3927 break;
3928 }
3929 return result_name;
3930}
3931
Greg Claytonabe0fed2011-04-18 08:33:37 +00003932void
3933Process::GetStatus (Stream &strm)
3934{
3935 const StateType state = GetState();
3936 if (StateIsStoppedState(state))
3937 {
3938 if (state == eStateExited)
3939 {
3940 int exit_status = GetExitStatus();
3941 const char *exit_description = GetExitDescription();
3942 strm.Printf ("Process %d exited with status = %i (0x%8.8x) %s\n",
3943 GetID(),
3944 exit_status,
3945 exit_status,
3946 exit_description ? exit_description : "");
3947 }
3948 else
3949 {
3950 if (state == eStateConnected)
3951 strm.Printf ("Connected to remote target.\n");
3952 else
3953 strm.Printf ("Process %d %s\n", GetID(), StateAsCString (state));
3954 }
3955 }
3956 else
3957 {
3958 strm.Printf ("Process %d is running.\n", GetID());
3959 }
3960}
3961
3962size_t
3963Process::GetThreadStatus (Stream &strm,
3964 bool only_threads_with_stop_reason,
3965 uint32_t start_frame,
3966 uint32_t num_frames,
3967 uint32_t num_frames_with_source)
3968{
3969 size_t num_thread_infos_dumped = 0;
3970
3971 const size_t num_threads = GetThreadList().GetSize();
3972 for (uint32_t i = 0; i < num_threads; i++)
3973 {
3974 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
3975 if (thread)
3976 {
3977 if (only_threads_with_stop_reason)
3978 {
3979 if (thread->GetStopInfo().get() == NULL)
3980 continue;
3981 }
3982 thread->GetStatus (strm,
3983 start_frame,
3984 num_frames,
3985 num_frames_with_source);
3986 ++num_thread_infos_dumped;
3987 }
3988 }
3989 return num_thread_infos_dumped;
3990}
3991
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003992//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003993// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003994//--------------------------------------------------------------
3995
Greg Claytond0a5a232010-09-19 02:33:57 +00003996Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00003997 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003998{
Greg Clayton638351a2010-12-04 00:10:17 +00003999 m_default_settings.reset (new ProcessInstanceSettings (*this,
4000 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00004001 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004002}
4003
Greg Claytond0a5a232010-09-19 02:33:57 +00004004Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004005{
4006}
4007
4008lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004009Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004010{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004011 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4012 false,
4013 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004014 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4015 return new_settings_sp;
4016}
4017
4018//--------------------------------------------------------------
4019// class ProcessInstanceSettings
4020//--------------------------------------------------------------
4021
Greg Clayton638351a2010-12-04 00:10:17 +00004022ProcessInstanceSettings::ProcessInstanceSettings
4023(
4024 UserSettingsController &owner,
4025 bool live_instance,
4026 const char *name
4027) :
4028 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004029 m_run_args (),
4030 m_env_vars (),
4031 m_input_path (),
4032 m_output_path (),
4033 m_error_path (),
Caroline Ticebd666012010-12-03 18:46:09 +00004034 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00004035 m_disable_stdio (false),
4036 m_inherit_host_env (true),
4037 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004038{
Caroline Tice396704b2010-09-09 18:26:37 +00004039 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4040 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4041 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00004042 // This is true for CreateInstanceName() too.
4043
4044 if (GetInstanceName () == InstanceSettings::InvalidName())
4045 {
4046 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4047 m_owner.RegisterInstanceSettings (this);
4048 }
Caroline Tice396704b2010-09-09 18:26:37 +00004049
4050 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004051 {
4052 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4053 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00004054 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004055 }
4056}
4057
4058ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004059 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004060 m_run_args (rhs.m_run_args),
4061 m_env_vars (rhs.m_env_vars),
4062 m_input_path (rhs.m_input_path),
4063 m_output_path (rhs.m_output_path),
4064 m_error_path (rhs.m_error_path),
Caroline Ticebd666012010-12-03 18:46:09 +00004065 m_disable_aslr (rhs.m_disable_aslr),
4066 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004067{
4068 if (m_instance_name != InstanceSettings::GetDefaultName())
4069 {
4070 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4071 CopyInstanceSettings (pending_settings,false);
4072 m_owner.RemovePendingSettings (m_instance_name);
4073 }
4074}
4075
4076ProcessInstanceSettings::~ProcessInstanceSettings ()
4077{
4078}
4079
4080ProcessInstanceSettings&
4081ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4082{
4083 if (this != &rhs)
4084 {
4085 m_run_args = rhs.m_run_args;
4086 m_env_vars = rhs.m_env_vars;
4087 m_input_path = rhs.m_input_path;
4088 m_output_path = rhs.m_output_path;
4089 m_error_path = rhs.m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004090 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00004091 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00004092 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004093 }
4094
4095 return *this;
4096}
4097
4098
4099void
4100ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4101 const char *index_value,
4102 const char *value,
4103 const ConstString &instance_name,
4104 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004105 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004106 Error &err,
4107 bool pending)
4108{
4109 if (var_name == RunArgsVarName())
4110 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
4111 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00004112 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00004113 // This is nice for local debugging, but it is isn't correct for
4114 // remote debugging. We need to stop process.env-vars from being
4115 // populated with the host environment and add this as a launch option
4116 // and get the correct environment from the Target's platform.
4117 // GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004118 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00004119 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004120 else if (var_name == InputPathVarName())
4121 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
4122 else if (var_name == OutputPathVarName())
4123 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
4124 else if (var_name == ErrorPathVarName())
4125 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004126 else if (var_name == DisableASLRVarName())
Greg Clayton17cd9952011-04-22 03:55:06 +00004127 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
Caroline Ticebd666012010-12-03 18:46:09 +00004128 else if (var_name == DisableSTDIOVarName ())
Greg Clayton17cd9952011-04-22 03:55:06 +00004129 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004130}
4131
4132void
4133ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4134 bool pending)
4135{
4136 if (new_settings.get() == NULL)
4137 return;
4138
4139 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4140
4141 m_run_args = new_process_settings->m_run_args;
4142 m_env_vars = new_process_settings->m_env_vars;
4143 m_input_path = new_process_settings->m_input_path;
4144 m_output_path = new_process_settings->m_output_path;
4145 m_error_path = new_process_settings->m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004146 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00004147 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004148}
4149
Caroline Ticebcb5b452010-09-20 21:37:42 +00004150bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004151ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4152 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004153 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004154 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004155{
4156 if (var_name == RunArgsVarName())
4157 {
4158 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00004159 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004160 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4161 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00004162 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004163 }
4164 else if (var_name == EnvVarsVarName())
4165 {
Greg Clayton638351a2010-12-04 00:10:17 +00004166 GetHostEnvironmentIfNeeded ();
4167
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004168 if (m_env_vars.size() > 0)
4169 {
4170 std::map<std::string, std::string>::iterator pos;
4171 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4172 {
4173 StreamString value_str;
4174 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4175 value.AppendString (value_str.GetData());
4176 }
4177 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004178 }
4179 else if (var_name == InputPathVarName())
4180 {
4181 value.AppendString (m_input_path.c_str());
4182 }
4183 else if (var_name == OutputPathVarName())
4184 {
4185 value.AppendString (m_output_path.c_str());
4186 }
4187 else if (var_name == ErrorPathVarName())
4188 {
4189 value.AppendString (m_error_path.c_str());
4190 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00004191 else if (var_name == InheritHostEnvVarName())
4192 {
4193 if (m_inherit_host_env)
4194 value.AppendString ("true");
4195 else
4196 value.AppendString ("false");
4197 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004198 else if (var_name == DisableASLRVarName())
4199 {
4200 if (m_disable_aslr)
4201 value.AppendString ("true");
4202 else
4203 value.AppendString ("false");
4204 }
Caroline Ticebd666012010-12-03 18:46:09 +00004205 else if (var_name == DisableSTDIOVarName())
4206 {
4207 if (m_disable_stdio)
4208 value.AppendString ("true");
4209 else
4210 value.AppendString ("false");
4211 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004212 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00004213 {
4214 if (err)
4215 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4216 return false;
4217 }
4218 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004219}
4220
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004221const ConstString
4222ProcessInstanceSettings::CreateInstanceName ()
4223{
4224 static int instance_count = 1;
4225 StreamString sstr;
4226
4227 sstr.Printf ("process_%d", instance_count);
4228 ++instance_count;
4229
4230 const ConstString ret_val (sstr.GetData());
4231 return ret_val;
4232}
4233
4234const ConstString &
4235ProcessInstanceSettings::RunArgsVarName ()
4236{
4237 static ConstString run_args_var_name ("run-args");
4238
4239 return run_args_var_name;
4240}
4241
4242const ConstString &
4243ProcessInstanceSettings::EnvVarsVarName ()
4244{
4245 static ConstString env_vars_var_name ("env-vars");
4246
4247 return env_vars_var_name;
4248}
4249
4250const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00004251ProcessInstanceSettings::InheritHostEnvVarName ()
4252{
4253 static ConstString g_name ("inherit-env");
4254
4255 return g_name;
4256}
4257
4258const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004259ProcessInstanceSettings::InputPathVarName ()
4260{
4261 static ConstString input_path_var_name ("input-path");
4262
4263 return input_path_var_name;
4264}
4265
4266const ConstString &
4267ProcessInstanceSettings::OutputPathVarName ()
4268{
Caroline Tice87097232010-09-07 18:35:40 +00004269 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004270
4271 return output_path_var_name;
4272}
4273
4274const ConstString &
4275ProcessInstanceSettings::ErrorPathVarName ()
4276{
Caroline Tice87097232010-09-07 18:35:40 +00004277 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004278
4279 return error_path_var_name;
4280}
4281
4282const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004283ProcessInstanceSettings::DisableASLRVarName ()
4284{
4285 static ConstString disable_aslr_var_name ("disable-aslr");
4286
4287 return disable_aslr_var_name;
4288}
4289
Caroline Ticebd666012010-12-03 18:46:09 +00004290const ConstString &
4291ProcessInstanceSettings::DisableSTDIOVarName ()
4292{
4293 static ConstString disable_stdio_var_name ("disable-stdio");
4294
4295 return disable_stdio_var_name;
4296}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004297
4298//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004299// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004300//--------------------------------------------------
4301
4302SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004303Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004304{
4305 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4306 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4307};
4308
4309
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004310SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004311Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004312{
Greg Clayton638351a2010-12-04 00:10:17 +00004313 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
4314 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
4315 { "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." },
4316 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00004317 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
4318 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
4319 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytond284b662011-02-18 01:44:25 +00004320 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00004321 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
4322 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
4323 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004324};
4325
4326
Jim Ingham7508e732010-08-09 23:31:02 +00004327