blob: 384f9e841200382c42651359104c87481d9daa3c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton32e0a752011-03-30 18:16:51 +000043void
Greg Clayton8b82f082011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
48 s.Printf (" pid = %i\n", m_pid);
49
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
51 s.Printf (" parent = %i\n", m_parent_pid);
52
53 if (m_executable)
54 {
55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
56 s.PutCString (" file = ");
57 m_executable.Dump(&s);
58 s.EOL();
59 }
Greg Clayton8b82f082011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Clayton8b82f082011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000066 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000068 else
Greg Clayton8b82f082011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000070 }
71 }
Greg Clayton8b82f082011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Clayton95bf0fd2011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Clayton8b82f082011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000090 {
Greg Clayton8b82f082011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000093 }
Greg Clayton8b82f082011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000095 {
Greg Clayton8b82f082011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000098 }
Greg Clayton8b82f082011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000100 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000103 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000105 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Clayton8b82f082011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000113{
Greg Clayton8b82f082011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000130}
131
132void
Greg Clayton8b82f082011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
138 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
139
Greg Clayton32e0a752011-03-30 18:16:51 +0000140
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000148
Greg Clayton8b82f082011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000154
Greg Clayton8b82f082011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000160
Greg Clayton8b82f082011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molendafd54b362011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Clayton8b82f082011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000177 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000195 }
196}
197
Greg Clayton8b82f082011-04-12 05:54:46 +0000198
199void
200ProcessInfo::SetArgumentsFromArgs (const Args& args,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 // Copy all arguments
205 m_arguments = args;
206
207 // Is the first argument the executable?
208 if (first_arg_is_executable)
209 {
210 const char *first_arg = args.GetArgumentAtIndex (0);
211 if (first_arg)
212 {
213 // Yes the first argument is an executable, set it as the executable
214 // in the launch options. Don't resolve the file path as the path
215 // could be a remote platform path
216 const bool resolve = false;
217 m_executable.SetFile(first_arg, resolve);
218
219 // If argument zero is an executable and shouldn't be included
220 // in the arguments, remove it from the front of the arguments
221 if (first_arg_is_executable_and_argument == false)
222 m_arguments.DeleteArgumentAtIndex (0);
223 }
224 }
225}
226
Greg Clayton32e0a752011-03-30 18:16:51 +0000227bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000228ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
229{
230 if ((read || write) && fd >= 0 && path && path[0])
231 {
232 m_action = eFileActionOpen;
233 m_fd = fd;
234 if (read && write)
235 m_arg = O_RDWR;
236 else if (read)
237 m_arg = O_RDONLY;
238 else
239 m_arg = O_WRONLY;
240 m_path.assign (path);
241 return true;
242 }
243 else
244 {
245 Clear();
246 }
247 return false;
248}
249
250bool
251ProcessLaunchInfo::FileAction::Close (int fd)
252{
253 Clear();
254 if (fd >= 0)
255 {
256 m_action = eFileActionClose;
257 m_fd = fd;
258 }
259 return m_fd >= 0;
260}
261
262
263bool
264ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
265{
266 Clear();
267 if (fd >= 0 && dup_fd >= 0)
268 {
269 m_action = eFileActionDuplicate;
270 m_fd = fd;
271 m_arg = dup_fd;
272 }
273 return m_fd >= 0;
274}
275
276
277
278bool
279ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
280 const FileAction *info,
281 Log *log,
282 Error& error)
283{
284 if (info == NULL)
285 return false;
286
287 switch (info->m_action)
288 {
289 case eFileActionNone:
290 error.Clear();
291 break;
292
293 case eFileActionClose:
294 if (info->m_fd == -1)
295 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
296 else
297 {
298 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
299 eErrorTypePOSIX);
300 if (log && (error.Fail() || log))
301 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
302 file_actions, info->m_fd);
303 }
304 break;
305
306 case eFileActionDuplicate:
307 if (info->m_fd == -1)
308 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
309 else if (info->m_arg == -1)
310 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
311 else
312 {
313 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
314 eErrorTypePOSIX);
315 if (log && (error.Fail() || log))
316 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
317 file_actions, info->m_fd, info->m_arg);
318 }
319 break;
320
321 case eFileActionOpen:
322 if (info->m_fd == -1)
323 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
324 else
325 {
326 int oflag = info->m_arg;
327 mode_t mode = 0;
328
329 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
330 info->m_fd,
331 info->m_path.c_str(),
332 oflag,
333 mode),
334 eErrorTypePOSIX);
335 if (error.Fail() || log)
336 error.PutToLog(log,
337 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
338 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
339 }
340 break;
341
342 default:
343 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
344 break;
345 }
346 return error.Success();
347}
348
349Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000350ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000351{
352 Error error;
353 char short_option = (char) m_getopt_table[option_idx].val;
354
355 switch (short_option)
356 {
357 case 's': // Stop at program entry point
358 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
359 break;
360
361 case 'e': // STDERR for read + write
362 {
363 ProcessLaunchInfo::FileAction action;
364 if (action.Open(STDERR_FILENO, option_arg, true, true))
365 launch_info.AppendFileAction (action);
366 }
367 break;
368
369 case 'i': // STDIN for read only
370 {
371 ProcessLaunchInfo::FileAction action;
372 if (action.Open(STDIN_FILENO, option_arg, true, false))
373 launch_info.AppendFileAction (action);
374 }
375 break;
376
377 case 'o': // Open STDOUT for write only
378 {
379 ProcessLaunchInfo::FileAction action;
380 if (action.Open(STDOUT_FILENO, option_arg, false, true))
381 launch_info.AppendFileAction (action);
382 }
383 break;
384
385 case 'p': // Process plug-in name
386 launch_info.SetProcessPluginName (option_arg);
387 break;
388
389 case 'n': // Disable STDIO
390 {
391 ProcessLaunchInfo::FileAction action;
392 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
393 launch_info.AppendFileAction (action);
394 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
395 launch_info.AppendFileAction (action);
396 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
397 launch_info.AppendFileAction (action);
398 }
399 break;
400
401 case 'w':
402 launch_info.SetWorkingDirectory (option_arg);
403 break;
404
405 case 't': // Open process in new terminal window
406 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
407 break;
408
409 case 'a':
410 launch_info.GetArchitecture().SetTriple (option_arg,
411 m_interpreter.GetPlatform(true).get());
412 break;
413
414 case 'A':
415 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
416 break;
417
418 case 'v':
419 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
420 break;
421
422 default:
423 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
424 break;
425
426 }
427 return error;
428}
429
430OptionDefinition
431ProcessLaunchCommandOptions::g_option_table[] =
432{
433{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
434{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
435{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
436{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
437{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
438{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
439
440{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
441{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
442{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
443
444{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
445
446{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
447
448{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
449};
450
451
452
453bool
454ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000455{
456 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
457 return true;
458 const char *match_name = m_match_info.GetName();
459 if (!match_name)
460 return true;
461
462 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
463}
464
465bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000466ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000467{
468 if (!NameMatches (proc_info.GetName()))
469 return false;
470
471 if (m_match_info.ProcessIDIsValid() &&
472 m_match_info.GetProcessID() != proc_info.GetProcessID())
473 return false;
474
475 if (m_match_info.ParentProcessIDIsValid() &&
476 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
477 return false;
478
Greg Clayton8b82f082011-04-12 05:54:46 +0000479 if (m_match_info.UserIDIsValid () &&
480 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000481 return false;
482
Greg Clayton8b82f082011-04-12 05:54:46 +0000483 if (m_match_info.GroupIDIsValid () &&
484 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000485 return false;
486
487 if (m_match_info.EffectiveUserIDIsValid () &&
488 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
489 return false;
490
491 if (m_match_info.EffectiveGroupIDIsValid () &&
492 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
493 return false;
494
495 if (m_match_info.GetArchitecture().IsValid() &&
496 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
497 return false;
498 return true;
499}
500
501bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000502ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000503{
504 if (m_name_match_type != eNameMatchIgnore)
505 return false;
506
507 if (m_match_info.ProcessIDIsValid())
508 return false;
509
510 if (m_match_info.ParentProcessIDIsValid())
511 return false;
512
Greg Clayton8b82f082011-04-12 05:54:46 +0000513 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000514 return false;
515
Greg Clayton8b82f082011-04-12 05:54:46 +0000516 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000517 return false;
518
519 if (m_match_info.EffectiveUserIDIsValid ())
520 return false;
521
522 if (m_match_info.EffectiveGroupIDIsValid ())
523 return false;
524
525 if (m_match_info.GetArchitecture().IsValid())
526 return false;
527
528 if (m_match_all_users)
529 return false;
530
531 return true;
532
533}
534
535void
Greg Clayton8b82f082011-04-12 05:54:46 +0000536ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000537{
538 m_match_info.Clear();
539 m_name_match_type = eNameMatchIgnore;
540 m_match_all_users = false;
541}
Greg Clayton58be07b2011-01-07 06:08:19 +0000542
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543Process*
544Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
545{
546 ProcessCreateInstance create_callback = NULL;
547 if (plugin_name)
548 {
549 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
550 if (create_callback)
551 {
552 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000553 if (debugger_ap->CanDebug(target, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 return debugger_ap.release();
555 }
556 }
557 else
558 {
Greg Claytonc982c762010-07-09 20:39:50 +0000559 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560 {
Greg Claytonc982c762010-07-09 20:39:50 +0000561 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000562 if (debugger_ap->CanDebug(target, false))
Greg Claytonc982c762010-07-09 20:39:50 +0000563 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000564 }
565 }
566 return NULL;
567}
568
569
570//----------------------------------------------------------------------
571// Process constructor
572//----------------------------------------------------------------------
573Process::Process(Target &target, Listener &listener) :
574 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000575 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000576 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000577 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 m_public_state (eStateUnloaded),
579 m_private_state (eStateUnloaded),
580 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
581 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
582 m_private_state_listener ("lldb.process.internal_state_listener"),
583 m_private_state_control_wait(),
584 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000585 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000586 m_thread_index_id (0),
587 m_exit_status (-1),
588 m_exit_string (),
589 m_thread_list (this),
590 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000591 m_image_tokens (),
592 m_listener (listener),
593 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000594 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000595 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000596 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000597 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000598 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000599 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000600 m_stdout_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000601 m_memory_cache (*this),
602 m_allocated_memory_cache (*this),
Jim Ingham8314c522011-09-15 21:36:42 +0000603 m_attached_to_process (false),
Sean Callanan90539452011-09-20 23:01:51 +0000604 m_next_event_action_ap(),
605 m_can_jit(eCanJITYes)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606{
Caroline Tice1559a462010-09-27 00:30:10 +0000607 UpdateInstanceName();
608
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000609 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000610 if (log)
611 log->Printf ("%p Process::Process()", this);
612
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000613 SetEventName (eBroadcastBitStateChanged, "state-changed");
614 SetEventName (eBroadcastBitInterrupt, "interrupt");
615 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
616 SetEventName (eBroadcastBitSTDERR, "stderr-available");
617
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 listener.StartListeningForEvents (this,
619 eBroadcastBitStateChanged |
620 eBroadcastBitInterrupt |
621 eBroadcastBitSTDOUT |
622 eBroadcastBitSTDERR);
623
624 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
625 eBroadcastBitStateChanged);
626
627 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
628 eBroadcastInternalStateControlStop |
629 eBroadcastInternalStateControlPause |
630 eBroadcastInternalStateControlResume);
631}
632
633//----------------------------------------------------------------------
634// Destructor
635//----------------------------------------------------------------------
636Process::~Process()
637{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000638 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 if (log)
640 log->Printf ("%p Process::~Process()", this);
641 StopPrivateStateThread();
642}
643
644void
645Process::Finalize()
646{
647 // Do any cleanup needed prior to being destructed... Subclasses
648 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000649
650 // We need to destroy the loader before the derived Process class gets destroyed
651 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000652 m_dyld_ap.reset();
653 m_os_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654}
655
656void
657Process::RegisterNotificationCallbacks (const Notifications& callbacks)
658{
659 m_notifications.push_back(callbacks);
660 if (callbacks.initialize != NULL)
661 callbacks.initialize (callbacks.baton, this);
662}
663
664bool
665Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
666{
667 std::vector<Notifications>::iterator pos, end = m_notifications.end();
668 for (pos = m_notifications.begin(); pos != end; ++pos)
669 {
670 if (pos->baton == callbacks.baton &&
671 pos->initialize == callbacks.initialize &&
672 pos->process_state_changed == callbacks.process_state_changed)
673 {
674 m_notifications.erase(pos);
675 return true;
676 }
677 }
678 return false;
679}
680
681void
682Process::SynchronouslyNotifyStateChanged (StateType state)
683{
684 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
685 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
686 {
687 if (notification_pos->process_state_changed)
688 notification_pos->process_state_changed (notification_pos->baton, this, state);
689 }
690}
691
692// FIXME: We need to do some work on events before the general Listener sees them.
693// For instance if we are continuing from a breakpoint, we need to ensure that we do
694// the little "insert real insn, step & stop" trick. But we can't do that when the
695// event is delivered by the broadcaster - since that is done on the thread that is
696// waiting for new events, so if we needed more than one event for our handling, we would
697// stall. So instead we do it when we fetch the event off of the queue.
698//
699
700StateType
701Process::GetNextEvent (EventSP &event_sp)
702{
703 StateType state = eStateInvalid;
704
705 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
706 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
707
708 return state;
709}
710
711
712StateType
713Process::WaitForProcessToStop (const TimeValue *timeout)
714{
Jim Ingham4b536182011-08-09 02:12:22 +0000715 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
716 // We have to actually check each event, and in the case of a stopped event check the restarted flag
717 // on the event.
718 EventSP event_sp;
719 StateType state = GetState();
720 // If we are exited or detached, we won't ever get back to any
721 // other valid state...
722 if (state == eStateDetached || state == eStateExited)
723 return state;
724
725 while (state != eStateInvalid)
726 {
727 state = WaitForStateChangedEvents (timeout, event_sp);
728 switch (state)
729 {
730 case eStateCrashed:
731 case eStateDetached:
732 case eStateExited:
733 case eStateUnloaded:
734 return state;
735 case eStateStopped:
736 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
737 continue;
738 else
739 return state;
740 default:
741 continue;
742 }
743 }
744 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745}
746
747
748StateType
749Process::WaitForState
750(
751 const TimeValue *timeout,
752 const StateType *match_states, const uint32_t num_match_states
753)
754{
755 EventSP event_sp;
756 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000757 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758 while (state != eStateInvalid)
759 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000760 // If we are exited or detached, we won't ever get back to any
761 // other valid state...
762 if (state == eStateDetached || state == eStateExited)
763 return state;
764
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765 state = WaitForStateChangedEvents (timeout, event_sp);
766
767 for (i=0; i<num_match_states; ++i)
768 {
769 if (match_states[i] == state)
770 return state;
771 }
772 }
773 return state;
774}
775
Jim Ingham30f9b212010-10-11 23:53:14 +0000776bool
777Process::HijackProcessEvents (Listener *listener)
778{
779 if (listener != NULL)
780 {
781 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
782 }
783 else
784 return false;
785}
786
787void
788Process::RestoreProcessEvents ()
789{
790 RestoreBroadcaster();
791}
792
Jim Ingham0f16e732011-02-08 05:20:59 +0000793bool
794Process::HijackPrivateProcessEvents (Listener *listener)
795{
796 if (listener != NULL)
797 {
798 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
799 }
800 else
801 return false;
802}
803
804void
805Process::RestorePrivateProcessEvents ()
806{
807 m_private_state_broadcaster.RestoreBroadcaster();
808}
809
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810StateType
811Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
812{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000813 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814
815 if (log)
816 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
817
818 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000819 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
820 this,
821 eBroadcastBitStateChanged,
822 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
824
825 if (log)
826 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
827 __FUNCTION__,
828 timeout,
829 StateAsCString(state));
830 return state;
831}
832
833Event *
834Process::PeekAtStateChangedEvents ()
835{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000836 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000837
838 if (log)
839 log->Printf ("Process::%s...", __FUNCTION__);
840
841 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000842 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
843 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000844 if (log)
845 {
846 if (event_ptr)
847 {
848 log->Printf ("Process::%s (event_ptr) => %s",
849 __FUNCTION__,
850 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
851 }
852 else
853 {
854 log->Printf ("Process::%s no events found",
855 __FUNCTION__);
856 }
857 }
858 return event_ptr;
859}
860
861StateType
862Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
863{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000864 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865
866 if (log)
867 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
868
869 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000870 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
871 &m_private_state_broadcaster,
872 eBroadcastBitStateChanged,
873 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
875
876 // This is a bit of a hack, but when we wait here we could very well return
877 // to the command-line, and that could disable the log, which would render the
878 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000880 {
881 if (state == eStateInvalid)
882 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
883 else
884 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
885 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886 return state;
887}
888
889bool
890Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
891{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000892 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893
894 if (log)
895 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
896
897 if (control_only)
898 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
899 else
900 return m_private_state_listener.WaitForEvent(timeout, event_sp);
901}
902
903bool
904Process::IsRunning () const
905{
906 return StateIsRunningState (m_public_state.GetValue());
907}
908
909int
910Process::GetExitStatus ()
911{
912 if (m_public_state.GetValue() == eStateExited)
913 return m_exit_status;
914 return -1;
915}
916
Greg Clayton85851dd2010-12-04 00:10:17 +0000917
918void
919Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
920{
921 if (m_inherit_host_env && !m_got_host_env)
922 {
923 m_got_host_env = true;
924 StringList host_env;
925 const size_t host_env_count = Host::GetEnvironment (host_env);
926 for (size_t idx=0; idx<host_env_count; idx++)
927 {
928 const char *env_entry = host_env.GetStringAtIndex (idx);
929 if (env_entry)
930 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000931 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000932 if (equal_pos)
933 {
934 std::string key (env_entry, equal_pos - env_entry);
935 std::string value (equal_pos + 1);
936 if (m_env_vars.find (key) == m_env_vars.end())
937 m_env_vars[key] = value;
938 }
939 }
940 }
941 }
942}
943
944
945size_t
946Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
947{
948 GetHostEnvironmentIfNeeded ();
949
950 dictionary::const_iterator pos, end = m_env_vars.end();
951 for (pos = m_env_vars.begin(); pos != end; ++pos)
952 {
953 std::string env_var_equal_value (pos->first);
954 env_var_equal_value.append(1, '=');
955 env_var_equal_value.append (pos->second);
956 env.AppendArgument (env_var_equal_value.c_str());
957 }
958 return env.GetArgumentCount();
959}
960
961
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000962const char *
963Process::GetExitDescription ()
964{
965 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
966 return m_exit_string.c_str();
967 return NULL;
968}
969
Greg Clayton6779606a2011-01-22 23:43:18 +0000970bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000971Process::SetExitStatus (int status, const char *cstr)
972{
Greg Clayton414f5d32011-01-25 02:58:48 +0000973 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
974 if (log)
975 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
976 status, status,
977 cstr ? "\"" : "",
978 cstr ? cstr : "NULL",
979 cstr ? "\"" : "");
980
Greg Clayton6779606a2011-01-22 23:43:18 +0000981 // We were already in the exited state
982 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000983 {
Greg Clayton385d6032011-01-26 23:47:29 +0000984 if (log)
985 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000986 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000987 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000988
989 m_exit_status = status;
990 if (cstr)
991 m_exit_string = cstr;
992 else
993 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994
Greg Clayton6779606a2011-01-22 23:43:18 +0000995 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000996
Greg Clayton6779606a2011-01-22 23:43:18 +0000997 SetPrivateState (eStateExited);
998 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000999}
1000
1001// This static callback can be used to watch for local child processes on
1002// the current host. The the child process exits, the process will be
1003// found in the global target list (we want to be completely sure that the
1004// lldb_private::Process doesn't go away before we can deliver the signal.
1005bool
1006Process::SetProcessExitStatus
1007(
1008 void *callback_baton,
1009 lldb::pid_t pid,
1010 int signo, // Zero for no signal
1011 int exit_status // Exit value of process if signal is zero
1012)
1013{
1014 if (signo == 0 || exit_status)
1015 {
Greg Clayton66111032010-06-23 01:19:29 +00001016 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017 if (target_sp)
1018 {
1019 ProcessSP process_sp (target_sp->GetProcessSP());
1020 if (process_sp)
1021 {
1022 const char *signal_cstr = NULL;
1023 if (signo)
1024 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1025
1026 process_sp->SetExitStatus (exit_status, signal_cstr);
1027 }
1028 }
1029 return true;
1030 }
1031 return false;
1032}
1033
1034
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001035void
1036Process::UpdateThreadListIfNeeded ()
1037{
1038 const uint32_t stop_id = GetStopID();
1039 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1040 {
1041 Mutex::Locker locker (m_thread_list.GetMutex ());
1042 ThreadList new_thread_list(this);
1043 // Always update the thread list with the protocol specific
1044 // thread list
1045 UpdateThreadList (m_thread_list, new_thread_list);
1046 OperatingSystem *os = GetOperatingSystem ();
1047 if (os)
1048 os->UpdateThreadList (m_thread_list, new_thread_list);
1049 m_thread_list.Update (new_thread_list);
1050 m_thread_list.SetStopID (stop_id);
1051 }
1052}
1053
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054uint32_t
1055Process::GetNextThreadIndexID ()
1056{
1057 return ++m_thread_index_id;
1058}
1059
1060StateType
1061Process::GetState()
1062{
1063 // If any other threads access this we will need a mutex for it
1064 return m_public_state.GetValue ();
1065}
1066
1067void
1068Process::SetPublicState (StateType new_state)
1069{
Greg Clayton414f5d32011-01-25 02:58:48 +00001070 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 if (log)
1072 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1073 m_public_state.SetValue (new_state);
1074}
1075
1076StateType
1077Process::GetPrivateState ()
1078{
1079 return m_private_state.GetValue();
1080}
1081
1082void
1083Process::SetPrivateState (StateType new_state)
1084{
Greg Clayton414f5d32011-01-25 02:58:48 +00001085 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 bool state_changed = false;
1087
1088 if (log)
1089 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1090
1091 Mutex::Locker locker(m_private_state.GetMutex());
1092
1093 const StateType old_state = m_private_state.GetValueNoLock ();
1094 state_changed = old_state != new_state;
1095 if (state_changed)
1096 {
1097 m_private_state.SetValueNoLock (new_state);
1098 if (StateIsStoppedState(new_state))
1099 {
Jim Ingham4b536182011-08-09 02:12:22 +00001100 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001101 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001103 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 }
1105 // Use our target to get a shared pointer to ourselves...
1106 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1107 }
1108 else
1109 {
1110 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001111 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112 }
1113}
1114
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115addr_t
1116Process::GetImageInfoAddress()
1117{
1118 return LLDB_INVALID_ADDRESS;
1119}
1120
Greg Clayton8f343b02010-11-04 01:54:29 +00001121//----------------------------------------------------------------------
1122// LoadImage
1123//
1124// This function provides a default implementation that works for most
1125// unix variants. Any Process subclasses that need to do shared library
1126// loading differently should override LoadImage and UnloadImage and
1127// do what is needed.
1128//----------------------------------------------------------------------
1129uint32_t
1130Process::LoadImage (const FileSpec &image_spec, Error &error)
1131{
1132 DynamicLoader *loader = GetDynamicLoader();
1133 if (loader)
1134 {
1135 error = loader->CanLoadImage();
1136 if (error.Fail())
1137 return LLDB_INVALID_IMAGE_TOKEN;
1138 }
1139
1140 if (error.Success())
1141 {
1142 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001143
1144 if (thread_sp)
1145 {
1146 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1147
1148 if (frame_sp)
1149 {
1150 ExecutionContext exe_ctx;
1151 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001152 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001153 StreamString expr;
1154 char path[PATH_MAX];
1155 image_spec.GetPath(path, sizeof(path));
1156 expr.Printf("dlopen (\"%s\", 2)", path);
1157 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001158 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001159 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001160 error = result_valobj_sp->GetError();
1161 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001162 {
1163 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001164 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001165 {
1166 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1167 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1168 {
1169 uint32_t image_token = m_image_tokens.size();
1170 m_image_tokens.push_back (image_ptr);
1171 return image_token;
1172 }
1173 }
1174 }
1175 }
1176 }
1177 }
1178 return LLDB_INVALID_IMAGE_TOKEN;
1179}
1180
1181//----------------------------------------------------------------------
1182// UnloadImage
1183//
1184// This function provides a default implementation that works for most
1185// unix variants. Any Process subclasses that need to do shared library
1186// loading differently should override LoadImage and UnloadImage and
1187// do what is needed.
1188//----------------------------------------------------------------------
1189Error
1190Process::UnloadImage (uint32_t image_token)
1191{
1192 Error error;
1193 if (image_token < m_image_tokens.size())
1194 {
1195 const addr_t image_addr = m_image_tokens[image_token];
1196 if (image_addr == LLDB_INVALID_ADDRESS)
1197 {
1198 error.SetErrorString("image already unloaded");
1199 }
1200 else
1201 {
1202 DynamicLoader *loader = GetDynamicLoader();
1203 if (loader)
1204 error = loader->CanLoadImage();
1205
1206 if (error.Success())
1207 {
1208 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001209
1210 if (thread_sp)
1211 {
1212 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1213
1214 if (frame_sp)
1215 {
1216 ExecutionContext exe_ctx;
1217 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001218 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001219 StreamString expr;
1220 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1221 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001222 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001223 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001224 if (result_valobj_sp->GetError().Success())
1225 {
1226 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001227 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001228 {
1229 if (scalar.UInt(1))
1230 {
1231 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1232 }
1233 else
1234 {
1235 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1236 }
1237 }
1238 }
1239 else
1240 {
1241 error = result_valobj_sp->GetError();
1242 }
1243 }
1244 }
1245 }
1246 }
1247 }
1248 else
1249 {
1250 error.SetErrorString("invalid image token");
1251 }
1252 return error;
1253}
1254
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001255const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256Process::GetABI()
1257{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001258 if (!m_abi_sp)
1259 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1260 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001261}
1262
Jim Ingham22777012010-09-23 02:01:19 +00001263LanguageRuntime *
1264Process::GetLanguageRuntime(lldb::LanguageType language)
1265{
1266 LanguageRuntimeCollection::iterator pos;
1267 pos = m_language_runtimes.find (language);
1268 if (pos == m_language_runtimes.end())
1269 {
1270 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1271
1272 m_language_runtimes[language]
1273 = runtime;
1274 return runtime.get();
1275 }
1276 else
1277 return (*pos).second.get();
1278}
1279
1280CPPLanguageRuntime *
1281Process::GetCPPLanguageRuntime ()
1282{
1283 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1284 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1285 return static_cast<CPPLanguageRuntime *> (runtime);
1286 return NULL;
1287}
1288
1289ObjCLanguageRuntime *
1290Process::GetObjCLanguageRuntime ()
1291{
1292 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1293 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1294 return static_cast<ObjCLanguageRuntime *> (runtime);
1295 return NULL;
1296}
1297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001298BreakpointSiteList &
1299Process::GetBreakpointSiteList()
1300{
1301 return m_breakpoint_site_list;
1302}
1303
1304const BreakpointSiteList &
1305Process::GetBreakpointSiteList() const
1306{
1307 return m_breakpoint_site_list;
1308}
1309
1310
1311void
1312Process::DisableAllBreakpointSites ()
1313{
1314 m_breakpoint_site_list.SetEnabledForAll (false);
1315}
1316
1317Error
1318Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1319{
1320 Error error (DisableBreakpointSiteByID (break_id));
1321
1322 if (error.Success())
1323 m_breakpoint_site_list.Remove(break_id);
1324
1325 return error;
1326}
1327
1328Error
1329Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1330{
1331 Error error;
1332 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1333 if (bp_site_sp)
1334 {
1335 if (bp_site_sp->IsEnabled())
1336 error = DisableBreakpoint (bp_site_sp.get());
1337 }
1338 else
1339 {
1340 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1341 }
1342
1343 return error;
1344}
1345
1346Error
1347Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1348{
1349 Error error;
1350 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1351 if (bp_site_sp)
1352 {
1353 if (!bp_site_sp->IsEnabled())
1354 error = EnableBreakpoint (bp_site_sp.get());
1355 }
1356 else
1357 {
1358 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1359 }
1360 return error;
1361}
1362
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001363lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1365{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001366 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 if (load_addr != LLDB_INVALID_ADDRESS)
1368 {
1369 BreakpointSiteSP bp_site_sp;
1370
1371 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1372 // create a new breakpoint site and add it.
1373
1374 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1375
1376 if (bp_site_sp)
1377 {
1378 bp_site_sp->AddOwner (owner);
1379 owner->SetBreakpointSite (bp_site_sp);
1380 return bp_site_sp->GetID();
1381 }
1382 else
1383 {
1384 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1385 if (bp_site_sp)
1386 {
1387 if (EnableBreakpoint (bp_site_sp.get()).Success())
1388 {
1389 owner->SetBreakpointSite (bp_site_sp);
1390 return m_breakpoint_site_list.Add (bp_site_sp);
1391 }
1392 }
1393 }
1394 }
1395 // We failed to enable the breakpoint
1396 return LLDB_INVALID_BREAK_ID;
1397
1398}
1399
1400void
1401Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1402{
1403 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1404 if (num_owners == 0)
1405 {
1406 DisableBreakpoint(bp_site_sp.get());
1407 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1408 }
1409}
1410
1411
1412size_t
1413Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1414{
1415 size_t bytes_removed = 0;
1416 addr_t intersect_addr;
1417 size_t intersect_size;
1418 size_t opcode_offset;
1419 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001420 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001421 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001422
Jim Ingham20c77192011-06-29 19:42:28 +00001423 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001425 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001426 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001427 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001428 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001429 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001430 {
1431 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1432 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001433 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001434 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001435 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001436 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 }
1438 }
1439 }
1440 return bytes_removed;
1441}
1442
1443
Greg Claytonded470d2011-03-19 01:12:21 +00001444
1445size_t
1446Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1447{
1448 PlatformSP platform_sp (m_target.GetPlatform());
1449 if (platform_sp)
1450 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1451 return 0;
1452}
1453
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001454Error
1455Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1456{
1457 Error error;
1458 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001459 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001460 const addr_t bp_addr = bp_site->GetLoadAddress();
1461 if (log)
1462 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1463 if (bp_site->IsEnabled())
1464 {
1465 if (log)
1466 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1467 return error;
1468 }
1469
1470 if (bp_addr == LLDB_INVALID_ADDRESS)
1471 {
1472 error.SetErrorString("BreakpointSite contains an invalid load address.");
1473 return error;
1474 }
1475 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1476 // trap for the breakpoint site
1477 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1478
1479 if (bp_opcode_size == 0)
1480 {
1481 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1482 }
1483 else
1484 {
1485 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1486
1487 if (bp_opcode_bytes == NULL)
1488 {
1489 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1490 return error;
1491 }
1492
1493 // Save the original opcode by reading it
1494 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1495 {
1496 // Write a software breakpoint in place of the original opcode
1497 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1498 {
1499 uint8_t verify_bp_opcode_bytes[64];
1500 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1501 {
1502 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1503 {
1504 bp_site->SetEnabled(true);
1505 bp_site->SetType (BreakpointSite::eSoftware);
1506 if (log)
1507 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1508 bp_site->GetID(),
1509 (uint64_t)bp_addr);
1510 }
1511 else
1512 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1513 }
1514 else
1515 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1516 }
1517 else
1518 error.SetErrorString("Unable to write breakpoint trap to memory.");
1519 }
1520 else
1521 error.SetErrorString("Unable to read memory at breakpoint address.");
1522 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001523 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001524 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1525 bp_site->GetID(),
1526 (uint64_t)bp_addr,
1527 error.AsCString());
1528 return error;
1529}
1530
1531Error
1532Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1533{
1534 Error error;
1535 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001536 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001537 addr_t bp_addr = bp_site->GetLoadAddress();
1538 lldb::user_id_t breakID = bp_site->GetID();
1539 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001540 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001541
1542 if (bp_site->IsHardware())
1543 {
1544 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1545 }
1546 else if (bp_site->IsEnabled())
1547 {
1548 const size_t break_op_size = bp_site->GetByteSize();
1549 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1550 if (break_op_size > 0)
1551 {
1552 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001553 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001554 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001555 bool break_op_found = false;
1556
1557 // Read the breakpoint opcode
1558 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1559 {
1560 bool verify = false;
1561 // Make sure we have the a breakpoint opcode exists at this address
1562 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1563 {
1564 break_op_found = true;
1565 // We found a valid breakpoint opcode at this address, now restore
1566 // the saved opcode.
1567 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1568 {
1569 verify = true;
1570 }
1571 else
1572 error.SetErrorString("Memory write failed when restoring original opcode.");
1573 }
1574 else
1575 {
1576 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1577 // Set verify to true and so we can check if the original opcode has already been restored
1578 verify = true;
1579 }
1580
1581 if (verify)
1582 {
Greg Claytonc982c762010-07-09 20:39:50 +00001583 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001584 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001585 // Verify that our original opcode made it back to the inferior
1586 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1587 {
1588 // compare the memory we just read with the original opcode
1589 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1590 {
1591 // SUCCESS
1592 bp_site->SetEnabled(false);
1593 if (log)
1594 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1595 return error;
1596 }
1597 else
1598 {
1599 if (break_op_found)
1600 error.SetErrorString("Failed to restore original opcode.");
1601 }
1602 }
1603 else
1604 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1605 }
1606 }
1607 else
1608 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1609 }
1610 }
1611 else
1612 {
1613 if (log)
1614 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1615 return error;
1616 }
1617
1618 if (log)
1619 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1620 bp_site->GetID(),
1621 (uint64_t)bp_addr,
1622 error.AsCString());
1623 return error;
1624
1625}
1626
Greg Clayton58be07b2011-01-07 06:08:19 +00001627// Comment out line below to disable memory caching
1628#define ENABLE_MEMORY_CACHING
1629// Uncomment to verify memory caching works after making changes to caching code
1630//#define VERIFY_MEMORY_READS
1631
1632#if defined (ENABLE_MEMORY_CACHING)
1633
1634#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001635
1636size_t
1637Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1638{
Greg Clayton58be07b2011-01-07 06:08:19 +00001639 // Memory caching is enabled, with debug verification
1640 if (buf && size)
1641 {
1642 // Uncomment the line below to make sure memory caching is working.
1643 // I ran this through the test suite and got no assertions, so I am
1644 // pretty confident this is working well. If any changes are made to
1645 // memory caching, uncomment the line below and test your changes!
1646
1647 // Verify all memory reads by using the cache first, then redundantly
1648 // reading the same memory from the inferior and comparing to make sure
1649 // everything is exactly the same.
1650 std::string verify_buf (size, '\0');
1651 assert (verify_buf.size() == size);
1652 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1653 Error verify_error;
1654 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1655 assert (cache_bytes_read == verify_bytes_read);
1656 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1657 assert (verify_error.Success() == error.Success());
1658 return cache_bytes_read;
1659 }
1660 return 0;
1661}
1662
1663#else // #if defined (VERIFY_MEMORY_READS)
1664
1665size_t
1666Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1667{
1668 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001669 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001670}
1671
1672#endif // #else for #if defined (VERIFY_MEMORY_READS)
1673
1674#else // #if defined (ENABLE_MEMORY_CACHING)
1675
1676size_t
1677Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1678{
1679 // Memory caching is disabled
1680 return ReadMemoryFromInferior (addr, buf, size, error);
1681}
1682
1683#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1684
1685
1686size_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001687Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1688{
1689 size_t total_cstr_len = 0;
1690 if (dst && dst_max_len)
1691 {
1692 // NULL out everything just to be safe
1693 memset (dst, 0, dst_max_len);
1694 Error error;
1695 addr_t curr_addr = addr;
1696 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1697 size_t bytes_left = dst_max_len - 1;
1698 char *curr_dst = dst;
1699
1700 while (bytes_left > 0)
1701 {
1702 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1703 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1704 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1705
1706 if (bytes_read == 0)
1707 {
1708 dst[total_cstr_len] = '\0';
1709 break;
1710 }
1711 const size_t len = strlen(curr_dst);
1712
1713 total_cstr_len += len;
1714
1715 if (len < bytes_to_read)
1716 break;
1717
1718 curr_dst += bytes_read;
1719 curr_addr += bytes_read;
1720 bytes_left -= bytes_read;
1721 }
1722 }
1723 return total_cstr_len;
1724}
1725
1726size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001727Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1728{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729 if (buf == NULL || size == 0)
1730 return 0;
1731
1732 size_t bytes_read = 0;
1733 uint8_t *bytes = (uint8_t *)buf;
1734
1735 while (bytes_read < size)
1736 {
1737 const size_t curr_size = size - bytes_read;
1738 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1739 bytes + bytes_read,
1740 curr_size,
1741 error);
1742 bytes_read += curr_bytes_read;
1743 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1744 break;
1745 }
1746
1747 // Replace any software breakpoint opcodes that fall into this range back
1748 // into "buf" before we return
1749 if (bytes_read > 0)
1750 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1751 return bytes_read;
1752}
1753
Greg Clayton58a4c462010-12-16 20:01:20 +00001754uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001755Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001756{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001757 Scalar scalar;
1758 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1759 return scalar.ULongLong(fail_value);
1760 return fail_value;
1761}
1762
1763addr_t
1764Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1765{
1766 Scalar scalar;
1767 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1768 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1769 return LLDB_INVALID_ADDRESS;
1770}
1771
1772
1773bool
1774Process::WritePointerToMemory (lldb::addr_t vm_addr,
1775 lldb::addr_t ptr_value,
1776 Error &error)
1777{
1778 Scalar scalar;
1779 const uint32_t addr_byte_size = GetAddressByteSize();
1780 if (addr_byte_size <= 4)
1781 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001782 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001783 scalar = ptr_value;
1784 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001785}
1786
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001787size_t
1788Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1789{
1790 size_t bytes_written = 0;
1791 const uint8_t *bytes = (const uint8_t *)buf;
1792
1793 while (bytes_written < size)
1794 {
1795 const size_t curr_size = size - bytes_written;
1796 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1797 bytes + bytes_written,
1798 curr_size,
1799 error);
1800 bytes_written += curr_bytes_written;
1801 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1802 break;
1803 }
1804 return bytes_written;
1805}
1806
1807size_t
1808Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1809{
Greg Clayton58be07b2011-01-07 06:08:19 +00001810#if defined (ENABLE_MEMORY_CACHING)
1811 m_memory_cache.Flush (addr, size);
1812#endif
1813
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001814 if (buf == NULL || size == 0)
1815 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00001816
Jim Ingham4b536182011-08-09 02:12:22 +00001817 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00001818
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 // We need to write any data that would go where any current software traps
1820 // (enabled software breakpoints) any software traps (breakpoints) that we
1821 // may have placed in our tasks memory.
1822
1823 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1824 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1825
1826 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001827 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828
1829 BreakpointSiteList::collection::const_iterator pos;
1830 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001831 addr_t intersect_addr = 0;
1832 size_t intersect_size = 0;
1833 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 const uint8_t *ubuf = (const uint8_t *)buf;
1835
1836 for (pos = iter; pos != end; ++pos)
1837 {
1838 BreakpointSiteSP bp;
1839 bp = pos->second;
1840
1841 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1842 assert(addr <= intersect_addr && intersect_addr < addr + size);
1843 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1844 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1845
1846 // Check for bytes before this breakpoint
1847 const addr_t curr_addr = addr + bytes_written;
1848 if (intersect_addr > curr_addr)
1849 {
1850 // There are some bytes before this breakpoint that we need to
1851 // just write to memory
1852 size_t curr_size = intersect_addr - curr_addr;
1853 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1854 ubuf + bytes_written,
1855 curr_size,
1856 error);
1857 bytes_written += curr_bytes_written;
1858 if (curr_bytes_written != curr_size)
1859 {
1860 // We weren't able to write all of the requested bytes, we
1861 // are done looping and will return the number of bytes that
1862 // we have written so far.
1863 break;
1864 }
1865 }
1866
1867 // Now write any bytes that would cover up any software breakpoints
1868 // directly into the breakpoint opcode buffer
1869 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1870 bytes_written += intersect_size;
1871 }
1872
1873 // Write any remaining bytes after the last breakpoint if we have any left
1874 if (bytes_written < size)
1875 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1876 ubuf + bytes_written,
1877 size - bytes_written,
1878 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00001879
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001880 return bytes_written;
1881}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001882
1883size_t
1884Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1885{
1886 if (byte_size == UINT32_MAX)
1887 byte_size = scalar.GetByteSize();
1888 if (byte_size > 0)
1889 {
1890 uint8_t buf[32];
1891 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1892 if (mem_size > 0)
1893 return WriteMemory(addr, buf, mem_size, error);
1894 else
1895 error.SetErrorString ("failed to get scalar as memory data");
1896 }
1897 else
1898 {
1899 error.SetErrorString ("invalid scalar value");
1900 }
1901 return 0;
1902}
1903
1904size_t
1905Process::ReadScalarIntegerFromMemory (addr_t addr,
1906 uint32_t byte_size,
1907 bool is_signed,
1908 Scalar &scalar,
1909 Error &error)
1910{
1911 uint64_t uval;
1912
1913 if (byte_size <= sizeof(uval))
1914 {
1915 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1916 if (bytes_read == byte_size)
1917 {
1918 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1919 uint32_t offset = 0;
1920 if (byte_size <= 4)
1921 scalar = data.GetMaxU32 (&offset, byte_size);
1922 else
1923 scalar = data.GetMaxU64 (&offset, byte_size);
1924
1925 if (is_signed)
1926 scalar.SignExtend(byte_size * 8);
1927 return bytes_read;
1928 }
1929 }
1930 else
1931 {
1932 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1933 }
1934 return 0;
1935}
1936
Greg Claytond495c532011-05-17 03:37:42 +00001937#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938addr_t
1939Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1940{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00001941 if (GetPrivateState() != eStateStopped)
1942 return LLDB_INVALID_ADDRESS;
1943
Greg Claytond495c532011-05-17 03:37:42 +00001944#if defined (USE_ALLOCATE_MEMORY_CACHE)
1945 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1946#else
Greg Claytonb2daec92011-01-23 19:58:49 +00001947 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1948 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1949 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001950 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001951 size,
Greg Claytond495c532011-05-17 03:37:42 +00001952 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00001953 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00001954 m_mod_id.GetStopID(),
1955 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00001956 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00001957#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958}
1959
Sean Callanan90539452011-09-20 23:01:51 +00001960bool
1961Process::CanJIT ()
1962{
1963 return m_can_jit == eCanJITYes;
1964}
1965
1966void
1967Process::SetCanJIT (bool can_jit)
1968{
1969 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
1970}
1971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972Error
1973Process::DeallocateMemory (addr_t ptr)
1974{
Greg Claytond495c532011-05-17 03:37:42 +00001975 Error error;
1976#if defined (USE_ALLOCATE_MEMORY_CACHE)
1977 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
1978 {
1979 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
1980 }
1981#else
1982 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00001983
1984 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1985 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001986 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001987 ptr,
1988 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00001989 m_mod_id.GetStopID(),
1990 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00001991#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00001992 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001993}
1994
1995
1996Error
1997Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1998{
1999 Error error;
2000 error.SetErrorString("watchpoints are not supported");
2001 return error;
2002}
2003
2004Error
2005Process::DisableWatchpoint (WatchpointLocation *watchpoint)
2006{
2007 Error error;
2008 error.SetErrorString("watchpoints are not supported");
2009 return error;
2010}
2011
2012StateType
2013Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2014{
2015 StateType state;
2016 // Now wait for the process to launch and return control to us, and then
2017 // call DidLaunch:
2018 while (1)
2019 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002020 event_sp.reset();
2021 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2022
2023 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002025
2026 // If state is invalid, then we timed out
2027 if (state == eStateInvalid)
2028 break;
2029
2030 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031 HandlePrivateEvent (event_sp);
2032 }
2033 return state;
2034}
2035
2036Error
2037Process::Launch
2038(
2039 char const *argv[],
2040 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00002041 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002042 const char *stdin_path,
2043 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00002044 const char *stderr_path,
2045 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002046)
2047{
2048 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002049 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002050 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002051 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002052 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053
Greg Claytonaa149cb2011-08-11 02:48:45 +00002054 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055 if (exe_module)
2056 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002057 char local_exec_file_path[PATH_MAX];
2058 char platform_exec_file_path[PATH_MAX];
2059 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2060 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061 if (exe_module->GetFileSpec().Exists())
2062 {
Greg Clayton71337622011-02-24 22:24:29 +00002063 if (PrivateStateThreadIsValid ())
2064 PausePrivateStateThread ();
2065
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 error = WillLaunch (exe_module);
2067 if (error.Success())
2068 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002069 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002070 // The args coming in should not contain the application name, the
2071 // lldb_private::Process class will add this in case the executable
2072 // gets resolved to a different file than was given on the command
2073 // line (like when an applicaiton bundle is specified and will
2074 // resolve to the contained exectuable file, or the file given was
2075 // a symlink or other file system link that resolves to a different
2076 // file).
2077
2078 // Get the resolved exectuable path
2079
2080 // Make a new argument vector
2081 std::vector<const char *> exec_path_plus_argv;
2082 // Append the resolved executable path
Greg Clayton2289fa42011-04-30 01:09:13 +00002083 exec_path_plus_argv.push_back (platform_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002084
2085 // Push all args if there are any
2086 if (argv)
2087 {
2088 for (int i = 0; argv[i]; ++i)
2089 exec_path_plus_argv.push_back(argv[i]);
2090 }
2091
2092 // Push a NULL to terminate the args.
2093 exec_path_plus_argv.push_back(NULL);
2094
2095 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00002096 error = DoLaunch (exe_module,
2097 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
2098 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00002099 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00002100 stdin_path,
2101 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00002102 stderr_path,
2103 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104
2105 if (error.Fail())
2106 {
2107 if (GetID() != LLDB_INVALID_PROCESS_ID)
2108 {
2109 SetID (LLDB_INVALID_PROCESS_ID);
2110 const char *error_string = error.AsCString();
2111 if (error_string == NULL)
2112 error_string = "launch failed";
2113 SetExitStatus (-1, error_string);
2114 }
2115 }
2116 else
2117 {
2118 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002119 TimeValue timeout_time;
2120 timeout_time = TimeValue::Now();
2121 timeout_time.OffsetWithSeconds(10);
2122 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123
Greg Clayton1a38ea72011-06-22 01:42:17 +00002124 if (state == eStateInvalid || event_sp.get() == NULL)
2125 {
2126 // We were able to launch the process, but we failed to
2127 // catch the initial stop.
2128 SetExitStatus (0, "failed to catch stop after launch");
2129 Destroy();
2130 }
2131 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002132 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002133
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134 DidLaunch ();
2135
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002136 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002137 if (m_dyld_ap.get())
2138 m_dyld_ap->DidLaunch();
2139
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002140 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141 // This delays passing the stopped event to listeners till DidLaunch gets
2142 // a chance to complete...
2143 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002144
2145 if (PrivateStateThreadIsValid ())
2146 ResumePrivateStateThread ();
2147 else
2148 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149 }
2150 else if (state == eStateExited)
2151 {
2152 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2153 // not likely to work, and return an invalid pid.
2154 HandlePrivateEvent (event_sp);
2155 }
2156 }
2157 }
2158 }
2159 else
2160 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002161 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162 }
2163 }
2164 return error;
2165}
2166
Jim Inghambb3a2832011-01-29 01:49:25 +00002167Process::NextEventAction::EventActionResult
2168Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169{
Jim Inghambb3a2832011-01-29 01:49:25 +00002170 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2171 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002172 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002173 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002174 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002175 return eEventActionRetry;
2176
2177 case eStateStopped:
2178 case eStateCrashed:
Jim Ingham5aee1622010-08-09 23:31:02 +00002179 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002180 // During attach, prior to sending the eStateStopped event,
2181 // lldb_private::Process subclasses must set the process must set
2182 // the new process ID.
2183 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton93d3c8332011-02-16 04:46:07 +00002184 m_process->CompleteAttach ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002185 return eEventActionSuccess;
Jim Ingham5aee1622010-08-09 23:31:02 +00002186 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002187
2188
2189 break;
2190 default:
2191 case eStateExited:
2192 case eStateInvalid:
2193 m_exit_string.assign ("No valid Process");
2194 return eEventActionExit;
2195 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002196 }
2197}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002198
Jim Inghambb3a2832011-01-29 01:49:25 +00002199Process::NextEventAction::EventActionResult
2200Process::AttachCompletionHandler::HandleBeingInterrupted()
2201{
2202 return eEventActionSuccess;
2203}
2204
2205const char *
2206Process::AttachCompletionHandler::GetExitString ()
2207{
2208 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209}
2210
2211Error
2212Process::Attach (lldb::pid_t attach_pid)
2213{
2214
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002215 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002216 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217
Greg Clayton93d3c8332011-02-16 04:46:07 +00002218 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002219 m_os_ap.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002220
Greg Claytonc982c762010-07-09 20:39:50 +00002221 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222 if (error.Success())
2223 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002224 SetPublicState (eStateAttaching);
2225
Greg Claytonc982c762010-07-09 20:39:50 +00002226 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002227 if (error.Success())
2228 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002229 SetNextEventAction(new Process::AttachCompletionHandler(this));
2230 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 }
2232 else
2233 {
2234 if (GetID() != LLDB_INVALID_PROCESS_ID)
2235 {
2236 SetID (LLDB_INVALID_PROCESS_ID);
2237 const char *error_string = error.AsCString();
2238 if (error_string == NULL)
2239 error_string = "attach failed";
2240
2241 SetExitStatus(-1, error_string);
2242 }
2243 }
2244 }
2245 return error;
2246}
2247
2248Error
2249Process::Attach (const char *process_name, bool wait_for_launch)
2250{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002252 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002253
2254 // Find the process and its architecture. Make sure it matches the architecture
2255 // of the current Target, and if not adjust it.
Greg Claytone996fd32011-03-08 22:40:15 +00002256 Error error;
Jim Ingham5aee1622010-08-09 23:31:02 +00002257
Jim Ingham2ecb7422010-08-17 21:54:19 +00002258 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00002259 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002260 ProcessInstanceInfoList process_infos;
Jim Ingham4299fdb2011-09-15 01:10:17 +00002261 PlatformSP platform_sp (m_target.GetPlatform ());
2262 assert (platform_sp.get());
2263
Greg Claytone996fd32011-03-08 22:40:15 +00002264 if (platform_sp)
Jim Ingham2ecb7422010-08-17 21:54:19 +00002265 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002266 ProcessInstanceInfoMatch match_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002267 match_info.GetProcessInfo().SetName(process_name);
2268 match_info.SetNameMatchType (eNameMatchEquals);
2269 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone996fd32011-03-08 22:40:15 +00002270 if (process_infos.GetSize() > 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271 {
Greg Claytone996fd32011-03-08 22:40:15 +00002272 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
2273 }
2274 else if (process_infos.GetSize() == 0)
2275 {
2276 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
2277 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278 }
2279 else
Greg Claytone996fd32011-03-08 22:40:15 +00002280 {
2281 error.SetErrorString ("Invalid platform");
2282 }
2283 }
2284
2285 if (error.Success())
2286 {
2287 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002288 m_os_ap.reset();
Greg Claytone996fd32011-03-08 22:40:15 +00002289
2290 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2291 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 {
Greg Claytone996fd32011-03-08 22:40:15 +00002293 SetPublicState (eStateAttaching);
2294 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2295 if (error.Fail())
2296 {
2297 if (GetID() != LLDB_INVALID_PROCESS_ID)
2298 {
2299 SetID (LLDB_INVALID_PROCESS_ID);
2300 const char *error_string = error.AsCString();
2301 if (error_string == NULL)
2302 error_string = "attach failed";
2303
2304 SetExitStatus(-1, error_string);
2305 }
2306 }
2307 else
2308 {
2309 SetNextEventAction(new Process::AttachCompletionHandler(this));
2310 StartPrivateStateThread();
2311 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 }
2313 }
2314 return error;
2315}
2316
Greg Clayton93d3c8332011-02-16 04:46:07 +00002317void
2318Process::CompleteAttach ()
2319{
2320 // Let the process subclass figure out at much as it can about the process
2321 // before we go looking for a dynamic loader plug-in.
Jim Ingham8314c522011-09-15 21:36:42 +00002322 m_attached_to_process = true;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002323 DidAttach();
2324
Jim Ingham4299fdb2011-09-15 01:10:17 +00002325 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2326 // the same as the one we've already set, switch architectures.
2327 PlatformSP platform_sp (m_target.GetPlatform ());
2328 assert (platform_sp.get());
2329 if (platform_sp)
2330 {
2331 ProcessInstanceInfo process_info;
2332 platform_sp->GetProcessInfo (GetID(), process_info);
2333 const ArchSpec &process_arch = process_info.GetArchitecture();
2334 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2335 m_target.SetArchitecture (process_arch);
2336 }
2337
2338 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002339 // plug-in
Greg Clayton7a5388b2011-03-20 04:57:14 +00002340 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002341 if (m_dyld_ap.get())
2342 m_dyld_ap->DidAttach();
2343
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002344 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002345 // Figure out which one is the executable, and set that in our target:
2346 ModuleList &modules = m_target.GetImages();
2347
2348 size_t num_modules = modules.GetSize();
2349 for (int i = 0; i < num_modules; i++)
2350 {
2351 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002352 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002353 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002354 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002355 m_target.SetExecutableModule (module_sp, false);
2356 break;
2357 }
2358 }
2359}
2360
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361Error
Greg Claytonb766a732011-02-04 01:58:07 +00002362Process::ConnectRemote (const char *remote_url)
2363{
Greg Claytonb766a732011-02-04 01:58:07 +00002364 m_abi_sp.reset();
2365 m_process_input_reader.reset();
2366
2367 // Find the process and its architecture. Make sure it matches the architecture
2368 // of the current Target, and if not adjust it.
2369
2370 Error error (DoConnectRemote (remote_url));
2371 if (error.Success())
2372 {
Greg Clayton71337622011-02-24 22:24:29 +00002373 if (GetID() != LLDB_INVALID_PROCESS_ID)
2374 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002375 EventSP event_sp;
2376 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2377
2378 if (state == eStateStopped || state == eStateCrashed)
2379 {
2380 // If we attached and actually have a process on the other end, then
2381 // this ended up being the equivalent of an attach.
2382 CompleteAttach ();
2383
2384 // This delays passing the stopped event to listeners till
2385 // CompleteAttach gets a chance to complete...
2386 HandlePrivateEvent (event_sp);
2387
2388 }
Greg Clayton71337622011-02-24 22:24:29 +00002389 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002390
2391 if (PrivateStateThreadIsValid ())
2392 ResumePrivateStateThread ();
2393 else
2394 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002395 }
2396 return error;
2397}
2398
2399
2400Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401Process::Resume ()
2402{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002403 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002405 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002406 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002407 StateAsCString(m_public_state.GetValue()),
2408 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002409
2410 Error error (WillResume());
2411 // Tell the process it is about to resume before the thread list
2412 if (error.Success())
2413 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002414 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 // can let all of our threads know that they are about to be
2416 // resumed. Threads will each be called with
2417 // Thread::WillResume(StateType) where StateType contains the state
2418 // that they are supposed to have when the process is resumed
2419 // (suspended/running/stepping). Threads should also check
2420 // their resume signal in lldb::Thread::GetResumeSignal()
2421 // to see if they are suppoed to start back up with a signal.
2422 if (m_thread_list.WillResume())
2423 {
2424 error = DoResume();
2425 if (error.Success())
2426 {
2427 DidResume();
2428 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002429 if (log)
2430 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431 }
2432 }
2433 else
2434 {
Jim Ingham444586b2011-01-24 06:34:17 +00002435 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 }
2437 }
Jim Ingham444586b2011-01-24 06:34:17 +00002438 else if (log)
2439 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 return error;
2441}
2442
2443Error
2444Process::Halt ()
2445{
Jim Inghambb3a2832011-01-29 01:49:25 +00002446 // Pause our private state thread so we can ensure no one else eats
2447 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002448 Listener halt_listener ("lldb.process.halt_listener");
2449 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002450
Jim Inghambb3a2832011-01-29 01:49:25 +00002451 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002452 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002453
Greg Clayton513c26c2011-01-29 07:10:55 +00002454 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002455 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002456
Greg Clayton513c26c2011-01-29 07:10:55 +00002457 bool caused_stop = false;
2458
2459 // Ask the process subclass to actually halt our process
2460 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002461 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002462 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002463 if (m_public_state.GetValue() == eStateAttaching)
2464 {
2465 SetExitStatus(SIGKILL, "Cancelled async attach.");
2466 Destroy ();
2467 }
2468 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002469 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002470 // If "caused_stop" is true, then DoHalt stopped the process. If
2471 // "caused_stop" is false, the process was already stopped.
2472 // If the DoHalt caused the process to stop, then we want to catch
2473 // this event and set the interrupted bool to true before we pass
2474 // this along so clients know that the process was interrupted by
2475 // a halt command.
2476 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002477 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002478 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002479 TimeValue timeout_time;
2480 timeout_time = TimeValue::Now();
2481 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002482 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2483 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002484
Jim Ingham0f16e732011-02-08 05:20:59 +00002485 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002486 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002487 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002488 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002489 }
2490 else
2491 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002492 if (StateIsStoppedState (state))
2493 {
2494 // We caused the process to interrupt itself, so mark this
2495 // as such in the stop event so clients can tell an interrupted
2496 // process from a natural stop
2497 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2498 }
2499 else
2500 {
2501 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2502 if (log)
2503 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2504 error.SetErrorString ("Did not get stopped event after halt.");
2505 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002506 }
2507 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002508 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002509 }
2510 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002511 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002512 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002513 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002514
2515 // Post any event we might have consumed. If all goes well, we will have
2516 // stopped the process, intercepted the event and set the interrupted
2517 // bool in the event. Post it to the private event queue and that will end up
2518 // correctly setting the state.
2519 if (event_sp)
2520 m_private_state_broadcaster.BroadcastEvent(event_sp);
2521
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522 return error;
2523}
2524
2525Error
2526Process::Detach ()
2527{
2528 Error error (WillDetach());
2529
2530 if (error.Success())
2531 {
2532 DisableAllBreakpointSites();
2533 error = DoDetach();
2534 if (error.Success())
2535 {
2536 DidDetach();
2537 StopPrivateStateThread();
2538 }
2539 }
2540 return error;
2541}
2542
2543Error
2544Process::Destroy ()
2545{
2546 Error error (WillDestroy());
2547 if (error.Success())
2548 {
2549 DisableAllBreakpointSites();
2550 error = DoDestroy();
2551 if (error.Success())
2552 {
2553 DidDestroy();
2554 StopPrivateStateThread();
2555 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002556 m_stdio_communication.StopReadThread();
2557 m_stdio_communication.Disconnect();
2558 if (m_process_input_reader && m_process_input_reader->IsActive())
2559 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2560 if (m_process_input_reader)
2561 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002562 }
2563 return error;
2564}
2565
2566Error
2567Process::Signal (int signal)
2568{
2569 Error error (WillSignal());
2570 if (error.Success())
2571 {
2572 error = DoSignal(signal);
2573 if (error.Success())
2574 DidSignal();
2575 }
2576 return error;
2577}
2578
Greg Clayton514487e2011-02-15 21:59:32 +00002579lldb::ByteOrder
2580Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002581{
Greg Clayton514487e2011-02-15 21:59:32 +00002582 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583}
2584
2585uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002586Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002587{
Greg Clayton514487e2011-02-15 21:59:32 +00002588 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589}
2590
Greg Clayton514487e2011-02-15 21:59:32 +00002591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592bool
2593Process::ShouldBroadcastEvent (Event *event_ptr)
2594{
2595 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2596 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002597 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002598
2599 switch (state)
2600 {
Greg Claytonb766a732011-02-04 01:58:07 +00002601 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602 case eStateAttaching:
2603 case eStateLaunching:
2604 case eStateDetached:
2605 case eStateExited:
2606 case eStateUnloaded:
2607 // These events indicate changes in the state of the debugging session, always report them.
2608 return_value = true;
2609 break;
2610 case eStateInvalid:
2611 // We stopped for no apparent reason, don't report it.
2612 return_value = false;
2613 break;
2614 case eStateRunning:
2615 case eStateStepping:
2616 // If we've started the target running, we handle the cases where we
2617 // are already running and where there is a transition from stopped to
2618 // running differently.
2619 // running -> running: Automatically suppress extra running events
2620 // stopped -> running: Report except when there is one or more no votes
2621 // and no yes votes.
2622 SynchronouslyNotifyStateChanged (state);
2623 switch (m_public_state.GetValue())
2624 {
2625 case eStateRunning:
2626 case eStateStepping:
2627 // We always suppress multiple runnings with no PUBLIC stop in between.
2628 return_value = false;
2629 break;
2630 default:
2631 // TODO: make this work correctly. For now always report
2632 // run if we aren't running so we don't miss any runnning
2633 // events. If I run the lldb/test/thread/a.out file and
2634 // break at main.cpp:58, run and hit the breakpoints on
2635 // multiple threads, then somehow during the stepping over
2636 // of all breakpoints no run gets reported.
2637 return_value = true;
2638
2639 // This is a transition from stop to run.
2640 switch (m_thread_list.ShouldReportRun (event_ptr))
2641 {
2642 case eVoteYes:
2643 case eVoteNoOpinion:
2644 return_value = true;
2645 break;
2646 case eVoteNo:
2647 return_value = false;
2648 break;
2649 }
2650 break;
2651 }
2652 break;
2653 case eStateStopped:
2654 case eStateCrashed:
2655 case eStateSuspended:
2656 {
2657 // We've stopped. First see if we're going to restart the target.
2658 // If we are going to stop, then we always broadcast the event.
2659 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00002660 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002661 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002663 if (log)
2664 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002665 return true;
2666 }
2667 else
2668 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002669 RefreshStateAfterStop ();
2670
2671 if (m_thread_list.ShouldStop (event_ptr) == false)
2672 {
2673 switch (m_thread_list.ShouldReportStop (event_ptr))
2674 {
2675 case eVoteYes:
2676 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002677 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679 case eVoteNo:
2680 return_value = false;
2681 break;
2682 }
2683
2684 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002685 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686 Resume ();
2687 }
2688 else
2689 {
2690 return_value = true;
2691 SynchronouslyNotifyStateChanged (state);
2692 }
2693 }
2694 }
2695 }
2696
2697 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00002698 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699 return return_value;
2700}
2701
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702
2703bool
2704Process::StartPrivateStateThread ()
2705{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002706 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707
Greg Clayton8b82f082011-04-12 05:54:46 +00002708 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00002710 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2711
2712 if (already_running)
2713 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714
2715 // Create a thread that watches our internal state and controls which
2716 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002717 char thread_name[1024];
2718 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2719 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002720 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721}
2722
2723void
2724Process::PausePrivateStateThread ()
2725{
2726 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2727}
2728
2729void
2730Process::ResumePrivateStateThread ()
2731{
2732 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2733}
2734
2735void
2736Process::StopPrivateStateThread ()
2737{
Greg Clayton8b82f082011-04-12 05:54:46 +00002738 if (PrivateStateThreadIsValid ())
2739 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740}
2741
2742void
2743Process::ControlPrivateStateThread (uint32_t signal)
2744{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002745 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746
2747 assert (signal == eBroadcastInternalStateControlStop ||
2748 signal == eBroadcastInternalStateControlPause ||
2749 signal == eBroadcastInternalStateControlResume);
2750
2751 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002752 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002754 // Signal the private state thread. First we should copy this is case the
2755 // thread starts exiting since the private state thread will NULL this out
2756 // when it exits
2757 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002758 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759 {
2760 TimeValue timeout_time;
2761 bool timed_out;
2762
2763 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2764
2765 timeout_time = TimeValue::Now();
2766 timeout_time.OffsetWithSeconds(2);
2767 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2768 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2769
2770 if (signal == eBroadcastInternalStateControlStop)
2771 {
2772 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002773 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774
2775 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002776 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002777 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778 }
2779 }
2780}
2781
2782void
2783Process::HandlePrivateEvent (EventSP &event_sp)
2784{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002785 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002786
Greg Clayton414f5d32011-01-25 02:58:48 +00002787 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002788
2789 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002790 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002791 {
Jim Ingham754ab982011-01-29 04:05:41 +00002792 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002793 switch (action_result)
2794 {
2795 case NextEventAction::eEventActionSuccess:
2796 SetNextEventAction(NULL);
2797 break;
2798 case NextEventAction::eEventActionRetry:
2799 break;
2800 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002801 // Handle Exiting Here. If we already got an exited event,
2802 // we should just propagate it. Otherwise, swallow this event,
2803 // and set our state to exit so the next event will kill us.
2804 if (new_state != eStateExited)
2805 {
2806 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002807 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002808 SetNextEventAction(NULL);
2809 return;
2810 }
2811 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002812 break;
2813 }
2814 }
2815
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816 // See if we should broadcast this state to external clients?
2817 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818
2819 if (should_broadcast)
2820 {
2821 if (log)
2822 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002823 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2824 __FUNCTION__,
2825 GetID(),
2826 StateAsCString(new_state),
2827 StateAsCString (GetState ()),
2828 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002829 }
Jim Ingham9575d842011-03-11 03:53:59 +00002830 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00002831 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002832 PushProcessInputReader ();
2833 else
2834 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00002835
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002836 BroadcastEvent (event_sp);
2837 }
2838 else
2839 {
2840 if (log)
2841 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002842 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2843 __FUNCTION__,
2844 GetID(),
2845 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00002846 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002847 }
2848 }
2849}
2850
2851void *
2852Process::PrivateStateThread (void *arg)
2853{
2854 Process *proc = static_cast<Process*> (arg);
2855 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002856 return result;
2857}
2858
2859void *
2860Process::RunPrivateStateThread ()
2861{
2862 bool control_only = false;
2863 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2864
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002865 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002866 if (log)
2867 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2868
2869 bool exit_now = false;
2870 while (!exit_now)
2871 {
2872 EventSP event_sp;
2873 WaitForEventsPrivate (NULL, event_sp, control_only);
2874 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2875 {
2876 switch (event_sp->GetType())
2877 {
2878 case eBroadcastInternalStateControlStop:
2879 exit_now = true;
2880 continue; // Go to next loop iteration so we exit without
2881 break; // doing any internal state managment below
2882
2883 case eBroadcastInternalStateControlPause:
2884 control_only = true;
2885 break;
2886
2887 case eBroadcastInternalStateControlResume:
2888 control_only = false;
2889 break;
2890 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002891
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002892 if (log)
2893 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2894
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002896 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897 }
2898
2899
2900 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2901
2902 if (internal_state != eStateInvalid)
2903 {
2904 HandlePrivateEvent (event_sp);
2905 }
2906
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002907 if (internal_state == eStateInvalid ||
2908 internal_state == eStateExited ||
2909 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002910 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002911 if (log)
2912 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2913
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002914 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002915 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002916 }
2917
Caroline Tice20ad3c42010-10-29 21:48:37 +00002918 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919 if (log)
2920 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2921
Greg Clayton6ed95942011-01-22 07:12:45 +00002922 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2923 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002924 return NULL;
2925}
2926
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927//------------------------------------------------------------------
2928// Process Event Data
2929//------------------------------------------------------------------
2930
2931Process::ProcessEventData::ProcessEventData () :
2932 EventData (),
2933 m_process_sp (),
2934 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002935 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002936 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002937 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002938{
2939}
2940
2941Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2942 EventData (),
2943 m_process_sp (process_sp),
2944 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002945 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002946 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002947 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948{
2949}
2950
2951Process::ProcessEventData::~ProcessEventData()
2952{
2953}
2954
2955const ConstString &
2956Process::ProcessEventData::GetFlavorString ()
2957{
2958 static ConstString g_flavor ("Process::ProcessEventData");
2959 return g_flavor;
2960}
2961
2962const ConstString &
2963Process::ProcessEventData::GetFlavor () const
2964{
2965 return ProcessEventData::GetFlavorString ();
2966}
2967
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968void
2969Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2970{
2971 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00002972 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2973 // the public event queue, then other times when we're pretending that this is where we stopped at the
2974 // end of expression evaluation. m_update_state is used to distinguish these
2975 // three cases; it is 0 when we're just pulling it off for private handling,
2976 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002977
Jim Inghama8604692011-05-22 21:45:01 +00002978 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002979 return;
2980
2981 m_process_sp->SetPublicState (m_state);
2982
2983 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2984 if (m_state == eStateStopped && ! m_restarted)
2985 {
2986 int num_threads = m_process_sp->GetThreadList().GetSize();
2987 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002988
Jim Ingham4b536182011-08-09 02:12:22 +00002989 // The actions might change one of the thread's stop_info's opinions about whether we should
2990 // stop the process, so we need to query that as we go.
2991 bool still_should_stop = true;
2992
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002993 for (idx = 0; idx < num_threads; ++idx)
2994 {
2995 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2996
Jim Inghamb15bfc72010-10-20 00:39:53 +00002997 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2998 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003000 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003001 // The stop action might restart the target. If it does, then we want to mark that in the
3002 // event so that whoever is receiving it will know to wait for the running event and reflect
3003 // that state appropriately.
3004 // We also need to stop processing actions, since they aren't expecting the target to be running.
3005 if (m_process_sp->GetPrivateState() == eStateRunning)
3006 {
3007 SetRestarted (true);
3008 break;
3009 }
3010 else if (!stop_info_sp->ShouldStop(event_ptr))
3011 {
3012 still_should_stop = false;
3013 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014 }
3015 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003016
Jim Ingham4b536182011-08-09 02:12:22 +00003017
3018 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003019 {
Jim Ingham4b536182011-08-09 02:12:22 +00003020 if (!still_should_stop)
3021 {
3022 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003023 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003024 m_process_sp->Resume();
3025 }
3026 else
3027 {
3028 // If we didn't restart, run the Stop Hooks here:
3029 // They might also restart the target, so watch for that.
3030 m_process_sp->GetTarget().RunStopHooks();
3031 if (m_process_sp->GetPrivateState() == eStateRunning)
3032 SetRestarted(true);
3033 }
Jim Ingham9575d842011-03-11 03:53:59 +00003034 }
3035
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 }
3037}
3038
3039void
3040Process::ProcessEventData::Dump (Stream *s) const
3041{
3042 if (m_process_sp)
3043 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
3044
Greg Clayton8b82f082011-04-12 05:54:46 +00003045 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003046}
3047
3048const Process::ProcessEventData *
3049Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3050{
3051 if (event_ptr)
3052 {
3053 const EventData *event_data = event_ptr->GetData();
3054 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3055 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3056 }
3057 return NULL;
3058}
3059
3060ProcessSP
3061Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3062{
3063 ProcessSP process_sp;
3064 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3065 if (data)
3066 process_sp = data->GetProcessSP();
3067 return process_sp;
3068}
3069
3070StateType
3071Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3072{
3073 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3074 if (data == NULL)
3075 return eStateInvalid;
3076 else
3077 return data->GetState();
3078}
3079
3080bool
3081Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3082{
3083 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3084 if (data == NULL)
3085 return false;
3086 else
3087 return data->GetRestarted();
3088}
3089
3090void
3091Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3092{
3093 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3094 if (data != NULL)
3095 data->SetRestarted(new_value);
3096}
3097
3098bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003099Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3100{
3101 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3102 if (data == NULL)
3103 return false;
3104 else
3105 return data->GetInterrupted ();
3106}
3107
3108void
3109Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3110{
3111 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3112 if (data != NULL)
3113 data->SetInterrupted(new_value);
3114}
3115
3116bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3118{
3119 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3120 if (data)
3121 {
3122 data->SetUpdateStateOnRemoval();
3123 return true;
3124 }
3125 return false;
3126}
3127
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003128void
Greg Clayton0603aa92010-10-04 01:05:56 +00003129Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130{
Greg Claytonc14ee322011-09-22 04:58:26 +00003131 exe_ctx.SetTargetPtr (&m_target);
3132 exe_ctx.SetProcessPtr (this);
3133 exe_ctx.SetThreadPtr(NULL);
3134 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003135}
3136
3137lldb::ProcessSP
3138Process::GetSP ()
3139{
3140 return GetTarget().GetProcessSP();
3141}
3142
Greg Claytone996fd32011-03-08 22:40:15 +00003143//uint32_t
3144//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3145//{
3146// return 0;
3147//}
3148//
3149//ArchSpec
3150//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3151//{
3152// return Host::GetArchSpecForExistingProcess (pid);
3153//}
3154//
3155//ArchSpec
3156//Process::GetArchSpecForExistingProcess (const char *process_name)
3157//{
3158// return Host::GetArchSpecForExistingProcess (process_name);
3159//}
3160//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003161void
3162Process::AppendSTDOUT (const char * s, size_t len)
3163{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003164 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003165 m_stdout_data.append (s, len);
3166
Greg Claytona9ff3062010-12-05 19:16:56 +00003167 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003168}
3169
3170void
3171Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3172{
3173 Process *process = (Process *) baton;
3174 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3175}
3176
3177size_t
3178Process::ProcessInputReaderCallback (void *baton,
3179 InputReader &reader,
3180 lldb::InputReaderAction notification,
3181 const char *bytes,
3182 size_t bytes_len)
3183{
3184 Process *process = (Process *) baton;
3185
3186 switch (notification)
3187 {
3188 case eInputReaderActivate:
3189 break;
3190
3191 case eInputReaderDeactivate:
3192 break;
3193
3194 case eInputReaderReactivate:
3195 break;
3196
Caroline Tice969ed3d2011-05-02 20:41:46 +00003197 case eInputReaderAsynchronousOutputWritten:
3198 break;
3199
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003200 case eInputReaderGotToken:
3201 {
3202 Error error;
3203 process->PutSTDIN (bytes, bytes_len, error);
3204 }
3205 break;
3206
Caroline Ticeefed6132010-11-19 20:47:54 +00003207 case eInputReaderInterrupt:
3208 process->Halt ();
3209 break;
3210
3211 case eInputReaderEndOfFile:
3212 process->AppendSTDOUT ("^D", 2);
3213 break;
3214
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003215 case eInputReaderDone:
3216 break;
3217
3218 }
3219
3220 return bytes_len;
3221}
3222
3223void
3224Process::ResetProcessInputReader ()
3225{
3226 m_process_input_reader.reset();
3227}
3228
3229void
3230Process::SetUpProcessInputReader (int file_descriptor)
3231{
3232 // First set up the Read Thread for reading/handling process I/O
3233
3234 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3235
3236 if (conn_ap.get())
3237 {
3238 m_stdio_communication.SetConnection (conn_ap.release());
3239 if (m_stdio_communication.IsConnected())
3240 {
3241 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3242 m_stdio_communication.StartReadThread();
3243
3244 // Now read thread is set up, set up input reader.
3245
3246 if (!m_process_input_reader.get())
3247 {
3248 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3249 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3250 this,
3251 eInputReaderGranularityByte,
3252 NULL,
3253 NULL,
3254 false));
3255
3256 if (err.Fail())
3257 m_process_input_reader.reset();
3258 }
3259 }
3260 }
3261}
3262
3263void
3264Process::PushProcessInputReader ()
3265{
3266 if (m_process_input_reader && !m_process_input_reader->IsActive())
3267 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3268}
3269
3270void
3271Process::PopProcessInputReader ()
3272{
3273 if (m_process_input_reader && m_process_input_reader->IsActive())
3274 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3275}
3276
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003277// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003278void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003279Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003280{
Greg Claytone0d378b2011-03-24 21:19:54 +00003281 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003282
3283 int i=0;
3284 const char *name;
3285 OptionEnumValueElement option_enum;
3286 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3287 {
3288 if (name)
3289 {
3290 option_enum.value = i;
3291 option_enum.string_value = name;
3292 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3293 g_plugins.push_back (option_enum);
3294 }
3295 ++i;
3296 }
3297 option_enum.value = 0;
3298 option_enum.string_value = NULL;
3299 option_enum.usage = NULL;
3300 g_plugins.push_back (option_enum);
3301
3302 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3303 {
3304 if (::strcmp (name, "plugin") == 0)
3305 {
3306 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3307 break;
3308 }
3309 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003310 UserSettingsControllerSP &usc = GetSettingsController();
3311 usc.reset (new SettingsController);
3312 UserSettingsController::InitializeSettingsController (usc,
3313 SettingsController::global_settings_table,
3314 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003315
3316 // Now call SettingsInitialize() for each 'child' of Process settings
3317 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003318}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003319
Greg Clayton99d0faf2010-11-18 23:32:35 +00003320void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003321Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003322{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003323 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3324
3325 Thread::SettingsTerminate ();
3326
3327 // Now terminate Process Settings.
3328
Greg Clayton99d0faf2010-11-18 23:32:35 +00003329 UserSettingsControllerSP &usc = GetSettingsController();
3330 UserSettingsController::FinalizeSettingsController (usc);
3331 usc.reset();
3332}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003333
Greg Clayton99d0faf2010-11-18 23:32:35 +00003334UserSettingsControllerSP &
3335Process::GetSettingsController ()
3336{
3337 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003338 return g_settings_controller;
3339}
3340
Caroline Tice1559a462010-09-27 00:30:10 +00003341void
3342Process::UpdateInstanceName ()
3343{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003344 Module *module = GetTarget().GetExecutableModulePointer();
3345 if (module)
Caroline Tice1559a462010-09-27 00:30:10 +00003346 {
3347 StreamString sstr;
Greg Claytonaa149cb2011-08-11 02:48:45 +00003348 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003349
Greg Claytondbe54502010-11-19 03:46:01 +00003350 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton8b82f082011-04-12 05:54:46 +00003351 sstr.GetData());
Caroline Tice1559a462010-09-27 00:30:10 +00003352 }
3353}
3354
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003355ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003356Process::RunThreadPlan (ExecutionContext &exe_ctx,
3357 lldb::ThreadPlanSP &thread_plan_sp,
3358 bool stop_others,
3359 bool try_all_threads,
3360 bool discard_on_error,
3361 uint32_t single_thread_timeout_usec,
3362 Stream &errors)
3363{
3364 ExecutionResults return_value = eExecutionSetupError;
3365
Jim Ingham77787032011-01-20 02:03:18 +00003366 if (thread_plan_sp.get() == NULL)
3367 {
3368 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003369 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003370 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003371
3372 if (exe_ctx.GetProcessPtr() != this)
3373 {
3374 errors.Printf("RunThreadPlan called on wrong process.");
3375 return eExecutionSetupError;
3376 }
3377
3378 Thread *thread = exe_ctx.GetThreadPtr();
3379 if (thread == NULL)
3380 {
3381 errors.Printf("RunThreadPlan called with invalid thread.");
3382 return eExecutionSetupError;
3383 }
Jim Ingham77787032011-01-20 02:03:18 +00003384
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003385 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3386 // For that to be true the plan can't be private - since private plans suppress themselves in the
3387 // GetCompletedPlan call.
3388
3389 bool orig_plan_private = thread_plan_sp->GetPrivate();
3390 thread_plan_sp->SetPrivate(false);
3391
Jim Ingham444586b2011-01-24 06:34:17 +00003392 if (m_private_state.GetValue() != eStateStopped)
3393 {
3394 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003395 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003396 }
3397
Jim Ingham66243842011-08-13 00:56:10 +00003398 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003399 const uint32_t thread_idx_id = thread->GetIndexID();
3400 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003401
3402 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3403 // so we should arrange to reset them as well.
3404
Greg Claytonc14ee322011-09-22 04:58:26 +00003405 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003406
Jim Ingham66243842011-08-13 00:56:10 +00003407 uint32_t selected_tid;
3408 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003409 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003410 {
3411 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003412 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003413 }
3414 else
3415 {
3416 selected_tid = LLDB_INVALID_THREAD_ID;
3417 }
3418
Greg Claytonc14ee322011-09-22 04:58:26 +00003419 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003420
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003421 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003422
3423 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3424 // restored on exit to the function.
3425
3426 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003427
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003428 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003429 if (log)
3430 {
3431 StreamString s;
3432 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham0f16e732011-02-08 05:20:59 +00003433 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003434 thread->GetIndexID(),
3435 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003436 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003437 }
3438
Jim Ingham0f16e732011-02-08 05:20:59 +00003439 bool got_event;
3440 lldb::EventSP event_sp;
3441 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003442
3443 TimeValue* timeout_ptr = NULL;
3444 TimeValue real_timeout;
3445
Jim Ingham0f16e732011-02-08 05:20:59 +00003446 bool first_timeout = true;
3447 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003448
Jim Inghamf48169b2010-11-30 02:22:11 +00003449 while (1)
3450 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003451 // We usually want to resume the process if we get to the top of the loop.
3452 // The only exception is if we get two running events with no intervening
3453 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003454
Jim Ingham0f16e732011-02-08 05:20:59 +00003455 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003456 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003457 // Do the initial resume and wait for the running event before going further.
3458
Greg Claytonc14ee322011-09-22 04:58:26 +00003459 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003460 if (!resume_error.Success())
3461 {
3462 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003463 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003464 break;
3465 }
3466
3467 real_timeout = TimeValue::Now();
3468 real_timeout.OffsetWithMicroSeconds(500000);
3469 timeout_ptr = &real_timeout;
3470
3471 got_event = listener.WaitForEvent(NULL, event_sp);
3472 if (!got_event)
3473 {
3474 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003475 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003476
3477 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003478 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003479 break;
3480 }
3481
3482 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3483 if (stop_state != eStateRunning)
3484 {
3485 if (log)
3486 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3487
3488 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003489 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003490 break;
3491 }
3492
3493 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003494 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003495 // We need to call the function synchronously, so spin waiting for it to return.
3496 // If we get interrupted while executing, we're going to lose our context, and
3497 // won't be able to gather the result at this point.
3498 // We set the timeout AFTER the resume, since the resume takes some time and we
3499 // don't want to charge that to the timeout.
3500
3501 if (single_thread_timeout_usec != 0)
3502 {
3503 real_timeout = TimeValue::Now();
3504 if (first_timeout)
3505 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3506 else
3507 real_timeout.OffsetWithSeconds(10);
3508
3509 timeout_ptr = &real_timeout;
3510 }
3511 }
3512 else
3513 {
3514 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003515 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003516 do_resume = true;
3517 }
3518
3519 // Now wait for the process to stop again:
3520 stop_state = lldb::eStateInvalid;
3521 event_sp.reset();
3522 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3523
3524 if (got_event)
3525 {
3526 if (event_sp.get())
3527 {
3528 bool keep_going = false;
3529 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3530 if (log)
3531 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3532
3533 switch (stop_state)
3534 {
3535 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003536 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003537 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003538 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003539 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003540 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003541 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003542 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003543 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3544 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003545 }
3546 else
3547 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003548 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3549 StopReason stop_reason = eStopReasonInvalid;
3550 if (stop_info_sp)
3551 stop_reason = stop_info_sp->GetStopReason();
3552 if (stop_reason == eStopReasonPlanComplete)
3553 {
3554 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003555 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003556 // Now mark this plan as private so it doesn't get reported as the stop reason
3557 // after this point.
3558 if (thread_plan_sp)
3559 thread_plan_sp->SetPrivate (orig_plan_private);
3560 return_value = eExecutionCompleted;
3561 }
3562 else
3563 {
3564 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003565 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003566
3567 return_value = eExecutionInterrupted;
3568 }
Jim Ingham160f78c2011-05-17 01:10:11 +00003569 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00003570 }
3571 break;
3572
Jim Ingham0f16e732011-02-08 05:20:59 +00003573 case lldb::eStateCrashed:
3574 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003575 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003576 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003577 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003578
Jim Ingham0f16e732011-02-08 05:20:59 +00003579 case lldb::eStateRunning:
3580 do_resume = false;
3581 keep_going = true;
3582 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003583
Jim Ingham0f16e732011-02-08 05:20:59 +00003584 default:
3585 if (log)
3586 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00003587
3588 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003589 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003590 break;
3591 }
3592 if (keep_going)
3593 continue;
3594 else
3595 break;
3596 }
3597 else
3598 {
3599 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003600 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00003601 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003602 break;
3603 }
3604 }
3605 else
3606 {
3607 // If we didn't get an event that means we've timed out...
3608 // We will interrupt the process here. Depending on what we were asked to do we will
3609 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00003610 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00003611
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003612 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00003613 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00003614 {
3615 if (first_timeout)
3616 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3617 "trying with all threads enabled.",
3618 single_thread_timeout_usec);
3619 else
3620 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3621 "and timeout: %d timed out.",
3622 single_thread_timeout_usec);
3623 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003624 else
Jim Ingham0f16e732011-02-08 05:20:59 +00003625 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3626 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00003627 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003628 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003629
Greg Claytonc14ee322011-09-22 04:58:26 +00003630 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00003631 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00003632 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003633 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003634 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003635
Jim Ingham0f16e732011-02-08 05:20:59 +00003636 // If halt succeeds, it always produces a stopped event. Wait for that:
3637
3638 real_timeout = TimeValue::Now();
3639 real_timeout.OffsetWithMicroSeconds(500000);
3640
3641 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00003642
3643 if (got_event)
3644 {
3645 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3646 if (log)
3647 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003648 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00003649 if (stop_state == lldb::eStateStopped
3650 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00003651 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003652 }
3653
Jim Ingham0f16e732011-02-08 05:20:59 +00003654 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00003655 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003656 // Between the time we initiated the Halt and the time we delivered it, the process could have
3657 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00003658
Greg Claytonc14ee322011-09-22 04:58:26 +00003659 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003660 {
3661 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003662 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003663 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003664 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003665 break;
3666 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003667
Jim Ingham0f16e732011-02-08 05:20:59 +00003668 if (!try_all_threads)
3669 {
3670 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003671 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003672 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003673 break;
3674 }
3675
3676 if (first_timeout)
3677 {
3678 // Set all the other threads to run, and return to the top of the loop, which will continue;
3679 first_timeout = false;
3680 thread_plan_sp->SetStopOthers (false);
3681 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003682 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003683
3684 continue;
3685 }
3686 else
3687 {
3688 // Running all threads failed, so return Interrupted.
3689 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003690 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003691 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003692 break;
3693 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003694 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003695 }
3696 else
3697 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003698 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003699 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003700 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003701 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00003702 }
3703 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003704 else
3705 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003706 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3707 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00003708 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003709 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.",
3710 halt_error.AsCString());
3711 real_timeout = TimeValue::Now();
3712 real_timeout.OffsetWithMicroSeconds(500000);
3713 timeout_ptr = &real_timeout;
3714 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3715 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003716 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003717 // This is not going anywhere, bag out.
3718 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003719 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003720 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003721 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003722 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003723 else
3724 {
3725 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3726 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003727 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00003728 if (stop_state == lldb::eStateStopped)
3729 {
3730 // Between the time we initiated the Halt and the time we delivered it, the process could have
3731 // already finished its job. Check that here:
3732
Greg Claytonc14ee322011-09-22 04:58:26 +00003733 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003734 {
3735 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003736 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003737 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003738 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003739 break;
3740 }
3741
3742 if (first_timeout)
3743 {
3744 // Set all the other threads to run, and return to the top of the loop, which will continue;
3745 first_timeout = false;
3746 thread_plan_sp->SetStopOthers (false);
3747 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003748 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003749
3750 continue;
3751 }
3752 else
3753 {
3754 // Running all threads failed, so return Interrupted.
3755 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003756 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003757 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003758 break;
3759 }
3760 }
3761 else
3762 {
Sean Callanan39821ac2011-08-09 22:07:08 +00003763 if (log)
3764 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3765 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003766 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003767 break;
3768 }
3769 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003770 }
3771
Jim Inghamf48169b2010-11-30 02:22:11 +00003772 }
3773
Jim Ingham0f16e732011-02-08 05:20:59 +00003774 } // END WAIT LOOP
3775
3776 // Now do some processing on the results of the run:
3777 if (return_value == eExecutionInterrupted)
3778 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003779 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003780 {
3781 StreamString s;
3782 if (event_sp)
3783 event_sp->Dump (&s);
3784 else
3785 {
Jim Ingham20829ac2011-08-09 22:24:33 +00003786 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003787 }
3788
3789 StreamString ts;
3790
Jim Ingham20829ac2011-08-09 22:24:33 +00003791 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00003792
3793 do
3794 {
3795 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3796
3797 if (!event_data)
3798 {
3799 event_explanation = "<no event data>";
3800 break;
3801 }
3802
3803 Process *process = event_data->GetProcessSP().get();
3804
3805 if (!process)
3806 {
3807 event_explanation = "<no process>";
3808 break;
3809 }
3810
3811 ThreadList &thread_list = process->GetThreadList();
3812
3813 uint32_t num_threads = thread_list.GetSize();
3814 uint32_t thread_index;
3815
3816 ts.Printf("<%u threads> ", num_threads);
3817
3818 for (thread_index = 0;
3819 thread_index < num_threads;
3820 ++thread_index)
3821 {
3822 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3823
3824 if (!thread)
3825 {
3826 ts.Printf("<?> ");
3827 continue;
3828 }
3829
3830 ts.Printf("<0x%4.4x ", thread->GetID());
3831 RegisterContext *register_context = thread->GetRegisterContext().get();
3832
3833 if (register_context)
3834 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3835 else
3836 ts.Printf("[ip unknown] ");
3837
3838 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3839 if (stop_info_sp)
3840 {
3841 const char *stop_desc = stop_info_sp->GetDescription();
3842 if (stop_desc)
3843 ts.PutCString (stop_desc);
3844 }
3845 ts.Printf(">");
3846 }
3847
3848 event_explanation = ts.GetData();
3849 } while (0);
3850
3851 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003852 {
3853 if (event_explanation)
3854 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3855 else
3856 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3857 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003858
3859 if (discard_on_error && thread_plan_sp)
3860 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003861 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003862 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003863 }
3864 }
3865 }
3866 else if (return_value == eExecutionSetupError)
3867 {
3868 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003869 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003870
3871 if (discard_on_error && thread_plan_sp)
3872 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003873 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003874 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003875 }
3876 }
3877 else
3878 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003879 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00003880 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003881 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003882 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00003883 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00003884 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003885 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00003886 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003887 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003888 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00003889 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00003890 }
3891 else
3892 {
3893 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003894 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00003895 if (discard_on_error && thread_plan_sp)
3896 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003897 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003898 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00003899 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003900 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00003901 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003902 }
3903 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003904
Jim Inghamf48169b2010-11-30 02:22:11 +00003905 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00003906 // Check that it's still there, and if it is put it back in the context. Also restore the
3907 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00003908 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
3909 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00003910 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003911 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00003912 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003913
3914 // Also restore the current process'es selected frame & thread, since this function calling may
3915 // be done behind the user's back.
3916
3917 if (selected_tid != LLDB_INVALID_THREAD_ID)
3918 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003919 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00003920 {
3921 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00003922 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00003923 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00003924 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00003925 }
3926 }
3927
3928 return return_value;
3929}
3930
3931const char *
3932Process::ExecutionResultAsCString (ExecutionResults result)
3933{
3934 const char *result_name;
3935
3936 switch (result)
3937 {
Greg Claytone0d378b2011-03-24 21:19:54 +00003938 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003939 result_name = "eExecutionCompleted";
3940 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003941 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00003942 result_name = "eExecutionDiscarded";
3943 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003944 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003945 result_name = "eExecutionInterrupted";
3946 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003947 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00003948 result_name = "eExecutionSetupError";
3949 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003950 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00003951 result_name = "eExecutionTimedOut";
3952 break;
3953 }
3954 return result_name;
3955}
3956
Greg Clayton7260f622011-04-18 08:33:37 +00003957void
3958Process::GetStatus (Stream &strm)
3959{
3960 const StateType state = GetState();
3961 if (StateIsStoppedState(state))
3962 {
3963 if (state == eStateExited)
3964 {
3965 int exit_status = GetExitStatus();
3966 const char *exit_description = GetExitDescription();
3967 strm.Printf ("Process %d exited with status = %i (0x%8.8x) %s\n",
3968 GetID(),
3969 exit_status,
3970 exit_status,
3971 exit_description ? exit_description : "");
3972 }
3973 else
3974 {
3975 if (state == eStateConnected)
3976 strm.Printf ("Connected to remote target.\n");
3977 else
3978 strm.Printf ("Process %d %s\n", GetID(), StateAsCString (state));
3979 }
3980 }
3981 else
3982 {
3983 strm.Printf ("Process %d is running.\n", GetID());
3984 }
3985}
3986
3987size_t
3988Process::GetThreadStatus (Stream &strm,
3989 bool only_threads_with_stop_reason,
3990 uint32_t start_frame,
3991 uint32_t num_frames,
3992 uint32_t num_frames_with_source)
3993{
3994 size_t num_thread_infos_dumped = 0;
3995
3996 const size_t num_threads = GetThreadList().GetSize();
3997 for (uint32_t i = 0; i < num_threads; i++)
3998 {
3999 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4000 if (thread)
4001 {
4002 if (only_threads_with_stop_reason)
4003 {
4004 if (thread->GetStopInfo().get() == NULL)
4005 continue;
4006 }
4007 thread->GetStatus (strm,
4008 start_frame,
4009 num_frames,
4010 num_frames_with_source);
4011 ++num_thread_infos_dumped;
4012 }
4013 }
4014 return num_thread_infos_dumped;
4015}
4016
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004017//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004018// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004019//--------------------------------------------------------------
4020
Greg Clayton1b654882010-09-19 02:33:57 +00004021Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004022 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004023{
Greg Clayton85851dd2010-12-04 00:10:17 +00004024 m_default_settings.reset (new ProcessInstanceSettings (*this,
4025 false,
Caroline Tice91123da2010-09-08 17:48:55 +00004026 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004027}
4028
Greg Clayton1b654882010-09-19 02:33:57 +00004029Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004030{
4031}
4032
4033lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004034Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004035{
Greg Claytondbe54502010-11-19 03:46:01 +00004036 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4037 false,
4038 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004039 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4040 return new_settings_sp;
4041}
4042
4043//--------------------------------------------------------------
4044// class ProcessInstanceSettings
4045//--------------------------------------------------------------
4046
Greg Clayton85851dd2010-12-04 00:10:17 +00004047ProcessInstanceSettings::ProcessInstanceSettings
4048(
4049 UserSettingsController &owner,
4050 bool live_instance,
4051 const char *name
4052) :
4053 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004054 m_run_args (),
4055 m_env_vars (),
4056 m_input_path (),
4057 m_output_path (),
4058 m_error_path (),
Caroline Ticef8da8632010-12-03 18:46:09 +00004059 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00004060 m_disable_stdio (false),
4061 m_inherit_host_env (true),
4062 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004063{
Caroline Ticef20e8232010-09-09 18:26:37 +00004064 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4065 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4066 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00004067 // This is true for CreateInstanceName() too.
4068
4069 if (GetInstanceName () == InstanceSettings::InvalidName())
4070 {
4071 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4072 m_owner.RegisterInstanceSettings (this);
4073 }
Caroline Ticef20e8232010-09-09 18:26:37 +00004074
4075 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004076 {
4077 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4078 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00004079 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004080 }
4081}
4082
4083ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00004084 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004085 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 Ticef8da8632010-12-03 18:46:09 +00004090 m_disable_aslr (rhs.m_disable_aslr),
4091 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004092{
4093 if (m_instance_name != InstanceSettings::GetDefaultName())
4094 {
4095 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4096 CopyInstanceSettings (pending_settings,false);
4097 m_owner.RemovePendingSettings (m_instance_name);
4098 }
4099}
4100
4101ProcessInstanceSettings::~ProcessInstanceSettings ()
4102{
4103}
4104
4105ProcessInstanceSettings&
4106ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4107{
4108 if (this != &rhs)
4109 {
4110 m_run_args = rhs.m_run_args;
4111 m_env_vars = rhs.m_env_vars;
4112 m_input_path = rhs.m_input_path;
4113 m_output_path = rhs.m_output_path;
4114 m_error_path = rhs.m_error_path;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004115 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00004116 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00004117 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004118 }
4119
4120 return *this;
4121}
4122
4123
4124void
4125ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4126 const char *index_value,
4127 const char *value,
4128 const ConstString &instance_name,
4129 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004130 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004131 Error &err,
4132 bool pending)
4133{
4134 if (var_name == RunArgsVarName())
4135 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
4136 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00004137 {
Greg Clayton8b82f082011-04-12 05:54:46 +00004138 // This is nice for local debugging, but it is isn't correct for
4139 // remote debugging. We need to stop process.env-vars from being
4140 // populated with the host environment and add this as a launch option
4141 // and get the correct environment from the Target's platform.
4142 // GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004143 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00004144 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004145 else if (var_name == InputPathVarName())
4146 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
4147 else if (var_name == OutputPathVarName())
4148 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
4149 else if (var_name == ErrorPathVarName())
4150 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004151 else if (var_name == DisableASLRVarName())
Greg Clayton385aa282011-04-22 03:55:06 +00004152 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00004153 else if (var_name == DisableSTDIOVarName ())
Greg Clayton385aa282011-04-22 03:55:06 +00004154 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004155}
4156
4157void
4158ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4159 bool pending)
4160{
4161 if (new_settings.get() == NULL)
4162 return;
4163
4164 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4165
4166 m_run_args = new_process_settings->m_run_args;
4167 m_env_vars = new_process_settings->m_env_vars;
4168 m_input_path = new_process_settings->m_input_path;
4169 m_output_path = new_process_settings->m_output_path;
4170 m_error_path = new_process_settings->m_error_path;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004171 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00004172 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004173}
4174
Caroline Tice12cecd72010-09-20 21:37:42 +00004175bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004176ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4177 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004178 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004179 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004180{
4181 if (var_name == RunArgsVarName())
4182 {
4183 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00004184 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004185 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4186 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00004187 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004188 }
4189 else if (var_name == EnvVarsVarName())
4190 {
Greg Clayton85851dd2010-12-04 00:10:17 +00004191 GetHostEnvironmentIfNeeded ();
4192
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004193 if (m_env_vars.size() > 0)
4194 {
4195 std::map<std::string, std::string>::iterator pos;
4196 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4197 {
4198 StreamString value_str;
4199 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4200 value.AppendString (value_str.GetData());
4201 }
4202 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004203 }
4204 else if (var_name == InputPathVarName())
4205 {
4206 value.AppendString (m_input_path.c_str());
4207 }
4208 else if (var_name == OutputPathVarName())
4209 {
4210 value.AppendString (m_output_path.c_str());
4211 }
4212 else if (var_name == ErrorPathVarName())
4213 {
4214 value.AppendString (m_error_path.c_str());
4215 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00004216 else if (var_name == InheritHostEnvVarName())
4217 {
4218 if (m_inherit_host_env)
4219 value.AppendString ("true");
4220 else
4221 value.AppendString ("false");
4222 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004223 else if (var_name == DisableASLRVarName())
4224 {
4225 if (m_disable_aslr)
4226 value.AppendString ("true");
4227 else
4228 value.AppendString ("false");
4229 }
Caroline Ticef8da8632010-12-03 18:46:09 +00004230 else if (var_name == DisableSTDIOVarName())
4231 {
4232 if (m_disable_stdio)
4233 value.AppendString ("true");
4234 else
4235 value.AppendString ("false");
4236 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004237 else
Caroline Tice12cecd72010-09-20 21:37:42 +00004238 {
4239 if (err)
4240 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4241 return false;
4242 }
4243 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004244}
4245
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004246const ConstString
4247ProcessInstanceSettings::CreateInstanceName ()
4248{
4249 static int instance_count = 1;
4250 StreamString sstr;
4251
4252 sstr.Printf ("process_%d", instance_count);
4253 ++instance_count;
4254
4255 const ConstString ret_val (sstr.GetData());
4256 return ret_val;
4257}
4258
4259const ConstString &
4260ProcessInstanceSettings::RunArgsVarName ()
4261{
4262 static ConstString run_args_var_name ("run-args");
4263
4264 return run_args_var_name;
4265}
4266
4267const ConstString &
4268ProcessInstanceSettings::EnvVarsVarName ()
4269{
4270 static ConstString env_vars_var_name ("env-vars");
4271
4272 return env_vars_var_name;
4273}
4274
4275const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00004276ProcessInstanceSettings::InheritHostEnvVarName ()
4277{
4278 static ConstString g_name ("inherit-env");
4279
4280 return g_name;
4281}
4282
4283const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004284ProcessInstanceSettings::InputPathVarName ()
4285{
4286 static ConstString input_path_var_name ("input-path");
4287
4288 return input_path_var_name;
4289}
4290
4291const ConstString &
4292ProcessInstanceSettings::OutputPathVarName ()
4293{
Caroline Tice49e27372010-09-07 18:35:40 +00004294 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004295
4296 return output_path_var_name;
4297}
4298
4299const ConstString &
4300ProcessInstanceSettings::ErrorPathVarName ()
4301{
Caroline Tice49e27372010-09-07 18:35:40 +00004302 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004303
4304 return error_path_var_name;
4305}
4306
4307const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004308ProcessInstanceSettings::DisableASLRVarName ()
4309{
4310 static ConstString disable_aslr_var_name ("disable-aslr");
4311
4312 return disable_aslr_var_name;
4313}
4314
Caroline Ticef8da8632010-12-03 18:46:09 +00004315const ConstString &
4316ProcessInstanceSettings::DisableSTDIOVarName ()
4317{
4318 static ConstString disable_stdio_var_name ("disable-stdio");
4319
4320 return disable_stdio_var_name;
4321}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004322
4323//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004324// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004325//--------------------------------------------------
4326
4327SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004328Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004329{
4330 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4331 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4332};
4333
4334
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004335SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004336Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004337{
Greg Clayton85851dd2010-12-04 00:10:17 +00004338 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
4339 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
4340 { "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." },
4341 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00004342 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
4343 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
4344 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004345 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00004346 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
4347 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
4348 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004349};
4350
4351
Jim Ingham5aee1622010-08-09 23:31:02 +00004352