1 //===-- 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"
17 #include "lldb/Core/ConnectionFileDescriptor.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/InputReader.h"
20 #include "lldb/Core/Log.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Expression/ClangUserExpression.h"
24 #include "lldb/Interpreter/CommandInterpreter.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Target/ABI.h"
27 #include "lldb/Target/DynamicLoader.h"
28 #include "lldb/Target/LanguageRuntime.h"
29 #include "lldb/Target/CPPLanguageRuntime.h"
30 #include "lldb/Target/ObjCLanguageRuntime.h"
31 #include "lldb/Target/Platform.h"
32 #include "lldb/Target/RegisterContext.h"
33 #include "lldb/Target/StopInfo.h"
34 #include "lldb/Target/Target.h"
35 #include "lldb/Target/TargetList.h"
36 #include "lldb/Target/Thread.h"
37 #include "lldb/Target/ThreadPlan.h"
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 void
43 ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
44 {
45     const char *cstr;
46     if (m_pid != LLDB_INVALID_PROCESS_ID)
47         s.Printf ("    pid = %i\n", m_pid);
48 
49     if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
50         s.Printf (" parent = %i\n", m_parent_pid);
51 
52     if (m_executable)
53     {
54         s.Printf ("   name = %s\n", m_executable.GetFilename().GetCString());
55         s.PutCString ("   file = ");
56         m_executable.Dump(&s);
57         s.EOL();
58     }
59     const uint32_t argc = m_arguments.GetArgumentCount();
60     if (argc > 0)
61     {
62         for (uint32_t i=0; i<argc; i++)
63         {
64             const char *arg = m_arguments.GetArgumentAtIndex(i);
65             if (i < 10)
66                 s.Printf (" arg[%u] = %s\n", i, arg);
67             else
68                 s.Printf ("arg[%u] = %s\n", i, arg);
69         }
70     }
71 
72     const uint32_t envc = m_environment.GetArgumentCount();
73     if (envc > 0)
74     {
75         for (uint32_t i=0; i<envc; i++)
76         {
77             const char *env = m_environment.GetArgumentAtIndex(i);
78             if (i < 10)
79                 s.Printf (" env[%u] = %s\n", i, env);
80             else
81                 s.Printf ("env[%u] = %s\n", i, env);
82         }
83     }
84 
85     if (m_arch.IsValid())
86         s.Printf ("   arch = %s\n", m_arch.GetTriple().str().c_str());
87 
88     if (m_uid != UINT32_MAX)
89     {
90         cstr = platform->GetUserName (m_uid);
91         s.Printf ("    uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
92     }
93     if (m_gid != UINT32_MAX)
94     {
95         cstr = platform->GetGroupName (m_gid);
96         s.Printf ("    gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
97     }
98     if (m_euid != UINT32_MAX)
99     {
100         cstr = platform->GetUserName (m_euid);
101         s.Printf ("   euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
102     }
103     if (m_egid != UINT32_MAX)
104     {
105         cstr = platform->GetGroupName (m_egid);
106         s.Printf ("   egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
107     }
108 }
109 
110 void
111 ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
112 {
113     const char *label;
114     if (show_args || verbose)
115         label = "ARGUMENTS";
116     else
117         label = "NAME";
118 
119     if (verbose)
120     {
121         s.Printf     ("PID    PARENT USER       GROUP      EFF USER   EFF GROUP  TRIPLE                   %s\n", label);
122         s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
123     }
124     else
125     {
126         s.Printf     ("PID    PARENT USER       ARCH    %s\n", label);
127         s.PutCString ("====== ====== ========== ======= ============================\n");
128     }
129 }
130 
131 void
132 ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
133 {
134     if (m_pid != LLDB_INVALID_PROCESS_ID)
135     {
136         const char *cstr;
137         s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
138 
139 
140         if (verbose)
141         {
142             cstr = platform->GetUserName (m_uid);
143             if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
144                 s.Printf ("%-10s ", cstr);
145             else
146                 s.Printf ("%-10u ", m_uid);
147 
148             cstr = platform->GetGroupName (m_gid);
149             if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
150                 s.Printf ("%-10s ", cstr);
151             else
152                 s.Printf ("%-10u ", m_gid);
153 
154             cstr = platform->GetUserName (m_euid);
155             if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
156                 s.Printf ("%-10s ", cstr);
157             else
158                 s.Printf ("%-10u ", m_euid);
159 
160             cstr = platform->GetGroupName (m_egid);
161             if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
162                 s.Printf ("%-10s ", cstr);
163             else
164                 s.Printf ("%-10u ", m_egid);
165             s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
166         }
167         else
168         {
169             s.Printf ("%-10s %.*-7s ",
170                       platform->GetUserName (m_euid),
171                       (int)m_arch.GetTriple().getArchName().size(),
172                       m_arch.GetTriple().getArchName().data());
173         }
174 
175         if (verbose || show_args)
176         {
177             const uint32_t argc = m_arguments.GetArgumentCount();
178             if (argc > 0)
179             {
180                 for (uint32_t i=0; i<argc; i++)
181                 {
182                     if (i > 0)
183                         s.PutChar (' ');
184                     s.PutCString (m_arguments.GetArgumentAtIndex(i));
185                 }
186             }
187         }
188         else
189         {
190             s.PutCString (GetName());
191         }
192 
193         s.EOL();
194     }
195 }
196 
197 
198 void
199 ProcessInfo::SetArgumentsFromArgs (const Args& args,
200                                        bool first_arg_is_executable,
201                                        bool first_arg_is_executable_and_argument)
202 {
203     // Copy all arguments
204     m_arguments = args;
205 
206     // Is the first argument the executable?
207     if (first_arg_is_executable)
208     {
209         const char *first_arg = args.GetArgumentAtIndex (0);
210         if (first_arg)
211         {
212             // Yes the first argument is an executable, set it as the executable
213             // in the launch options. Don't resolve the file path as the path
214             // could be a remote platform path
215             const bool resolve = false;
216             m_executable.SetFile(first_arg, resolve);
217 
218             // If argument zero is an executable and shouldn't be included
219             // in the arguments, remove it from the front of the arguments
220             if (first_arg_is_executable_and_argument == false)
221                 m_arguments.DeleteArgumentAtIndex (0);
222         }
223     }
224 }
225 
226 bool
227 ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
228 {
229     if ((read || write) && fd >= 0 && path && path[0])
230     {
231         m_action = eFileActionOpen;
232         m_fd = fd;
233         if (read && write)
234             m_arg = O_RDWR;
235         else if (read)
236             m_arg = O_RDONLY;
237         else
238             m_arg = O_WRONLY;
239         m_path.assign (path);
240         return true;
241     }
242     else
243     {
244         Clear();
245     }
246     return false;
247 }
248 
249 bool
250 ProcessLaunchInfo::FileAction::Close (int fd)
251 {
252     Clear();
253     if (fd >= 0)
254     {
255         m_action = eFileActionClose;
256         m_fd = fd;
257     }
258     return m_fd >= 0;
259 }
260 
261 
262 bool
263 ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
264 {
265     Clear();
266     if (fd >= 0 && dup_fd >= 0)
267     {
268         m_action = eFileActionDuplicate;
269         m_fd = fd;
270         m_arg = dup_fd;
271     }
272     return m_fd >= 0;
273 }
274 
275 
276 
277 bool
278 ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
279                                                         const FileAction *info,
280                                                         Log *log,
281                                                         Error& error)
282 {
283     if (info == NULL)
284         return false;
285 
286     switch (info->m_action)
287     {
288         case eFileActionNone:
289             error.Clear();
290             break;
291 
292         case eFileActionClose:
293             if (info->m_fd == -1)
294                 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
295             else
296             {
297                 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
298                                 eErrorTypePOSIX);
299                 if (log && (error.Fail() || log))
300                     error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
301                                    file_actions, info->m_fd);
302             }
303             break;
304 
305         case eFileActionDuplicate:
306             if (info->m_fd == -1)
307                 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
308             else if (info->m_arg == -1)
309                 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
310             else
311             {
312                 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
313                                 eErrorTypePOSIX);
314                 if (log && (error.Fail() || log))
315                     error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
316                                    file_actions, info->m_fd, info->m_arg);
317             }
318             break;
319 
320         case eFileActionOpen:
321             if (info->m_fd == -1)
322                 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
323             else
324             {
325                 int oflag = info->m_arg;
326                 mode_t mode = 0;
327 
328                 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
329                                                                     info->m_fd,
330                                                                     info->m_path.c_str(),
331                                                                     oflag,
332                                                                     mode),
333                                 eErrorTypePOSIX);
334                 if (error.Fail() || log)
335                     error.PutToLog(log,
336                                    "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
337                                    file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
338             }
339             break;
340 
341         default:
342             error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
343             break;
344     }
345     return error.Success();
346 }
347 
348 Error
349 ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
350 {
351     Error error;
352     char short_option = (char) m_getopt_table[option_idx].val;
353 
354     switch (short_option)
355     {
356         case 's':   // Stop at program entry point
357             launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
358             break;
359 
360         case 'e':   // STDERR for read + write
361             {
362                 ProcessLaunchInfo::FileAction action;
363                 if (action.Open(STDERR_FILENO, option_arg, true, true))
364                     launch_info.AppendFileAction (action);
365             }
366             break;
367 
368         case 'i':   // STDIN for read only
369             {
370                 ProcessLaunchInfo::FileAction action;
371                 if (action.Open(STDIN_FILENO, option_arg, true, false))
372                     launch_info.AppendFileAction (action);
373             }
374             break;
375 
376         case 'o':   // Open STDOUT for write only
377             {
378                 ProcessLaunchInfo::FileAction action;
379                 if (action.Open(STDOUT_FILENO, option_arg, false, true))
380                     launch_info.AppendFileAction (action);
381             }
382             break;
383 
384         case 'p':   // Process plug-in name
385             launch_info.SetProcessPluginName (option_arg);
386             break;
387 
388         case 'n':   // Disable STDIO
389             {
390                 ProcessLaunchInfo::FileAction action;
391                 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
392                     launch_info.AppendFileAction (action);
393                 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
394                     launch_info.AppendFileAction (action);
395                 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
396                     launch_info.AppendFileAction (action);
397             }
398             break;
399 
400         case 'w':
401             launch_info.SetWorkingDirectory (option_arg);
402             break;
403 
404         case 't':   // Open process in new terminal window
405             launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
406             break;
407 
408         case 'a':
409             launch_info.GetArchitecture().SetTriple (option_arg,
410                                                      m_interpreter.GetPlatform(true).get());
411             break;
412 
413         case 'A':
414             launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
415             break;
416 
417         case 'v':
418             launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
419             break;
420 
421         default:
422             error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
423             break;
424 
425     }
426     return error;
427 }
428 
429 OptionDefinition
430 ProcessLaunchCommandOptions::g_option_table[] =
431 {
432 { LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument,       NULL, 0, eArgTypeNone,          "Stop at the entry point of the program when launching a process."},
433 { LLDB_OPT_SET_ALL, false, "disable-aslr",  'A', no_argument,       NULL, 0, eArgTypeNone,          "Disable address space layout randomization when launching a process."},
434 { LLDB_OPT_SET_ALL, false, "plugin",        'p', required_argument, NULL, 0, eArgTypePlugin,        "Name of the process plugin you want to use."},
435 { LLDB_OPT_SET_ALL, false, "working-dir",   'w', required_argument, NULL, 0, eArgTypePath,          "Set the current working directory to <path> when running the inferior."},
436 { LLDB_OPT_SET_ALL, false, "arch",          'a', required_argument, NULL, 0, eArgTypeArchitecture,  "Set the architecture for the process to launch when ambiguous."},
437 { LLDB_OPT_SET_ALL, false, "environment",   'v', required_argument, NULL, 0, eArgTypeNone,          "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
438 
439 { LLDB_OPT_SET_1  , false, "stdin",         'i', required_argument, NULL, 0, eArgTypePath,    "Redirect stdin for the process to <path>."},
440 { LLDB_OPT_SET_1  , false, "stdout",        'o', required_argument, NULL, 0, eArgTypePath,    "Redirect stdout for the process to <path>."},
441 { LLDB_OPT_SET_1  , false, "stderr",        'e', required_argument, NULL, 0, eArgTypePath,    "Redirect stderr for the process to <path>."},
442 
443 { LLDB_OPT_SET_2  , false, "tty",           't', no_argument,       NULL, 0, eArgTypeNone,    "Start the process in a terminal (not supported on all platforms)."},
444 
445 { LLDB_OPT_SET_3  , false, "no-stdio",      'n', no_argument,       NULL, 0, eArgTypeNone,    "Do not set up for terminal I/O to go to running process."},
446 
447 { 0               , false, NULL,             0,  0,                 NULL, 0, eArgTypeNone,    NULL }
448 };
449 
450 
451 
452 bool
453 ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
454 {
455     if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
456         return true;
457     const char *match_name = m_match_info.GetName();
458     if (!match_name)
459         return true;
460 
461     return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
462 }
463 
464 bool
465 ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
466 {
467     if (!NameMatches (proc_info.GetName()))
468         return false;
469 
470     if (m_match_info.ProcessIDIsValid() &&
471         m_match_info.GetProcessID() != proc_info.GetProcessID())
472         return false;
473 
474     if (m_match_info.ParentProcessIDIsValid() &&
475         m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
476         return false;
477 
478     if (m_match_info.UserIDIsValid () &&
479         m_match_info.GetUserID() != proc_info.GetUserID())
480         return false;
481 
482     if (m_match_info.GroupIDIsValid () &&
483         m_match_info.GetGroupID() != proc_info.GetGroupID())
484         return false;
485 
486     if (m_match_info.EffectiveUserIDIsValid () &&
487         m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
488         return false;
489 
490     if (m_match_info.EffectiveGroupIDIsValid () &&
491         m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
492         return false;
493 
494     if (m_match_info.GetArchitecture().IsValid() &&
495         m_match_info.GetArchitecture() != proc_info.GetArchitecture())
496         return false;
497     return true;
498 }
499 
500 bool
501 ProcessInstanceInfoMatch::MatchAllProcesses () const
502 {
503     if (m_name_match_type != eNameMatchIgnore)
504         return false;
505 
506     if (m_match_info.ProcessIDIsValid())
507         return false;
508 
509     if (m_match_info.ParentProcessIDIsValid())
510         return false;
511 
512     if (m_match_info.UserIDIsValid ())
513         return false;
514 
515     if (m_match_info.GroupIDIsValid ())
516         return false;
517 
518     if (m_match_info.EffectiveUserIDIsValid ())
519         return false;
520 
521     if (m_match_info.EffectiveGroupIDIsValid ())
522         return false;
523 
524     if (m_match_info.GetArchitecture().IsValid())
525         return false;
526 
527     if (m_match_all_users)
528         return false;
529 
530     return true;
531 
532 }
533 
534 void
535 ProcessInstanceInfoMatch::Clear()
536 {
537     m_match_info.Clear();
538     m_name_match_type = eNameMatchIgnore;
539     m_match_all_users = false;
540 }
541 
542 //----------------------------------------------------------------------
543 // MemoryCache constructor
544 //----------------------------------------------------------------------
545 Process::MemoryCache::MemoryCache() :
546     m_cache_line_byte_size (512),
547     m_cache_mutex (Mutex::eMutexTypeRecursive),
548     m_cache ()
549 {
550 }
551 
552 //----------------------------------------------------------------------
553 // Destructor
554 //----------------------------------------------------------------------
555 Process::MemoryCache::~MemoryCache()
556 {
557 }
558 
559 void
560 Process::MemoryCache::Clear()
561 {
562     Mutex::Locker locker (m_cache_mutex);
563     m_cache.clear();
564 }
565 
566 void
567 Process::MemoryCache::Flush (addr_t addr, size_t size)
568 {
569     if (size == 0)
570         return;
571 
572     const uint32_t cache_line_byte_size = m_cache_line_byte_size;
573     const addr_t end_addr = (addr + size - 1);
574     const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
575     const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
576 
577     Mutex::Locker locker (m_cache_mutex);
578     if (m_cache.empty())
579         return;
580 
581     assert ((flush_start_addr % cache_line_byte_size) == 0);
582 
583     for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
584     {
585         collection::iterator pos = m_cache.find (curr_addr);
586         if (pos != m_cache.end())
587             m_cache.erase(pos);
588     }
589 }
590 
591 size_t
592 Process::MemoryCache::Read
593 (
594     Process *process,
595     addr_t addr,
596     void *dst,
597     size_t dst_len,
598     Error &error
599 )
600 {
601     size_t bytes_left = dst_len;
602     if (dst && bytes_left > 0)
603     {
604         const uint32_t cache_line_byte_size = m_cache_line_byte_size;
605         uint8_t *dst_buf = (uint8_t *)dst;
606         addr_t curr_addr = addr - (addr % cache_line_byte_size);
607         addr_t cache_offset = addr - curr_addr;
608         Mutex::Locker locker (m_cache_mutex);
609 
610         while (bytes_left > 0)
611         {
612             collection::const_iterator pos = m_cache.find (curr_addr);
613             collection::const_iterator end = m_cache.end ();
614 
615             if (pos != end)
616             {
617                 size_t curr_read_size = cache_line_byte_size - cache_offset;
618                 if (curr_read_size > bytes_left)
619                     curr_read_size = bytes_left;
620 
621                 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
622 
623                 bytes_left -= curr_read_size;
624                 curr_addr += curr_read_size + cache_offset;
625                 cache_offset = 0;
626 
627                 if (bytes_left > 0)
628                 {
629                     // Get sequential cache page hits
630                     for (++pos; (pos != end) && (bytes_left > 0); ++pos)
631                     {
632                         assert ((curr_addr % cache_line_byte_size) == 0);
633 
634                         if (pos->first != curr_addr)
635                             break;
636 
637                         curr_read_size = pos->second->GetByteSize();
638                         if (curr_read_size > bytes_left)
639                             curr_read_size = bytes_left;
640 
641                         memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
642 
643                         bytes_left -= curr_read_size;
644                         curr_addr += curr_read_size;
645 
646                         // We have a cache page that succeeded to read some bytes
647                         // but not an entire page. If this happens, we must cap
648                         // off how much data we are able to read...
649                         if (pos->second->GetByteSize() != cache_line_byte_size)
650                             return dst_len - bytes_left;
651                     }
652                 }
653             }
654 
655             // We need to read from the process
656 
657             if (bytes_left > 0)
658             {
659                 assert ((curr_addr % cache_line_byte_size) == 0);
660                 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
661                 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
662                                                                              data_buffer_heap_ap->GetBytes(),
663                                                                              data_buffer_heap_ap->GetByteSize(),
664                                                                              error);
665                 if (process_bytes_read == 0)
666                     return dst_len - bytes_left;
667 
668                 if (process_bytes_read != cache_line_byte_size)
669                     data_buffer_heap_ap->SetByteSize (process_bytes_read);
670                 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
671                 // We have read data and put it into the cache, continue through the
672                 // loop again to get the data out of the cache...
673             }
674         }
675     }
676 
677     return dst_len - bytes_left;
678 }
679 
680 Process*
681 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
682 {
683     ProcessCreateInstance create_callback = NULL;
684     if (plugin_name)
685     {
686         create_callback  = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
687         if (create_callback)
688         {
689             std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
690             if (debugger_ap->CanDebug(target))
691                 return debugger_ap.release();
692         }
693     }
694     else
695     {
696         for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
697         {
698             std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
699             if (debugger_ap->CanDebug(target))
700                 return debugger_ap.release();
701         }
702     }
703     return NULL;
704 }
705 
706 
707 //----------------------------------------------------------------------
708 // Process constructor
709 //----------------------------------------------------------------------
710 Process::Process(Target &target, Listener &listener) :
711     UserID (LLDB_INVALID_PROCESS_ID),
712     Broadcaster ("lldb.process"),
713     ProcessInstanceSettings (*GetSettingsController()),
714     m_target (target),
715     m_public_state (eStateUnloaded),
716     m_private_state (eStateUnloaded),
717     m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
718     m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
719     m_private_state_listener ("lldb.process.internal_state_listener"),
720     m_private_state_control_wait(),
721     m_private_state_thread (LLDB_INVALID_HOST_THREAD),
722     m_stop_id (0),
723     m_thread_index_id (0),
724     m_exit_status (-1),
725     m_exit_string (),
726     m_thread_list (this),
727     m_notifications (),
728     m_image_tokens (),
729     m_listener (listener),
730     m_breakpoint_site_list (),
731     m_dynamic_checkers_ap (),
732     m_unix_signals (),
733     m_abi_sp (),
734     m_process_input_reader (),
735     m_stdio_communication ("process.stdio"),
736     m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
737     m_stdout_data (),
738     m_memory_cache (),
739     m_next_event_action_ap()
740 {
741     UpdateInstanceName();
742 
743     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
744     if (log)
745         log->Printf ("%p Process::Process()", this);
746 
747     SetEventName (eBroadcastBitStateChanged, "state-changed");
748     SetEventName (eBroadcastBitInterrupt, "interrupt");
749     SetEventName (eBroadcastBitSTDOUT, "stdout-available");
750     SetEventName (eBroadcastBitSTDERR, "stderr-available");
751 
752     listener.StartListeningForEvents (this,
753                                       eBroadcastBitStateChanged |
754                                       eBroadcastBitInterrupt |
755                                       eBroadcastBitSTDOUT |
756                                       eBroadcastBitSTDERR);
757 
758     m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
759                                                      eBroadcastBitStateChanged);
760 
761     m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
762                                                      eBroadcastInternalStateControlStop |
763                                                      eBroadcastInternalStateControlPause |
764                                                      eBroadcastInternalStateControlResume);
765 }
766 
767 //----------------------------------------------------------------------
768 // Destructor
769 //----------------------------------------------------------------------
770 Process::~Process()
771 {
772     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
773     if (log)
774         log->Printf ("%p Process::~Process()", this);
775     StopPrivateStateThread();
776 }
777 
778 void
779 Process::Finalize()
780 {
781     // Do any cleanup needed prior to being destructed... Subclasses
782     // that override this method should call this superclass method as well.
783 
784     // We need to destroy the loader before the derived Process class gets destroyed
785     // since it is very likely that undoing the loader will require access to the real process.
786     if (m_dyld_ap.get() != NULL)
787         m_dyld_ap.reset();
788 }
789 
790 void
791 Process::RegisterNotificationCallbacks (const Notifications& callbacks)
792 {
793     m_notifications.push_back(callbacks);
794     if (callbacks.initialize != NULL)
795         callbacks.initialize (callbacks.baton, this);
796 }
797 
798 bool
799 Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
800 {
801     std::vector<Notifications>::iterator pos, end = m_notifications.end();
802     for (pos = m_notifications.begin(); pos != end; ++pos)
803     {
804         if (pos->baton == callbacks.baton &&
805             pos->initialize == callbacks.initialize &&
806             pos->process_state_changed == callbacks.process_state_changed)
807         {
808             m_notifications.erase(pos);
809             return true;
810         }
811     }
812     return false;
813 }
814 
815 void
816 Process::SynchronouslyNotifyStateChanged (StateType state)
817 {
818     std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
819     for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
820     {
821         if (notification_pos->process_state_changed)
822             notification_pos->process_state_changed (notification_pos->baton, this, state);
823     }
824 }
825 
826 // FIXME: We need to do some work on events before the general Listener sees them.
827 // For instance if we are continuing from a breakpoint, we need to ensure that we do
828 // the little "insert real insn, step & stop" trick.  But we can't do that when the
829 // event is delivered by the broadcaster - since that is done on the thread that is
830 // waiting for new events, so if we needed more than one event for our handling, we would
831 // stall.  So instead we do it when we fetch the event off of the queue.
832 //
833 
834 StateType
835 Process::GetNextEvent (EventSP &event_sp)
836 {
837     StateType state = eStateInvalid;
838 
839     if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
840         state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
841 
842     return state;
843 }
844 
845 
846 StateType
847 Process::WaitForProcessToStop (const TimeValue *timeout)
848 {
849     StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
850     return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
851 }
852 
853 
854 StateType
855 Process::WaitForState
856 (
857     const TimeValue *timeout,
858     const StateType *match_states, const uint32_t num_match_states
859 )
860 {
861     EventSP event_sp;
862     uint32_t i;
863     StateType state = GetState();
864     while (state != eStateInvalid)
865     {
866         // If we are exited or detached, we won't ever get back to any
867         // other valid state...
868         if (state == eStateDetached || state == eStateExited)
869             return state;
870 
871         state = WaitForStateChangedEvents (timeout, event_sp);
872 
873         for (i=0; i<num_match_states; ++i)
874         {
875             if (match_states[i] == state)
876                 return state;
877         }
878     }
879     return state;
880 }
881 
882 bool
883 Process::HijackProcessEvents (Listener *listener)
884 {
885     if (listener != NULL)
886     {
887         return HijackBroadcaster(listener, eBroadcastBitStateChanged);
888     }
889     else
890         return false;
891 }
892 
893 void
894 Process::RestoreProcessEvents ()
895 {
896     RestoreBroadcaster();
897 }
898 
899 bool
900 Process::HijackPrivateProcessEvents (Listener *listener)
901 {
902     if (listener != NULL)
903     {
904         return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
905     }
906     else
907         return false;
908 }
909 
910 void
911 Process::RestorePrivateProcessEvents ()
912 {
913     m_private_state_broadcaster.RestoreBroadcaster();
914 }
915 
916 StateType
917 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
918 {
919     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
920 
921     if (log)
922         log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
923 
924     StateType state = eStateInvalid;
925     if (m_listener.WaitForEventForBroadcasterWithType (timeout,
926                                                        this,
927                                                        eBroadcastBitStateChanged,
928                                                        event_sp))
929         state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
930 
931     if (log)
932         log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
933                      __FUNCTION__,
934                      timeout,
935                      StateAsCString(state));
936     return state;
937 }
938 
939 Event *
940 Process::PeekAtStateChangedEvents ()
941 {
942     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
943 
944     if (log)
945         log->Printf ("Process::%s...", __FUNCTION__);
946 
947     Event *event_ptr;
948     event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
949                                                                   eBroadcastBitStateChanged);
950     if (log)
951     {
952         if (event_ptr)
953         {
954             log->Printf ("Process::%s (event_ptr) => %s",
955                          __FUNCTION__,
956                          StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
957         }
958         else
959         {
960             log->Printf ("Process::%s no events found",
961                          __FUNCTION__);
962         }
963     }
964     return event_ptr;
965 }
966 
967 StateType
968 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
969 {
970     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
971 
972     if (log)
973         log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
974 
975     StateType state = eStateInvalid;
976     if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
977                                                                      &m_private_state_broadcaster,
978                                                                      eBroadcastBitStateChanged,
979                                                                      event_sp))
980         state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
981 
982     // This is a bit of a hack, but when we wait here we could very well return
983     // to the command-line, and that could disable the log, which would render the
984     // log we got above invalid.
985     if (log)
986     {
987         if (state == eStateInvalid)
988             log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
989         else
990             log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
991     }
992     return state;
993 }
994 
995 bool
996 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
997 {
998     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
999 
1000     if (log)
1001         log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1002 
1003     if (control_only)
1004         return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1005     else
1006         return m_private_state_listener.WaitForEvent(timeout, event_sp);
1007 }
1008 
1009 bool
1010 Process::IsRunning () const
1011 {
1012     return StateIsRunningState (m_public_state.GetValue());
1013 }
1014 
1015 int
1016 Process::GetExitStatus ()
1017 {
1018     if (m_public_state.GetValue() == eStateExited)
1019         return m_exit_status;
1020     return -1;
1021 }
1022 
1023 
1024 void
1025 Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
1026 {
1027     if (m_inherit_host_env && !m_got_host_env)
1028     {
1029         m_got_host_env = true;
1030         StringList host_env;
1031         const size_t host_env_count = Host::GetEnvironment (host_env);
1032         for (size_t idx=0; idx<host_env_count; idx++)
1033         {
1034             const char *env_entry = host_env.GetStringAtIndex (idx);
1035             if (env_entry)
1036             {
1037                 const char *equal_pos = ::strchr(env_entry, '=');
1038                 if (equal_pos)
1039                 {
1040                     std::string key (env_entry, equal_pos - env_entry);
1041                     std::string value (equal_pos + 1);
1042                     if (m_env_vars.find (key) == m_env_vars.end())
1043                         m_env_vars[key] = value;
1044                 }
1045             }
1046         }
1047     }
1048 }
1049 
1050 
1051 size_t
1052 Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
1053 {
1054     GetHostEnvironmentIfNeeded ();
1055 
1056     dictionary::const_iterator pos, end = m_env_vars.end();
1057     for (pos = m_env_vars.begin(); pos != end; ++pos)
1058     {
1059         std::string env_var_equal_value (pos->first);
1060         env_var_equal_value.append(1, '=');
1061         env_var_equal_value.append (pos->second);
1062         env.AppendArgument (env_var_equal_value.c_str());
1063     }
1064     return env.GetArgumentCount();
1065 }
1066 
1067 
1068 const char *
1069 Process::GetExitDescription ()
1070 {
1071     if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1072         return m_exit_string.c_str();
1073     return NULL;
1074 }
1075 
1076 bool
1077 Process::SetExitStatus (int status, const char *cstr)
1078 {
1079     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1080     if (log)
1081         log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1082                     status, status,
1083                     cstr ? "\"" : "",
1084                     cstr ? cstr : "NULL",
1085                     cstr ? "\"" : "");
1086 
1087     // We were already in the exited state
1088     if (m_private_state.GetValue() == eStateExited)
1089     {
1090         if (log)
1091             log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
1092         return false;
1093     }
1094 
1095     m_exit_status = status;
1096     if (cstr)
1097         m_exit_string = cstr;
1098     else
1099         m_exit_string.clear();
1100 
1101     DidExit ();
1102 
1103     SetPrivateState (eStateExited);
1104     return true;
1105 }
1106 
1107 // This static callback can be used to watch for local child processes on
1108 // the current host. The the child process exits, the process will be
1109 // found in the global target list (we want to be completely sure that the
1110 // lldb_private::Process doesn't go away before we can deliver the signal.
1111 bool
1112 Process::SetProcessExitStatus
1113 (
1114     void *callback_baton,
1115     lldb::pid_t pid,
1116     int signo,      // Zero for no signal
1117     int exit_status      // Exit value of process if signal is zero
1118 )
1119 {
1120     if (signo == 0 || exit_status)
1121     {
1122         TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
1123         if (target_sp)
1124         {
1125             ProcessSP process_sp (target_sp->GetProcessSP());
1126             if (process_sp)
1127             {
1128                 const char *signal_cstr = NULL;
1129                 if (signo)
1130                     signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1131 
1132                 process_sp->SetExitStatus (exit_status, signal_cstr);
1133             }
1134         }
1135         return true;
1136     }
1137     return false;
1138 }
1139 
1140 
1141 uint32_t
1142 Process::GetNextThreadIndexID ()
1143 {
1144     return ++m_thread_index_id;
1145 }
1146 
1147 StateType
1148 Process::GetState()
1149 {
1150     // If any other threads access this we will need a mutex for it
1151     return m_public_state.GetValue ();
1152 }
1153 
1154 void
1155 Process::SetPublicState (StateType new_state)
1156 {
1157     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1158     if (log)
1159         log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1160     m_public_state.SetValue (new_state);
1161 }
1162 
1163 StateType
1164 Process::GetPrivateState ()
1165 {
1166     return m_private_state.GetValue();
1167 }
1168 
1169 void
1170 Process::SetPrivateState (StateType new_state)
1171 {
1172     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1173     bool state_changed = false;
1174 
1175     if (log)
1176         log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1177 
1178     Mutex::Locker locker(m_private_state.GetMutex());
1179 
1180     const StateType old_state = m_private_state.GetValueNoLock ();
1181     state_changed = old_state != new_state;
1182     if (state_changed)
1183     {
1184         m_private_state.SetValueNoLock (new_state);
1185         if (StateIsStoppedState(new_state))
1186         {
1187             m_stop_id++;
1188             m_memory_cache.Clear();
1189             if (log)
1190                 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
1191         }
1192         // Use our target to get a shared pointer to ourselves...
1193         m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1194     }
1195     else
1196     {
1197         if (log)
1198             log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
1199     }
1200 }
1201 
1202 
1203 uint32_t
1204 Process::GetStopID() const
1205 {
1206     return m_stop_id;
1207 }
1208 
1209 addr_t
1210 Process::GetImageInfoAddress()
1211 {
1212     return LLDB_INVALID_ADDRESS;
1213 }
1214 
1215 //----------------------------------------------------------------------
1216 // LoadImage
1217 //
1218 // This function provides a default implementation that works for most
1219 // unix variants. Any Process subclasses that need to do shared library
1220 // loading differently should override LoadImage and UnloadImage and
1221 // do what is needed.
1222 //----------------------------------------------------------------------
1223 uint32_t
1224 Process::LoadImage (const FileSpec &image_spec, Error &error)
1225 {
1226     DynamicLoader *loader = GetDynamicLoader();
1227     if (loader)
1228     {
1229         error = loader->CanLoadImage();
1230         if (error.Fail())
1231             return LLDB_INVALID_IMAGE_TOKEN;
1232     }
1233 
1234     if (error.Success())
1235     {
1236         ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1237         if (thread_sp == NULL)
1238             thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
1239 
1240         if (thread_sp)
1241         {
1242             StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1243 
1244             if (frame_sp)
1245             {
1246                 ExecutionContext exe_ctx;
1247                 frame_sp->CalculateExecutionContext (exe_ctx);
1248                 bool unwind_on_error = true;
1249                 bool keep_in_memory = false;
1250                 StreamString expr;
1251                 char path[PATH_MAX];
1252                 image_spec.GetPath(path, sizeof(path));
1253                 expr.Printf("dlopen (\"%s\", 2)", path);
1254                 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
1255                 lldb::ValueObjectSP result_valobj_sp;
1256                 ClangUserExpression::Evaluate (exe_ctx, keep_in_memory, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
1257                 if (result_valobj_sp->GetError().Success())
1258                 {
1259                     Scalar scalar;
1260                     if (result_valobj_sp->ResolveValue (scalar))
1261                     {
1262                         addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1263                         if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1264                         {
1265                             uint32_t image_token = m_image_tokens.size();
1266                             m_image_tokens.push_back (image_ptr);
1267                             return image_token;
1268                         }
1269                     }
1270                 }
1271             }
1272         }
1273     }
1274     return LLDB_INVALID_IMAGE_TOKEN;
1275 }
1276 
1277 //----------------------------------------------------------------------
1278 // UnloadImage
1279 //
1280 // This function provides a default implementation that works for most
1281 // unix variants. Any Process subclasses that need to do shared library
1282 // loading differently should override LoadImage and UnloadImage and
1283 // do what is needed.
1284 //----------------------------------------------------------------------
1285 Error
1286 Process::UnloadImage (uint32_t image_token)
1287 {
1288     Error error;
1289     if (image_token < m_image_tokens.size())
1290     {
1291         const addr_t image_addr = m_image_tokens[image_token];
1292         if (image_addr == LLDB_INVALID_ADDRESS)
1293         {
1294             error.SetErrorString("image already unloaded");
1295         }
1296         else
1297         {
1298             DynamicLoader *loader = GetDynamicLoader();
1299             if (loader)
1300                 error = loader->CanLoadImage();
1301 
1302             if (error.Success())
1303             {
1304                 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1305                 if (thread_sp == NULL)
1306                     thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
1307 
1308                 if (thread_sp)
1309                 {
1310                     StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1311 
1312                     if (frame_sp)
1313                     {
1314                         ExecutionContext exe_ctx;
1315                         frame_sp->CalculateExecutionContext (exe_ctx);
1316                         bool unwind_on_error = true;
1317                         bool keep_in_memory = false;
1318                         StreamString expr;
1319                         expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1320                         const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
1321                         lldb::ValueObjectSP result_valobj_sp;
1322                         ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, keep_in_memory, expr.GetData(), prefix, result_valobj_sp);
1323                         if (result_valobj_sp->GetError().Success())
1324                         {
1325                             Scalar scalar;
1326                             if (result_valobj_sp->ResolveValue (scalar))
1327                             {
1328                                 if (scalar.UInt(1))
1329                                 {
1330                                     error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1331                                 }
1332                                 else
1333                                 {
1334                                     m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1335                                 }
1336                             }
1337                         }
1338                         else
1339                         {
1340                             error = result_valobj_sp->GetError();
1341                         }
1342                     }
1343                 }
1344             }
1345         }
1346     }
1347     else
1348     {
1349         error.SetErrorString("invalid image token");
1350     }
1351     return error;
1352 }
1353 
1354 const ABI *
1355 Process::GetABI()
1356 {
1357     if (m_abi_sp.get() == NULL)
1358         m_abi_sp.reset(ABI::FindPlugin(m_target.GetArchitecture()));
1359 
1360     return m_abi_sp.get();
1361 }
1362 
1363 LanguageRuntime *
1364 Process::GetLanguageRuntime(lldb::LanguageType language)
1365 {
1366     LanguageRuntimeCollection::iterator pos;
1367     pos = m_language_runtimes.find (language);
1368     if (pos == m_language_runtimes.end())
1369     {
1370         lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1371 
1372         m_language_runtimes[language]
1373             = runtime;
1374         return runtime.get();
1375     }
1376     else
1377         return (*pos).second.get();
1378 }
1379 
1380 CPPLanguageRuntime *
1381 Process::GetCPPLanguageRuntime ()
1382 {
1383     LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1384     if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1385         return static_cast<CPPLanguageRuntime *> (runtime);
1386     return NULL;
1387 }
1388 
1389 ObjCLanguageRuntime *
1390 Process::GetObjCLanguageRuntime ()
1391 {
1392     LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1393     if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1394         return static_cast<ObjCLanguageRuntime *> (runtime);
1395     return NULL;
1396 }
1397 
1398 BreakpointSiteList &
1399 Process::GetBreakpointSiteList()
1400 {
1401     return m_breakpoint_site_list;
1402 }
1403 
1404 const BreakpointSiteList &
1405 Process::GetBreakpointSiteList() const
1406 {
1407     return m_breakpoint_site_list;
1408 }
1409 
1410 
1411 void
1412 Process::DisableAllBreakpointSites ()
1413 {
1414     m_breakpoint_site_list.SetEnabledForAll (false);
1415 }
1416 
1417 Error
1418 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1419 {
1420     Error error (DisableBreakpointSiteByID (break_id));
1421 
1422     if (error.Success())
1423         m_breakpoint_site_list.Remove(break_id);
1424 
1425     return error;
1426 }
1427 
1428 Error
1429 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1430 {
1431     Error error;
1432     BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1433     if (bp_site_sp)
1434     {
1435         if (bp_site_sp->IsEnabled())
1436             error = DisableBreakpoint (bp_site_sp.get());
1437     }
1438     else
1439     {
1440         error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1441     }
1442 
1443     return error;
1444 }
1445 
1446 Error
1447 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1448 {
1449     Error error;
1450     BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1451     if (bp_site_sp)
1452     {
1453         if (!bp_site_sp->IsEnabled())
1454             error = EnableBreakpoint (bp_site_sp.get());
1455     }
1456     else
1457     {
1458         error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1459     }
1460     return error;
1461 }
1462 
1463 lldb::break_id_t
1464 Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1465 {
1466     const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
1467     if (load_addr != LLDB_INVALID_ADDRESS)
1468     {
1469         BreakpointSiteSP bp_site_sp;
1470 
1471         // Look up this breakpoint site.  If it exists, then add this new owner, otherwise
1472         // create a new breakpoint site and add it.
1473 
1474         bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1475 
1476         if (bp_site_sp)
1477         {
1478             bp_site_sp->AddOwner (owner);
1479             owner->SetBreakpointSite (bp_site_sp);
1480             return bp_site_sp->GetID();
1481         }
1482         else
1483         {
1484             bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1485             if (bp_site_sp)
1486             {
1487                 if (EnableBreakpoint (bp_site_sp.get()).Success())
1488                 {
1489                     owner->SetBreakpointSite (bp_site_sp);
1490                     return m_breakpoint_site_list.Add (bp_site_sp);
1491                 }
1492             }
1493         }
1494     }
1495     // We failed to enable the breakpoint
1496     return LLDB_INVALID_BREAK_ID;
1497 
1498 }
1499 
1500 void
1501 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1502 {
1503     uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1504     if (num_owners == 0)
1505     {
1506         DisableBreakpoint(bp_site_sp.get());
1507         m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1508     }
1509 }
1510 
1511 
1512 size_t
1513 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1514 {
1515     size_t bytes_removed = 0;
1516     addr_t intersect_addr;
1517     size_t intersect_size;
1518     size_t opcode_offset;
1519     size_t idx;
1520     BreakpointSiteSP bp;
1521 
1522     for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1523     {
1524         if (bp->GetType() == BreakpointSite::eSoftware)
1525         {
1526             if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1527             {
1528                 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1529                 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1530                 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1531                 size_t buf_offset = intersect_addr - bp_addr;
1532                 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1533             }
1534         }
1535     }
1536     return bytes_removed;
1537 }
1538 
1539 
1540 
1541 size_t
1542 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1543 {
1544     PlatformSP platform_sp (m_target.GetPlatform());
1545     if (platform_sp)
1546         return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1547     return 0;
1548 }
1549 
1550 Error
1551 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1552 {
1553     Error error;
1554     assert (bp_site != NULL);
1555     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
1556     const addr_t bp_addr = bp_site->GetLoadAddress();
1557     if (log)
1558         log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1559     if (bp_site->IsEnabled())
1560     {
1561         if (log)
1562             log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1563         return error;
1564     }
1565 
1566     if (bp_addr == LLDB_INVALID_ADDRESS)
1567     {
1568         error.SetErrorString("BreakpointSite contains an invalid load address.");
1569         return error;
1570     }
1571     // Ask the lldb::Process subclass to fill in the correct software breakpoint
1572     // trap for the breakpoint site
1573     const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1574 
1575     if (bp_opcode_size == 0)
1576     {
1577         error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1578     }
1579     else
1580     {
1581         const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1582 
1583         if (bp_opcode_bytes == NULL)
1584         {
1585             error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1586             return error;
1587         }
1588 
1589         // Save the original opcode by reading it
1590         if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1591         {
1592             // Write a software breakpoint in place of the original opcode
1593             if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1594             {
1595                 uint8_t verify_bp_opcode_bytes[64];
1596                 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1597                 {
1598                     if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1599                     {
1600                         bp_site->SetEnabled(true);
1601                         bp_site->SetType (BreakpointSite::eSoftware);
1602                         if (log)
1603                             log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1604                                          bp_site->GetID(),
1605                                          (uint64_t)bp_addr);
1606                     }
1607                     else
1608                         error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1609                 }
1610                 else
1611                     error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1612             }
1613             else
1614                 error.SetErrorString("Unable to write breakpoint trap to memory.");
1615         }
1616         else
1617             error.SetErrorString("Unable to read memory at breakpoint address.");
1618     }
1619     if (log && error.Fail())
1620         log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1621                      bp_site->GetID(),
1622                      (uint64_t)bp_addr,
1623                      error.AsCString());
1624     return error;
1625 }
1626 
1627 Error
1628 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1629 {
1630     Error error;
1631     assert (bp_site != NULL);
1632     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
1633     addr_t bp_addr = bp_site->GetLoadAddress();
1634     lldb::user_id_t breakID = bp_site->GetID();
1635     if (log)
1636         log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
1637 
1638     if (bp_site->IsHardware())
1639     {
1640         error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1641     }
1642     else if (bp_site->IsEnabled())
1643     {
1644         const size_t break_op_size = bp_site->GetByteSize();
1645         const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1646         if (break_op_size > 0)
1647         {
1648             // Clear a software breakoint instruction
1649             uint8_t curr_break_op[8];
1650             assert (break_op_size <= sizeof(curr_break_op));
1651             bool break_op_found = false;
1652 
1653             // Read the breakpoint opcode
1654             if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1655             {
1656                 bool verify = false;
1657                 // Make sure we have the a breakpoint opcode exists at this address
1658                 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1659                 {
1660                     break_op_found = true;
1661                     // We found a valid breakpoint opcode at this address, now restore
1662                     // the saved opcode.
1663                     if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1664                     {
1665                         verify = true;
1666                     }
1667                     else
1668                         error.SetErrorString("Memory write failed when restoring original opcode.");
1669                 }
1670                 else
1671                 {
1672                     error.SetErrorString("Original breakpoint trap is no longer in memory.");
1673                     // Set verify to true and so we can check if the original opcode has already been restored
1674                     verify = true;
1675                 }
1676 
1677                 if (verify)
1678                 {
1679                     uint8_t verify_opcode[8];
1680                     assert (break_op_size < sizeof(verify_opcode));
1681                     // Verify that our original opcode made it back to the inferior
1682                     if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1683                     {
1684                         // compare the memory we just read with the original opcode
1685                         if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1686                         {
1687                             // SUCCESS
1688                             bp_site->SetEnabled(false);
1689                             if (log)
1690                                 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1691                             return error;
1692                         }
1693                         else
1694                         {
1695                             if (break_op_found)
1696                                 error.SetErrorString("Failed to restore original opcode.");
1697                         }
1698                     }
1699                     else
1700                         error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1701                 }
1702             }
1703             else
1704                 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1705         }
1706     }
1707     else
1708     {
1709         if (log)
1710             log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1711         return error;
1712     }
1713 
1714     if (log)
1715         log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1716                      bp_site->GetID(),
1717                      (uint64_t)bp_addr,
1718                      error.AsCString());
1719     return error;
1720 
1721 }
1722 
1723 // Comment out line below to disable memory caching
1724 #define ENABLE_MEMORY_CACHING
1725 // Uncomment to verify memory caching works after making changes to caching code
1726 //#define VERIFY_MEMORY_READS
1727 
1728 #if defined (ENABLE_MEMORY_CACHING)
1729 
1730 #if defined (VERIFY_MEMORY_READS)
1731 
1732 size_t
1733 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1734 {
1735     // Memory caching is enabled, with debug verification
1736     if (buf && size)
1737     {
1738         // Uncomment the line below to make sure memory caching is working.
1739         // I ran this through the test suite and got no assertions, so I am
1740         // pretty confident this is working well. If any changes are made to
1741         // memory caching, uncomment the line below and test your changes!
1742 
1743         // Verify all memory reads by using the cache first, then redundantly
1744         // reading the same memory from the inferior and comparing to make sure
1745         // everything is exactly the same.
1746         std::string verify_buf (size, '\0');
1747         assert (verify_buf.size() == size);
1748         const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1749         Error verify_error;
1750         const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1751         assert (cache_bytes_read == verify_bytes_read);
1752         assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1753         assert (verify_error.Success() == error.Success());
1754         return cache_bytes_read;
1755     }
1756     return 0;
1757 }
1758 
1759 #else   // #if defined (VERIFY_MEMORY_READS)
1760 
1761 size_t
1762 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1763 {
1764     // Memory caching enabled, no verification
1765     return m_memory_cache.Read (this, addr, buf, size, error);
1766 }
1767 
1768 #endif  // #else for #if defined (VERIFY_MEMORY_READS)
1769 
1770 #else   // #if defined (ENABLE_MEMORY_CACHING)
1771 
1772 size_t
1773 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1774 {
1775     // Memory caching is disabled
1776     return ReadMemoryFromInferior (addr, buf, size, error);
1777 }
1778 
1779 #endif  // #else for #if defined (ENABLE_MEMORY_CACHING)
1780 
1781 
1782 size_t
1783 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1784 {
1785     size_t total_cstr_len = 0;
1786     if (dst && dst_max_len)
1787     {
1788         // NULL out everything just to be safe
1789         memset (dst, 0, dst_max_len);
1790         Error error;
1791         addr_t curr_addr = addr;
1792         const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1793         size_t bytes_left = dst_max_len - 1;
1794         char *curr_dst = dst;
1795 
1796         while (bytes_left > 0)
1797         {
1798             addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1799             addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1800             size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1801 
1802             if (bytes_read == 0)
1803             {
1804                 dst[total_cstr_len] = '\0';
1805                 break;
1806             }
1807             const size_t len = strlen(curr_dst);
1808 
1809             total_cstr_len += len;
1810 
1811             if (len < bytes_to_read)
1812                 break;
1813 
1814             curr_dst += bytes_read;
1815             curr_addr += bytes_read;
1816             bytes_left -= bytes_read;
1817         }
1818     }
1819     return total_cstr_len;
1820 }
1821 
1822 size_t
1823 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1824 {
1825     if (buf == NULL || size == 0)
1826         return 0;
1827 
1828     size_t bytes_read = 0;
1829     uint8_t *bytes = (uint8_t *)buf;
1830 
1831     while (bytes_read < size)
1832     {
1833         const size_t curr_size = size - bytes_read;
1834         const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1835                                                      bytes + bytes_read,
1836                                                      curr_size,
1837                                                      error);
1838         bytes_read += curr_bytes_read;
1839         if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1840             break;
1841     }
1842 
1843     // Replace any software breakpoint opcodes that fall into this range back
1844     // into "buf" before we return
1845     if (bytes_read > 0)
1846         RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1847     return bytes_read;
1848 }
1849 
1850 uint64_t
1851 Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1852 {
1853     if (integer_byte_size > sizeof(uint64_t))
1854     {
1855         error.SetErrorString ("unsupported integer size");
1856     }
1857     else
1858     {
1859         uint8_t tmp[sizeof(uint64_t)];
1860         DataExtractor data (tmp,
1861                             integer_byte_size,
1862                             m_target.GetArchitecture().GetByteOrder(),
1863                             m_target.GetArchitecture().GetAddressByteSize());
1864         if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1865         {
1866             uint32_t offset = 0;
1867             return data.GetMaxU64 (&offset, integer_byte_size);
1868         }
1869     }
1870     // Any plug-in that doesn't return success a memory read with the number
1871     // of bytes that were requested should be setting the error
1872     assert (error.Fail());
1873     return 0;
1874 }
1875 
1876 size_t
1877 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1878 {
1879     size_t bytes_written = 0;
1880     const uint8_t *bytes = (const uint8_t *)buf;
1881 
1882     while (bytes_written < size)
1883     {
1884         const size_t curr_size = size - bytes_written;
1885         const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1886                                                          bytes + bytes_written,
1887                                                          curr_size,
1888                                                          error);
1889         bytes_written += curr_bytes_written;
1890         if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1891             break;
1892     }
1893     return bytes_written;
1894 }
1895 
1896 size_t
1897 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1898 {
1899 #if defined (ENABLE_MEMORY_CACHING)
1900     m_memory_cache.Flush (addr, size);
1901 #endif
1902 
1903     if (buf == NULL || size == 0)
1904         return 0;
1905     // We need to write any data that would go where any current software traps
1906     // (enabled software breakpoints) any software traps (breakpoints) that we
1907     // may have placed in our tasks memory.
1908 
1909     BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1910     BreakpointSiteList::collection::const_iterator end =  m_breakpoint_site_list.GetMap()->end();
1911 
1912     if (iter == end || iter->second->GetLoadAddress() > addr + size)
1913         return DoWriteMemory(addr, buf, size, error);
1914 
1915     BreakpointSiteList::collection::const_iterator pos;
1916     size_t bytes_written = 0;
1917     addr_t intersect_addr = 0;
1918     size_t intersect_size = 0;
1919     size_t opcode_offset = 0;
1920     const uint8_t *ubuf = (const uint8_t *)buf;
1921 
1922     for (pos = iter; pos != end; ++pos)
1923     {
1924         BreakpointSiteSP bp;
1925         bp = pos->second;
1926 
1927         assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1928         assert(addr <= intersect_addr && intersect_addr < addr + size);
1929         assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1930         assert(opcode_offset + intersect_size <= bp->GetByteSize());
1931 
1932         // Check for bytes before this breakpoint
1933         const addr_t curr_addr = addr + bytes_written;
1934         if (intersect_addr > curr_addr)
1935         {
1936             // There are some bytes before this breakpoint that we need to
1937             // just write to memory
1938             size_t curr_size = intersect_addr - curr_addr;
1939             size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1940                                                             ubuf + bytes_written,
1941                                                             curr_size,
1942                                                             error);
1943             bytes_written += curr_bytes_written;
1944             if (curr_bytes_written != curr_size)
1945             {
1946                 // We weren't able to write all of the requested bytes, we
1947                 // are done looping and will return the number of bytes that
1948                 // we have written so far.
1949                 break;
1950             }
1951         }
1952 
1953         // Now write any bytes that would cover up any software breakpoints
1954         // directly into the breakpoint opcode buffer
1955         ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1956         bytes_written += intersect_size;
1957     }
1958 
1959     // Write any remaining bytes after the last breakpoint if we have any left
1960     if (bytes_written < size)
1961         bytes_written += WriteMemoryPrivate (addr + bytes_written,
1962                                              ubuf + bytes_written,
1963                                              size - bytes_written,
1964                                              error);
1965 
1966     return bytes_written;
1967 }
1968 
1969 addr_t
1970 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1971 {
1972     // Fixme: we should track the blocks we've allocated, and clean them up...
1973     // We could even do our own allocator here if that ends up being more efficient.
1974     addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1975     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1976     if (log)
1977         log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
1978                     size,
1979                     permissions & ePermissionsReadable ? 'r' : '-',
1980                     permissions & ePermissionsWritable ? 'w' : '-',
1981                     permissions & ePermissionsExecutable ? 'x' : '-',
1982                     (uint64_t)allocated_addr,
1983                     m_stop_id);
1984     return allocated_addr;
1985 }
1986 
1987 Error
1988 Process::DeallocateMemory (addr_t ptr)
1989 {
1990     Error error(DoDeallocateMemory (ptr));
1991 
1992     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1993     if (log)
1994         log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1995                     ptr,
1996                     error.AsCString("SUCCESS"),
1997                     m_stop_id);
1998     return error;
1999 }
2000 
2001 
2002 Error
2003 Process::EnableWatchpoint (WatchpointLocation *watchpoint)
2004 {
2005     Error error;
2006     error.SetErrorString("watchpoints are not supported");
2007     return error;
2008 }
2009 
2010 Error
2011 Process::DisableWatchpoint (WatchpointLocation *watchpoint)
2012 {
2013     Error error;
2014     error.SetErrorString("watchpoints are not supported");
2015     return error;
2016 }
2017 
2018 StateType
2019 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2020 {
2021     StateType state;
2022     // Now wait for the process to launch and return control to us, and then
2023     // call DidLaunch:
2024     while (1)
2025     {
2026         event_sp.reset();
2027         state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2028 
2029         if (StateIsStoppedState(state))
2030             break;
2031 
2032         // If state is invalid, then we timed out
2033         if (state == eStateInvalid)
2034             break;
2035 
2036         if (event_sp)
2037             HandlePrivateEvent (event_sp);
2038     }
2039     return state;
2040 }
2041 
2042 Error
2043 Process::Launch
2044 (
2045     char const *argv[],
2046     char const *envp[],
2047     uint32_t launch_flags,
2048     const char *stdin_path,
2049     const char *stdout_path,
2050     const char *stderr_path,
2051     const char *working_directory
2052 )
2053 {
2054     Error error;
2055     m_abi_sp.reset();
2056     m_dyld_ap.reset();
2057     m_process_input_reader.reset();
2058 
2059     Module *exe_module = m_target.GetExecutableModule().get();
2060     if (exe_module)
2061     {
2062         char exec_file_path[PATH_MAX];
2063         exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path));
2064         if (exe_module->GetFileSpec().Exists())
2065         {
2066             if (PrivateStateThreadIsValid ())
2067                 PausePrivateStateThread ();
2068 
2069             error = WillLaunch (exe_module);
2070             if (error.Success())
2071             {
2072                 SetPublicState (eStateLaunching);
2073                 // The args coming in should not contain the application name, the
2074                 // lldb_private::Process class will add this in case the executable
2075                 // gets resolved to a different file than was given on the command
2076                 // line (like when an applicaiton bundle is specified and will
2077                 // resolve to the contained exectuable file, or the file given was
2078                 // a symlink or other file system link that resolves to a different
2079                 // file).
2080 
2081                 // Get the resolved exectuable path
2082 
2083                 // Make a new argument vector
2084                 std::vector<const char *> exec_path_plus_argv;
2085                 // Append the resolved executable path
2086                 exec_path_plus_argv.push_back (exec_file_path);
2087 
2088                 // Push all args if there are any
2089                 if (argv)
2090                 {
2091                     for (int i = 0; argv[i]; ++i)
2092                         exec_path_plus_argv.push_back(argv[i]);
2093                 }
2094 
2095                 // Push a NULL to terminate the args.
2096                 exec_path_plus_argv.push_back(NULL);
2097 
2098                 // Now launch using these arguments.
2099                 error = DoLaunch (exe_module,
2100                                   exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
2101                                   envp,
2102                                   launch_flags,
2103                                   stdin_path,
2104                                   stdout_path,
2105                                   stderr_path,
2106                                   working_directory);
2107 
2108                 if (error.Fail())
2109                 {
2110                     if (GetID() != LLDB_INVALID_PROCESS_ID)
2111                     {
2112                         SetID (LLDB_INVALID_PROCESS_ID);
2113                         const char *error_string = error.AsCString();
2114                         if (error_string == NULL)
2115                             error_string = "launch failed";
2116                         SetExitStatus (-1, error_string);
2117                     }
2118                 }
2119                 else
2120                 {
2121                     EventSP event_sp;
2122                     StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2123 
2124                     if (state == eStateStopped || state == eStateCrashed)
2125                     {
2126 
2127                         DidLaunch ();
2128 
2129                         m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2130                         if (m_dyld_ap.get())
2131                             m_dyld_ap->DidLaunch();
2132 
2133                         // This delays passing the stopped event to listeners till DidLaunch gets
2134                         // a chance to complete...
2135                         HandlePrivateEvent (event_sp);
2136 
2137                         if (PrivateStateThreadIsValid ())
2138                             ResumePrivateStateThread ();
2139                         else
2140                             StartPrivateStateThread ();
2141                     }
2142                     else if (state == eStateExited)
2143                     {
2144                         // We exited while trying to launch somehow.  Don't call DidLaunch as that's
2145                         // not likely to work, and return an invalid pid.
2146                         HandlePrivateEvent (event_sp);
2147                     }
2148                 }
2149             }
2150         }
2151         else
2152         {
2153             error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", exec_file_path);
2154         }
2155     }
2156     return error;
2157 }
2158 
2159 Process::NextEventAction::EventActionResult
2160 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
2161 {
2162     StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2163     switch (state)
2164     {
2165         case eStateRunning:
2166         case eStateConnected:
2167             return eEventActionRetry;
2168 
2169         case eStateStopped:
2170         case eStateCrashed:
2171         {
2172             // During attach, prior to sending the eStateStopped event,
2173             // lldb_private::Process subclasses must set the process must set
2174             // the new process ID.
2175             assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2176             m_process->CompleteAttach ();
2177             return eEventActionSuccess;
2178         }
2179 
2180 
2181             break;
2182         default:
2183         case eStateExited:
2184         case eStateInvalid:
2185             m_exit_string.assign ("No valid Process");
2186             return eEventActionExit;
2187             break;
2188     }
2189 }
2190 
2191 Process::NextEventAction::EventActionResult
2192 Process::AttachCompletionHandler::HandleBeingInterrupted()
2193 {
2194     return eEventActionSuccess;
2195 }
2196 
2197 const char *
2198 Process::AttachCompletionHandler::GetExitString ()
2199 {
2200     return m_exit_string.c_str();
2201 }
2202 
2203 Error
2204 Process::Attach (lldb::pid_t attach_pid)
2205 {
2206 
2207     m_abi_sp.reset();
2208     m_process_input_reader.reset();
2209 
2210     // Find the process and its architecture.  Make sure it matches the architecture
2211     // of the current Target, and if not adjust it.
2212 
2213     ProcessInstanceInfo process_info;
2214     PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
2215     if (platform_sp)
2216     {
2217         if (platform_sp->GetProcessInfo (attach_pid, process_info))
2218         {
2219             const ArchSpec &process_arch = process_info.GetArchitecture();
2220             if (process_arch.IsValid())
2221                 GetTarget().SetArchitecture(process_arch);
2222         }
2223     }
2224 
2225     m_dyld_ap.reset();
2226 
2227     Error error (WillAttachToProcessWithID(attach_pid));
2228     if (error.Success())
2229     {
2230         SetPublicState (eStateAttaching);
2231 
2232         error = DoAttachToProcessWithID (attach_pid);
2233         if (error.Success())
2234         {
2235             SetNextEventAction(new Process::AttachCompletionHandler(this));
2236             StartPrivateStateThread();
2237         }
2238         else
2239         {
2240             if (GetID() != LLDB_INVALID_PROCESS_ID)
2241             {
2242                 SetID (LLDB_INVALID_PROCESS_ID);
2243                 const char *error_string = error.AsCString();
2244                 if (error_string == NULL)
2245                     error_string = "attach failed";
2246 
2247                 SetExitStatus(-1, error_string);
2248             }
2249         }
2250     }
2251     return error;
2252 }
2253 
2254 Error
2255 Process::Attach (const char *process_name, bool wait_for_launch)
2256 {
2257     m_abi_sp.reset();
2258     m_process_input_reader.reset();
2259 
2260     // Find the process and its architecture.  Make sure it matches the architecture
2261     // of the current Target, and if not adjust it.
2262     Error error;
2263 
2264     if (!wait_for_launch)
2265     {
2266         ProcessInstanceInfoList process_infos;
2267         PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
2268         if (platform_sp)
2269         {
2270             ProcessInstanceInfoMatch match_info;
2271             match_info.GetProcessInfo().SetName(process_name);
2272             match_info.SetNameMatchType (eNameMatchEquals);
2273             platform_sp->FindProcesses (match_info, process_infos);
2274             if (process_infos.GetSize() > 1)
2275             {
2276                 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
2277             }
2278             else if (process_infos.GetSize() == 0)
2279             {
2280                 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
2281             }
2282             else
2283             {
2284                 ProcessInstanceInfo process_info;
2285                 if (process_infos.GetInfoAtIndex (0, process_info))
2286                 {
2287                     const ArchSpec &process_arch = process_info.GetArchitecture();
2288                     if (process_arch.IsValid() && process_arch != GetTarget().GetArchitecture())
2289                     {
2290                         // Set the architecture on the target.
2291                         GetTarget().SetArchitecture (process_arch);
2292                     }
2293                 }
2294             }
2295         }
2296         else
2297         {
2298             error.SetErrorString ("Invalid platform");
2299         }
2300     }
2301 
2302     if (error.Success())
2303     {
2304         m_dyld_ap.reset();
2305 
2306         error = WillAttachToProcessWithName(process_name, wait_for_launch);
2307         if (error.Success())
2308         {
2309             SetPublicState (eStateAttaching);
2310             error = DoAttachToProcessWithName (process_name, wait_for_launch);
2311             if (error.Fail())
2312             {
2313                 if (GetID() != LLDB_INVALID_PROCESS_ID)
2314                 {
2315                     SetID (LLDB_INVALID_PROCESS_ID);
2316                     const char *error_string = error.AsCString();
2317                     if (error_string == NULL)
2318                         error_string = "attach failed";
2319 
2320                     SetExitStatus(-1, error_string);
2321                 }
2322             }
2323             else
2324             {
2325                 SetNextEventAction(new Process::AttachCompletionHandler(this));
2326                 StartPrivateStateThread();
2327             }
2328         }
2329     }
2330     return error;
2331 }
2332 
2333 void
2334 Process::CompleteAttach ()
2335 {
2336     // Let the process subclass figure out at much as it can about the process
2337     // before we go looking for a dynamic loader plug-in.
2338     DidAttach();
2339 
2340     // We have complete the attach, now it is time to find the dynamic loader
2341     // plug-in
2342     m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2343     if (m_dyld_ap.get())
2344         m_dyld_ap->DidAttach();
2345 
2346     // Figure out which one is the executable, and set that in our target:
2347     ModuleList &modules = m_target.GetImages();
2348 
2349     size_t num_modules = modules.GetSize();
2350     for (int i = 0; i < num_modules; i++)
2351     {
2352         ModuleSP module_sp (modules.GetModuleAtIndex(i));
2353         if (module_sp && module_sp->IsExecutable())
2354         {
2355             ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
2356             if (target_exe_module_sp != module_sp)
2357                 m_target.SetExecutableModule (module_sp, false);
2358             break;
2359         }
2360     }
2361 }
2362 
2363 Error
2364 Process::ConnectRemote (const char *remote_url)
2365 {
2366     m_abi_sp.reset();
2367     m_process_input_reader.reset();
2368 
2369     // Find the process and its architecture.  Make sure it matches the architecture
2370     // of the current Target, and if not adjust it.
2371 
2372     Error error (DoConnectRemote (remote_url));
2373     if (error.Success())
2374     {
2375         if (GetID() != LLDB_INVALID_PROCESS_ID)
2376         {
2377             EventSP event_sp;
2378             StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2379 
2380             if (state == eStateStopped || state == eStateCrashed)
2381             {
2382                 // If we attached and actually have a process on the other end, then
2383                 // this ended up being the equivalent of an attach.
2384                 CompleteAttach ();
2385 
2386                 // This delays passing the stopped event to listeners till
2387                 // CompleteAttach gets a chance to complete...
2388                 HandlePrivateEvent (event_sp);
2389 
2390             }
2391         }
2392 
2393         if (PrivateStateThreadIsValid ())
2394             ResumePrivateStateThread ();
2395         else
2396             StartPrivateStateThread ();
2397     }
2398     return error;
2399 }
2400 
2401 
2402 Error
2403 Process::Resume ()
2404 {
2405     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2406     if (log)
2407         log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
2408                     m_stop_id,
2409                     StateAsCString(m_public_state.GetValue()),
2410                     StateAsCString(m_private_state.GetValue()));
2411 
2412     Error error (WillResume());
2413     // Tell the process it is about to resume before the thread list
2414     if (error.Success())
2415     {
2416         // Now let the thread list know we are about to resume so it
2417         // can let all of our threads know that they are about to be
2418         // resumed. Threads will each be called with
2419         // Thread::WillResume(StateType) where StateType contains the state
2420         // that they are supposed to have when the process is resumed
2421         // (suspended/running/stepping). Threads should also check
2422         // their resume signal in lldb::Thread::GetResumeSignal()
2423         // to see if they are suppoed to start back up with a signal.
2424         if (m_thread_list.WillResume())
2425         {
2426             error = DoResume();
2427             if (error.Success())
2428             {
2429                 DidResume();
2430                 m_thread_list.DidResume();
2431                 if (log)
2432                     log->Printf ("Process thinks the process has resumed.");
2433             }
2434         }
2435         else
2436         {
2437             error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
2438         }
2439     }
2440     else if (log)
2441         log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
2442     return error;
2443 }
2444 
2445 Error
2446 Process::Halt ()
2447 {
2448     // Pause our private state thread so we can ensure no one else eats
2449     // the stop event out from under us.
2450     Listener halt_listener ("lldb.process.halt_listener");
2451     HijackPrivateProcessEvents(&halt_listener);
2452 
2453     EventSP event_sp;
2454     Error error (WillHalt());
2455 
2456     if (error.Success())
2457     {
2458 
2459         bool caused_stop = false;
2460 
2461         // Ask the process subclass to actually halt our process
2462         error = DoHalt(caused_stop);
2463         if (error.Success())
2464         {
2465             if (m_public_state.GetValue() == eStateAttaching)
2466             {
2467                 SetExitStatus(SIGKILL, "Cancelled async attach.");
2468                 Destroy ();
2469             }
2470             else
2471             {
2472                 // If "caused_stop" is true, then DoHalt stopped the process. If
2473                 // "caused_stop" is false, the process was already stopped.
2474                 // If the DoHalt caused the process to stop, then we want to catch
2475                 // this event and set the interrupted bool to true before we pass
2476                 // this along so clients know that the process was interrupted by
2477                 // a halt command.
2478                 if (caused_stop)
2479                 {
2480                     // Wait for 1 second for the process to stop.
2481                     TimeValue timeout_time;
2482                     timeout_time = TimeValue::Now();
2483                     timeout_time.OffsetWithSeconds(1);
2484                     bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2485                     StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2486 
2487                     if (!got_event || state == eStateInvalid)
2488                     {
2489                         // We timeout out and didn't get a stop event...
2490                         error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
2491                     }
2492                     else
2493                     {
2494                         if (StateIsStoppedState (state))
2495                         {
2496                             // We caused the process to interrupt itself, so mark this
2497                             // as such in the stop event so clients can tell an interrupted
2498                             // process from a natural stop
2499                             ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2500                         }
2501                         else
2502                         {
2503                             LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2504                             if (log)
2505                                 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2506                             error.SetErrorString ("Did not get stopped event after halt.");
2507                         }
2508                     }
2509                 }
2510                 DidHalt();
2511             }
2512         }
2513     }
2514     // Resume our private state thread before we post the event (if any)
2515     RestorePrivateProcessEvents();
2516 
2517     // Post any event we might have consumed. If all goes well, we will have
2518     // stopped the process, intercepted the event and set the interrupted
2519     // bool in the event.  Post it to the private event queue and that will end up
2520     // correctly setting the state.
2521     if (event_sp)
2522         m_private_state_broadcaster.BroadcastEvent(event_sp);
2523 
2524     return error;
2525 }
2526 
2527 Error
2528 Process::Detach ()
2529 {
2530     Error error (WillDetach());
2531 
2532     if (error.Success())
2533     {
2534         DisableAllBreakpointSites();
2535         error = DoDetach();
2536         if (error.Success())
2537         {
2538             DidDetach();
2539             StopPrivateStateThread();
2540         }
2541     }
2542     return error;
2543 }
2544 
2545 Error
2546 Process::Destroy ()
2547 {
2548     Error error (WillDestroy());
2549     if (error.Success())
2550     {
2551         DisableAllBreakpointSites();
2552         error = DoDestroy();
2553         if (error.Success())
2554         {
2555             DidDestroy();
2556             StopPrivateStateThread();
2557         }
2558         m_stdio_communication.StopReadThread();
2559         m_stdio_communication.Disconnect();
2560         if (m_process_input_reader && m_process_input_reader->IsActive())
2561             m_target.GetDebugger().PopInputReader (m_process_input_reader);
2562         if (m_process_input_reader)
2563             m_process_input_reader.reset();
2564     }
2565     return error;
2566 }
2567 
2568 Error
2569 Process::Signal (int signal)
2570 {
2571     Error error (WillSignal());
2572     if (error.Success())
2573     {
2574         error = DoSignal(signal);
2575         if (error.Success())
2576             DidSignal();
2577     }
2578     return error;
2579 }
2580 
2581 lldb::ByteOrder
2582 Process::GetByteOrder () const
2583 {
2584     return m_target.GetArchitecture().GetByteOrder();
2585 }
2586 
2587 uint32_t
2588 Process::GetAddressByteSize () const
2589 {
2590     return m_target.GetArchitecture().GetAddressByteSize();
2591 }
2592 
2593 
2594 bool
2595 Process::ShouldBroadcastEvent (Event *event_ptr)
2596 {
2597     const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2598     bool return_value = true;
2599     LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
2600 
2601     switch (state)
2602     {
2603         case eStateConnected:
2604         case eStateAttaching:
2605         case eStateLaunching:
2606         case eStateDetached:
2607         case eStateExited:
2608         case eStateUnloaded:
2609             // These events indicate changes in the state of the debugging session, always report them.
2610             return_value = true;
2611             break;
2612         case eStateInvalid:
2613             // We stopped for no apparent reason, don't report it.
2614             return_value = false;
2615             break;
2616         case eStateRunning:
2617         case eStateStepping:
2618             // If we've started the target running, we handle the cases where we
2619             // are already running and where there is a transition from stopped to
2620             // running differently.
2621             // running -> running: Automatically suppress extra running events
2622             // stopped -> running: Report except when there is one or more no votes
2623             //     and no yes votes.
2624             SynchronouslyNotifyStateChanged (state);
2625             switch (m_public_state.GetValue())
2626             {
2627                 case eStateRunning:
2628                 case eStateStepping:
2629                     // We always suppress multiple runnings with no PUBLIC stop in between.
2630                     return_value = false;
2631                     break;
2632                 default:
2633                     // TODO: make this work correctly. For now always report
2634                     // run if we aren't running so we don't miss any runnning
2635                     // events. If I run the lldb/test/thread/a.out file and
2636                     // break at main.cpp:58, run and hit the breakpoints on
2637                     // multiple threads, then somehow during the stepping over
2638                     // of all breakpoints no run gets reported.
2639                     return_value = true;
2640 
2641                     // This is a transition from stop to run.
2642                     switch (m_thread_list.ShouldReportRun (event_ptr))
2643                     {
2644                         case eVoteYes:
2645                         case eVoteNoOpinion:
2646                             return_value = true;
2647                             break;
2648                         case eVoteNo:
2649                             return_value = false;
2650                             break;
2651                     }
2652                     break;
2653             }
2654             break;
2655         case eStateStopped:
2656         case eStateCrashed:
2657         case eStateSuspended:
2658         {
2659             // We've stopped.  First see if we're going to restart the target.
2660             // If we are going to stop, then we always broadcast the event.
2661             // If we aren't going to stop, let the thread plans decide if we're going to report this event.
2662             // If no thread has an opinion, we don't report it.
2663             if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
2664             {
2665                 if (log)
2666                     log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
2667                 return true;
2668             }
2669             else
2670             {
2671                 RefreshStateAfterStop ();
2672 
2673                 if (m_thread_list.ShouldStop (event_ptr) == false)
2674                 {
2675                     switch (m_thread_list.ShouldReportStop (event_ptr))
2676                     {
2677                         case eVoteYes:
2678                             Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
2679                             // Intentional fall-through here.
2680                         case eVoteNoOpinion:
2681                         case eVoteNo:
2682                             return_value = false;
2683                             break;
2684                     }
2685 
2686                     if (log)
2687                         log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
2688                     Resume ();
2689                 }
2690                 else
2691                 {
2692                     return_value = true;
2693                     SynchronouslyNotifyStateChanged (state);
2694                 }
2695             }
2696         }
2697     }
2698 
2699     if (log)
2700         log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2701     return return_value;
2702 }
2703 
2704 
2705 bool
2706 Process::StartPrivateStateThread ()
2707 {
2708     LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
2709 
2710     bool already_running = PrivateStateThreadIsValid ();
2711     if (log)
2712         log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2713 
2714     if (already_running)
2715         return true;
2716 
2717     // Create a thread that watches our internal state and controls which
2718     // events make it to clients (into the DCProcess event queue).
2719     char thread_name[1024];
2720     snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2721     m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
2722     return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
2723 }
2724 
2725 void
2726 Process::PausePrivateStateThread ()
2727 {
2728     ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2729 }
2730 
2731 void
2732 Process::ResumePrivateStateThread ()
2733 {
2734     ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2735 }
2736 
2737 void
2738 Process::StopPrivateStateThread ()
2739 {
2740     if (PrivateStateThreadIsValid ())
2741         ControlPrivateStateThread (eBroadcastInternalStateControlStop);
2742 }
2743 
2744 void
2745 Process::ControlPrivateStateThread (uint32_t signal)
2746 {
2747     LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
2748 
2749     assert (signal == eBroadcastInternalStateControlStop ||
2750             signal == eBroadcastInternalStateControlPause ||
2751             signal == eBroadcastInternalStateControlResume);
2752 
2753     if (log)
2754         log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
2755 
2756     // Signal the private state thread. First we should copy this is case the
2757     // thread starts exiting since the private state thread will NULL this out
2758     // when it exits
2759     const lldb::thread_t private_state_thread = m_private_state_thread;
2760     if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
2761     {
2762         TimeValue timeout_time;
2763         bool timed_out;
2764 
2765         m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2766 
2767         timeout_time = TimeValue::Now();
2768         timeout_time.OffsetWithSeconds(2);
2769         m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2770         m_private_state_control_wait.SetValue (false, eBroadcastNever);
2771 
2772         if (signal == eBroadcastInternalStateControlStop)
2773         {
2774             if (timed_out)
2775                 Host::ThreadCancel (private_state_thread, NULL);
2776 
2777             thread_result_t result = NULL;
2778             Host::ThreadJoin (private_state_thread, &result, NULL);
2779             m_private_state_thread = LLDB_INVALID_HOST_THREAD;
2780         }
2781     }
2782 }
2783 
2784 void
2785 Process::HandlePrivateEvent (EventSP &event_sp)
2786 {
2787     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2788 
2789     const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2790 
2791     // First check to see if anybody wants a shot at this event:
2792     if (m_next_event_action_ap.get() != NULL)
2793     {
2794         NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
2795         switch (action_result)
2796         {
2797             case NextEventAction::eEventActionSuccess:
2798                 SetNextEventAction(NULL);
2799                 break;
2800             case NextEventAction::eEventActionRetry:
2801                 break;
2802             case NextEventAction::eEventActionExit:
2803                 // Handle Exiting Here.  If we already got an exited event,
2804                 // we should just propagate it.  Otherwise, swallow this event,
2805                 // and set our state to exit so the next event will kill us.
2806                 if (new_state != eStateExited)
2807                 {
2808                     // FIXME: should cons up an exited event, and discard this one.
2809                     SetExitStatus(0, m_next_event_action_ap->GetExitString());
2810                     SetNextEventAction(NULL);
2811                     return;
2812                 }
2813                 SetNextEventAction(NULL);
2814                 break;
2815         }
2816     }
2817 
2818     // See if we should broadcast this state to external clients?
2819     const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
2820 
2821     if (should_broadcast)
2822     {
2823         if (log)
2824         {
2825             log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2826                          __FUNCTION__,
2827                          GetID(),
2828                          StateAsCString(new_state),
2829                          StateAsCString (GetState ()),
2830                          IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
2831         }
2832         Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
2833         if (StateIsRunningState (new_state))
2834             PushProcessInputReader ();
2835         else
2836             PopProcessInputReader ();
2837 
2838         BroadcastEvent (event_sp);
2839     }
2840     else
2841     {
2842         if (log)
2843         {
2844             log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2845                          __FUNCTION__,
2846                          GetID(),
2847                          StateAsCString(new_state),
2848                          StateAsCString (GetState ()),
2849                          IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
2850         }
2851     }
2852 }
2853 
2854 void *
2855 Process::PrivateStateThread (void *arg)
2856 {
2857     Process *proc = static_cast<Process*> (arg);
2858     void *result = proc->RunPrivateStateThread ();
2859     return result;
2860 }
2861 
2862 void *
2863 Process::RunPrivateStateThread ()
2864 {
2865     bool control_only = false;
2866     m_private_state_control_wait.SetValue (false, eBroadcastNever);
2867 
2868     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2869     if (log)
2870         log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2871 
2872     bool exit_now = false;
2873     while (!exit_now)
2874     {
2875         EventSP event_sp;
2876         WaitForEventsPrivate (NULL, event_sp, control_only);
2877         if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2878         {
2879             switch (event_sp->GetType())
2880             {
2881             case eBroadcastInternalStateControlStop:
2882                 exit_now = true;
2883                 continue;   // Go to next loop iteration so we exit without
2884                 break;      // doing any internal state managment below
2885 
2886             case eBroadcastInternalStateControlPause:
2887                 control_only = true;
2888                 break;
2889 
2890             case eBroadcastInternalStateControlResume:
2891                 control_only = false;
2892                 break;
2893             }
2894 
2895             if (log)
2896                 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2897 
2898             m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2899             continue;
2900         }
2901 
2902 
2903         const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2904 
2905         if (internal_state != eStateInvalid)
2906         {
2907             HandlePrivateEvent (event_sp);
2908         }
2909 
2910         if (internal_state == eStateInvalid ||
2911             internal_state == eStateExited  ||
2912             internal_state == eStateDetached )
2913         {
2914             if (log)
2915                 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2916 
2917             break;
2918         }
2919     }
2920 
2921     // Verify log is still enabled before attempting to write to it...
2922     if (log)
2923         log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2924 
2925     m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2926     m_private_state_thread = LLDB_INVALID_HOST_THREAD;
2927     return NULL;
2928 }
2929 
2930 //------------------------------------------------------------------
2931 // Process Event Data
2932 //------------------------------------------------------------------
2933 
2934 Process::ProcessEventData::ProcessEventData () :
2935     EventData (),
2936     m_process_sp (),
2937     m_state (eStateInvalid),
2938     m_restarted (false),
2939     m_update_state (false),
2940     m_interrupted (false)
2941 {
2942 }
2943 
2944 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2945     EventData (),
2946     m_process_sp (process_sp),
2947     m_state (state),
2948     m_restarted (false),
2949     m_update_state (false),
2950     m_interrupted (false)
2951 {
2952 }
2953 
2954 Process::ProcessEventData::~ProcessEventData()
2955 {
2956 }
2957 
2958 const ConstString &
2959 Process::ProcessEventData::GetFlavorString ()
2960 {
2961     static ConstString g_flavor ("Process::ProcessEventData");
2962     return g_flavor;
2963 }
2964 
2965 const ConstString &
2966 Process::ProcessEventData::GetFlavor () const
2967 {
2968     return ProcessEventData::GetFlavorString ();
2969 }
2970 
2971 void
2972 Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2973 {
2974     // This function gets called twice for each event, once when the event gets pulled
2975     // off of the private process event queue, and once when it gets pulled off of
2976     // the public event queue.  m_update_state is used to distinguish these
2977     // two cases; it is false when we're just pulling it off for private handling,
2978     // and we don't want to do the breakpoint command handling then.
2979 
2980     if (!m_update_state)
2981         return;
2982 
2983     m_process_sp->SetPublicState (m_state);
2984 
2985     // If we're stopped and haven't restarted, then do the breakpoint commands here:
2986     if (m_state == eStateStopped && ! m_restarted)
2987     {
2988         int num_threads = m_process_sp->GetThreadList().GetSize();
2989         int idx;
2990 
2991         for (idx = 0; idx < num_threads; ++idx)
2992         {
2993             lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2994 
2995             StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2996             if (stop_info_sp)
2997             {
2998                 stop_info_sp->PerformAction(event_ptr);
2999             }
3000         }
3001 
3002         // The stop action might restart the target.  If it does, then we want to mark that in the
3003         // event so that whoever is receiving it will know to wait for the running event and reflect
3004         // that state appropriately.
3005 
3006         if (m_process_sp->GetPrivateState() == eStateRunning)
3007             SetRestarted(true);
3008         else
3009         {
3010             // Finally, if we didn't restart, run the Stop Hooks here:
3011             // They might also restart the target, so watch for that.
3012             m_process_sp->GetTarget().RunStopHooks();
3013             if (m_process_sp->GetPrivateState() == eStateRunning)
3014                 SetRestarted(true);
3015         }
3016 
3017     }
3018 }
3019 
3020 void
3021 Process::ProcessEventData::Dump (Stream *s) const
3022 {
3023     if (m_process_sp)
3024         s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
3025 
3026     s->Printf("state = %s", StateAsCString(GetState()));
3027 }
3028 
3029 const Process::ProcessEventData *
3030 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3031 {
3032     if (event_ptr)
3033     {
3034         const EventData *event_data = event_ptr->GetData();
3035         if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3036             return static_cast <const ProcessEventData *> (event_ptr->GetData());
3037     }
3038     return NULL;
3039 }
3040 
3041 ProcessSP
3042 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3043 {
3044     ProcessSP process_sp;
3045     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3046     if (data)
3047         process_sp = data->GetProcessSP();
3048     return process_sp;
3049 }
3050 
3051 StateType
3052 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3053 {
3054     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3055     if (data == NULL)
3056         return eStateInvalid;
3057     else
3058         return data->GetState();
3059 }
3060 
3061 bool
3062 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3063 {
3064     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3065     if (data == NULL)
3066         return false;
3067     else
3068         return data->GetRestarted();
3069 }
3070 
3071 void
3072 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3073 {
3074     ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3075     if (data != NULL)
3076         data->SetRestarted(new_value);
3077 }
3078 
3079 bool
3080 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3081 {
3082     const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3083     if (data == NULL)
3084         return false;
3085     else
3086         return data->GetInterrupted ();
3087 }
3088 
3089 void
3090 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3091 {
3092     ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3093     if (data != NULL)
3094         data->SetInterrupted(new_value);
3095 }
3096 
3097 bool
3098 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3099 {
3100     ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3101     if (data)
3102     {
3103         data->SetUpdateStateOnRemoval();
3104         return true;
3105     }
3106     return false;
3107 }
3108 
3109 void
3110 Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
3111 {
3112     exe_ctx.target = &m_target;
3113     exe_ctx.process = this;
3114     exe_ctx.thread = NULL;
3115     exe_ctx.frame = NULL;
3116 }
3117 
3118 lldb::ProcessSP
3119 Process::GetSP ()
3120 {
3121     return GetTarget().GetProcessSP();
3122 }
3123 
3124 //uint32_t
3125 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3126 //{
3127 //    return 0;
3128 //}
3129 //
3130 //ArchSpec
3131 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3132 //{
3133 //    return Host::GetArchSpecForExistingProcess (pid);
3134 //}
3135 //
3136 //ArchSpec
3137 //Process::GetArchSpecForExistingProcess (const char *process_name)
3138 //{
3139 //    return Host::GetArchSpecForExistingProcess (process_name);
3140 //}
3141 //
3142 void
3143 Process::AppendSTDOUT (const char * s, size_t len)
3144 {
3145     Mutex::Locker locker (m_stdio_communication_mutex);
3146     m_stdout_data.append (s, len);
3147 
3148     BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3149 }
3150 
3151 void
3152 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3153 {
3154     Process *process = (Process *) baton;
3155     process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3156 }
3157 
3158 size_t
3159 Process::ProcessInputReaderCallback (void *baton,
3160                                      InputReader &reader,
3161                                      lldb::InputReaderAction notification,
3162                                      const char *bytes,
3163                                      size_t bytes_len)
3164 {
3165     Process *process = (Process *) baton;
3166 
3167     switch (notification)
3168     {
3169     case eInputReaderActivate:
3170         break;
3171 
3172     case eInputReaderDeactivate:
3173         break;
3174 
3175     case eInputReaderReactivate:
3176         break;
3177 
3178     case eInputReaderGotToken:
3179         {
3180             Error error;
3181             process->PutSTDIN (bytes, bytes_len, error);
3182         }
3183         break;
3184 
3185     case eInputReaderInterrupt:
3186         process->Halt ();
3187         break;
3188 
3189     case eInputReaderEndOfFile:
3190         process->AppendSTDOUT ("^D", 2);
3191         break;
3192 
3193     case eInputReaderDone:
3194         break;
3195 
3196     }
3197 
3198     return bytes_len;
3199 }
3200 
3201 void
3202 Process::ResetProcessInputReader ()
3203 {
3204     m_process_input_reader.reset();
3205 }
3206 
3207 void
3208 Process::SetUpProcessInputReader (int file_descriptor)
3209 {
3210     // First set up the Read Thread for reading/handling process I/O
3211 
3212     std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3213 
3214     if (conn_ap.get())
3215     {
3216         m_stdio_communication.SetConnection (conn_ap.release());
3217         if (m_stdio_communication.IsConnected())
3218         {
3219             m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3220             m_stdio_communication.StartReadThread();
3221 
3222             // Now read thread is set up, set up input reader.
3223 
3224             if (!m_process_input_reader.get())
3225             {
3226                 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3227                 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3228                                                                this,
3229                                                                eInputReaderGranularityByte,
3230                                                                NULL,
3231                                                                NULL,
3232                                                                false));
3233 
3234                 if  (err.Fail())
3235                     m_process_input_reader.reset();
3236             }
3237         }
3238     }
3239 }
3240 
3241 void
3242 Process::PushProcessInputReader ()
3243 {
3244     if (m_process_input_reader && !m_process_input_reader->IsActive())
3245         m_target.GetDebugger().PushInputReader (m_process_input_reader);
3246 }
3247 
3248 void
3249 Process::PopProcessInputReader ()
3250 {
3251     if (m_process_input_reader && m_process_input_reader->IsActive())
3252         m_target.GetDebugger().PopInputReader (m_process_input_reader);
3253 }
3254 
3255 // The process needs to know about installed plug-ins
3256 void
3257 Process::SettingsInitialize ()
3258 {
3259     static std::vector<OptionEnumValueElement> g_plugins;
3260 
3261     int i=0;
3262     const char *name;
3263     OptionEnumValueElement option_enum;
3264     while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3265     {
3266         if (name)
3267         {
3268             option_enum.value = i;
3269             option_enum.string_value = name;
3270             option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3271             g_plugins.push_back (option_enum);
3272         }
3273         ++i;
3274     }
3275     option_enum.value = 0;
3276     option_enum.string_value = NULL;
3277     option_enum.usage = NULL;
3278     g_plugins.push_back (option_enum);
3279 
3280     for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3281     {
3282         if (::strcmp (name, "plugin") == 0)
3283         {
3284             SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3285             break;
3286         }
3287     }
3288     UserSettingsControllerSP &usc = GetSettingsController();
3289     usc.reset (new SettingsController);
3290     UserSettingsController::InitializeSettingsController (usc,
3291                                                           SettingsController::global_settings_table,
3292                                                           SettingsController::instance_settings_table);
3293 
3294     // Now call SettingsInitialize() for each 'child' of Process settings
3295     Thread::SettingsInitialize ();
3296 }
3297 
3298 void
3299 Process::SettingsTerminate ()
3300 {
3301     // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3302 
3303     Thread::SettingsTerminate ();
3304 
3305     // Now terminate Process Settings.
3306 
3307     UserSettingsControllerSP &usc = GetSettingsController();
3308     UserSettingsController::FinalizeSettingsController (usc);
3309     usc.reset();
3310 }
3311 
3312 UserSettingsControllerSP &
3313 Process::GetSettingsController ()
3314 {
3315     static UserSettingsControllerSP g_settings_controller;
3316     return g_settings_controller;
3317 }
3318 
3319 void
3320 Process::UpdateInstanceName ()
3321 {
3322     ModuleSP module_sp = GetTarget().GetExecutableModule();
3323     if (module_sp)
3324     {
3325         StreamString sstr;
3326         sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
3327 
3328         GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
3329                                                          sstr.GetData());
3330     }
3331 }
3332 
3333 ExecutionResults
3334 Process::RunThreadPlan (ExecutionContext &exe_ctx,
3335                         lldb::ThreadPlanSP &thread_plan_sp,
3336                         bool stop_others,
3337                         bool try_all_threads,
3338                         bool discard_on_error,
3339                         uint32_t single_thread_timeout_usec,
3340                         Stream &errors)
3341 {
3342     ExecutionResults return_value = eExecutionSetupError;
3343 
3344     if (thread_plan_sp.get() == NULL)
3345     {
3346         errors.Printf("RunThreadPlan called with empty thread plan.");
3347         return eExecutionSetupError;
3348     }
3349 
3350     if (m_private_state.GetValue() != eStateStopped)
3351     {
3352         errors.Printf ("RunThreadPlan called while the private state was not stopped.");
3353         return eExecutionSetupError;
3354     }
3355 
3356     // Save this value for restoration of the execution context after we run
3357     uint32_t tid = exe_ctx.thread->GetIndexID();
3358 
3359     // N.B. Running the target may unset the currently selected thread and frame.  We don't want to do that either,
3360     // so we should arrange to reset them as well.
3361 
3362     lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
3363     lldb::StackFrameSP selected_frame_sp;
3364 
3365     uint32_t selected_tid;
3366     if (selected_thread_sp != NULL)
3367     {
3368         selected_tid = selected_thread_sp->GetIndexID();
3369         selected_frame_sp = selected_thread_sp->GetSelectedFrame();
3370     }
3371     else
3372     {
3373         selected_tid = LLDB_INVALID_THREAD_ID;
3374     }
3375 
3376     exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
3377 
3378     Listener listener("lldb.process.listener.run-thread-plan");
3379 
3380     // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3381     // restored on exit to the function.
3382 
3383     ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
3384 
3385     lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3386     if (log)
3387     {
3388         StreamString s;
3389         thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
3390         log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
3391                      exe_ctx.thread->GetIndexID(),
3392                      exe_ctx.thread->GetID(),
3393                      s.GetData());
3394     }
3395 
3396     bool got_event;
3397     lldb::EventSP event_sp;
3398     lldb::StateType stop_state = lldb::eStateInvalid;
3399 
3400     TimeValue* timeout_ptr = NULL;
3401     TimeValue real_timeout;
3402 
3403     bool first_timeout = true;
3404     bool do_resume = true;
3405 
3406     while (1)
3407     {
3408         // We usually want to resume the process if we get to the top of the loop.
3409         // The only exception is if we get two running events with no intervening
3410         // stop, which can happen, we will just wait for then next stop event.
3411 
3412         if (do_resume)
3413         {
3414             // Do the initial resume and wait for the running event before going further.
3415 
3416             Error resume_error = exe_ctx.process->Resume ();
3417             if (!resume_error.Success())
3418             {
3419                 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
3420                 return_value = eExecutionSetupError;
3421                 break;
3422             }
3423 
3424             real_timeout = TimeValue::Now();
3425             real_timeout.OffsetWithMicroSeconds(500000);
3426             timeout_ptr = &real_timeout;
3427 
3428             got_event = listener.WaitForEvent(NULL, event_sp);
3429             if (!got_event)
3430             {
3431                 if (log)
3432                     log->Printf("Didn't get any event after initial resume, exiting.");
3433 
3434                 errors.Printf("Didn't get any event after initial resume, exiting.");
3435                 return_value = eExecutionSetupError;
3436                 break;
3437             }
3438 
3439             stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3440             if (stop_state != eStateRunning)
3441             {
3442                 if (log)
3443                     log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3444 
3445                 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3446                 return_value = eExecutionSetupError;
3447                 break;
3448             }
3449 
3450             if (log)
3451                 log->Printf ("Resuming succeeded.");
3452             // We need to call the function synchronously, so spin waiting for it to return.
3453             // If we get interrupted while executing, we're going to lose our context, and
3454             // won't be able to gather the result at this point.
3455             // We set the timeout AFTER the resume, since the resume takes some time and we
3456             // don't want to charge that to the timeout.
3457 
3458             if (single_thread_timeout_usec != 0)
3459             {
3460                 real_timeout = TimeValue::Now();
3461                 if (first_timeout)
3462                     real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3463                 else
3464                     real_timeout.OffsetWithSeconds(10);
3465 
3466                 timeout_ptr = &real_timeout;
3467             }
3468         }
3469         else
3470         {
3471             if (log)
3472                 log->Printf ("Handled an extra running event.");
3473             do_resume = true;
3474         }
3475 
3476         // Now wait for the process to stop again:
3477         stop_state = lldb::eStateInvalid;
3478         event_sp.reset();
3479         got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3480 
3481         if (got_event)
3482         {
3483             if (event_sp.get())
3484             {
3485                 bool keep_going = false;
3486                 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3487                 if (log)
3488                     log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3489 
3490                 switch (stop_state)
3491                 {
3492                 case lldb::eStateStopped:
3493                     // Yay, we're done.
3494                     if (log)
3495                         log->Printf ("Execution completed successfully.");
3496                     return_value = eExecutionCompleted;
3497                     break;
3498                 case lldb::eStateCrashed:
3499                     if (log)
3500                         log->Printf ("Execution crashed.");
3501                     return_value = eExecutionInterrupted;
3502                     break;
3503                 case lldb::eStateRunning:
3504                     do_resume = false;
3505                     keep_going = true;
3506                     break;
3507                 default:
3508                     if (log)
3509                         log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
3510                     return_value = eExecutionInterrupted;
3511                     break;
3512                 }
3513                 if (keep_going)
3514                     continue;
3515                 else
3516                     break;
3517             }
3518             else
3519             {
3520                 if (log)
3521                     log->Printf ("got_event was true, but the event pointer was null.  How odd...");
3522                 return_value = eExecutionInterrupted;
3523                 break;
3524             }
3525         }
3526         else
3527         {
3528             // If we didn't get an event that means we've timed out...
3529             // We will interrupt the process here.  Depending on what we were asked to do we will
3530             // either exit, or try with all threads running for the same timeout.
3531             // Not really sure what to do if Halt fails here...
3532 
3533             if (log) {
3534                 if (try_all_threads)
3535                 {
3536                     if (first_timeout)
3537                         log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3538                                      "trying with all threads enabled.",
3539                                      single_thread_timeout_usec);
3540                     else
3541                         log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3542                                      "and timeout: %d timed out.",
3543                                      single_thread_timeout_usec);
3544                 }
3545                 else
3546                     log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3547                                  "halt and abandoning execution.",
3548                                  single_thread_timeout_usec);
3549             }
3550 
3551             Error halt_error = exe_ctx.process->Halt();
3552             if (halt_error.Success())
3553             {
3554                 if (log)
3555                     log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
3556 
3557                 // If halt succeeds, it always produces a stopped event.  Wait for that:
3558 
3559                 real_timeout = TimeValue::Now();
3560                 real_timeout.OffsetWithMicroSeconds(500000);
3561 
3562                 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3563 
3564                 if (got_event)
3565                 {
3566                     stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3567                     if (log)
3568                     {
3569                         log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
3570                         if (stop_state == lldb::eStateStopped
3571                             && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
3572                             log->Printf ("    Event was the Halt interruption event.");
3573                     }
3574 
3575                     if (stop_state == lldb::eStateStopped)
3576                     {
3577                         // Between the time we initiated the Halt and the time we delivered it, the process could have
3578                         // already finished its job.  Check that here:
3579 
3580                         if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3581                         {
3582                             if (log)
3583                                 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done.  "
3584                                              "Exiting wait loop.");
3585                             return_value = eExecutionCompleted;
3586                             break;
3587                         }
3588 
3589                         if (!try_all_threads)
3590                         {
3591                             if (log)
3592                                 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
3593                             return_value = eExecutionInterrupted;
3594                             break;
3595                         }
3596 
3597                         if (first_timeout)
3598                         {
3599                             // Set all the other threads to run, and return to the top of the loop, which will continue;
3600                             first_timeout = false;
3601                             thread_plan_sp->SetStopOthers (false);
3602                             if (log)
3603                                 log->Printf ("Process::RunThreadPlan(): About to resume.");
3604 
3605                             continue;
3606                         }
3607                         else
3608                         {
3609                             // Running all threads failed, so return Interrupted.
3610                             if (log)
3611                                 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3612                             return_value = eExecutionInterrupted;
3613                             break;
3614                         }
3615                     }
3616                 }
3617                 else
3618                 {   if (log)
3619                         log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event.  "
3620                                 "I'm getting out of here passing Interrupted.");
3621                     return_value = eExecutionInterrupted;
3622                     break;
3623                 }
3624             }
3625             else
3626             {
3627                 // This branch is to work around some problems with gdb-remote's Halt.  It is a little racy, and can return
3628                 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
3629                 if (log)
3630                     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.",
3631                                  halt_error.AsCString());
3632                 real_timeout = TimeValue::Now();
3633                 real_timeout.OffsetWithMicroSeconds(500000);
3634                 timeout_ptr = &real_timeout;
3635                 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3636                 if (!got_event || event_sp.get() == NULL)
3637                 {
3638                     // This is not going anywhere, bag out.
3639                     if (log)
3640                         log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
3641                     return_value = eExecutionInterrupted;
3642                     break;
3643                 }
3644                 else
3645                 {
3646                     stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3647                     if (log)
3648                         log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event.  Whatever...");
3649                     if (stop_state == lldb::eStateStopped)
3650                     {
3651                         // Between the time we initiated the Halt and the time we delivered it, the process could have
3652                         // already finished its job.  Check that here:
3653 
3654                         if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3655                         {
3656                             if (log)
3657                                 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done.  "
3658                                              "Exiting wait loop.");
3659                             return_value = eExecutionCompleted;
3660                             break;
3661                         }
3662 
3663                         if (first_timeout)
3664                         {
3665                             // Set all the other threads to run, and return to the top of the loop, which will continue;
3666                             first_timeout = false;
3667                             thread_plan_sp->SetStopOthers (false);
3668                             if (log)
3669                                 log->Printf ("Process::RunThreadPlan(): About to resume.");
3670 
3671                             continue;
3672                         }
3673                         else
3674                         {
3675                             // Running all threads failed, so return Interrupted.
3676                             if (log)
3677                                 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
3678                             return_value = eExecutionInterrupted;
3679                             break;
3680                         }
3681                     }
3682                     else
3683                     {
3684                         log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3685                                      " a stopped event, instead got %s.", StateAsCString(stop_state));
3686                         return_value = eExecutionInterrupted;
3687                         break;
3688                     }
3689                 }
3690             }
3691 
3692         }
3693 
3694     }  // END WAIT LOOP
3695 
3696     // Now do some processing on the results of the run:
3697     if (return_value == eExecutionInterrupted)
3698     {
3699         if (log)
3700         {
3701             StreamString s;
3702             if (event_sp)
3703                 event_sp->Dump (&s);
3704             else
3705             {
3706                 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3707             }
3708 
3709             StreamString ts;
3710 
3711             const char *event_explanation;
3712 
3713             do
3714             {
3715                 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3716 
3717                 if (!event_data)
3718                 {
3719                     event_explanation = "<no event data>";
3720                     break;
3721                 }
3722 
3723                 Process *process = event_data->GetProcessSP().get();
3724 
3725                 if (!process)
3726                 {
3727                     event_explanation = "<no process>";
3728                     break;
3729                 }
3730 
3731                 ThreadList &thread_list = process->GetThreadList();
3732 
3733                 uint32_t num_threads = thread_list.GetSize();
3734                 uint32_t thread_index;
3735 
3736                 ts.Printf("<%u threads> ", num_threads);
3737 
3738                 for (thread_index = 0;
3739                      thread_index < num_threads;
3740                      ++thread_index)
3741                 {
3742                     Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3743 
3744                     if (!thread)
3745                     {
3746                         ts.Printf("<?> ");
3747                         continue;
3748                     }
3749 
3750                     ts.Printf("<0x%4.4x ", thread->GetID());
3751                     RegisterContext *register_context = thread->GetRegisterContext().get();
3752 
3753                     if (register_context)
3754                         ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3755                     else
3756                         ts.Printf("[ip unknown] ");
3757 
3758                     lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3759                     if (stop_info_sp)
3760                     {
3761                         const char *stop_desc = stop_info_sp->GetDescription();
3762                         if (stop_desc)
3763                             ts.PutCString (stop_desc);
3764                     }
3765                     ts.Printf(">");
3766                 }
3767 
3768                 event_explanation = ts.GetData();
3769             } while (0);
3770 
3771             if (log)
3772                 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3773 
3774             if (discard_on_error && thread_plan_sp)
3775             {
3776                 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3777             }
3778         }
3779     }
3780     else if (return_value == eExecutionSetupError)
3781     {
3782         if (log)
3783             log->Printf("Process::RunThreadPlan(): execution set up error.");
3784 
3785         if (discard_on_error && thread_plan_sp)
3786         {
3787             exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3788         }
3789     }
3790     else
3791     {
3792         if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3793         {
3794             if (log)
3795                 log->Printf("Process::RunThreadPlan(): thread plan is done");
3796             return_value = eExecutionCompleted;
3797         }
3798         else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3799         {
3800             if (log)
3801                 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
3802             return_value = eExecutionDiscarded;
3803         }
3804         else
3805         {
3806             if (log)
3807                 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
3808             if (discard_on_error && thread_plan_sp)
3809             {
3810                 if (log)
3811                     log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
3812                 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3813             }
3814         }
3815     }
3816 
3817     // Thread we ran the function in may have gone away because we ran the target
3818     // Check that it's still there.
3819     exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3820     if (exe_ctx.thread)
3821         exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3822 
3823     // Also restore the current process'es selected frame & thread, since this function calling may
3824     // be done behind the user's back.
3825 
3826     if (selected_tid != LLDB_INVALID_THREAD_ID)
3827     {
3828         if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3829         {
3830             // We were able to restore the selected thread, now restore the frame:
3831             exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3832         }
3833     }
3834 
3835     return return_value;
3836 }
3837 
3838 const char *
3839 Process::ExecutionResultAsCString (ExecutionResults result)
3840 {
3841     const char *result_name;
3842 
3843     switch (result)
3844     {
3845         case eExecutionCompleted:
3846             result_name = "eExecutionCompleted";
3847             break;
3848         case eExecutionDiscarded:
3849             result_name = "eExecutionDiscarded";
3850             break;
3851         case eExecutionInterrupted:
3852             result_name = "eExecutionInterrupted";
3853             break;
3854         case eExecutionSetupError:
3855             result_name = "eExecutionSetupError";
3856             break;
3857         case eExecutionTimedOut:
3858             result_name = "eExecutionTimedOut";
3859             break;
3860     }
3861     return result_name;
3862 }
3863 
3864 //--------------------------------------------------------------
3865 // class Process::SettingsController
3866 //--------------------------------------------------------------
3867 
3868 Process::SettingsController::SettingsController () :
3869     UserSettingsController ("process", Target::GetSettingsController())
3870 {
3871     m_default_settings.reset (new ProcessInstanceSettings (*this,
3872                                                            false,
3873                                                            InstanceSettings::GetDefaultName().AsCString()));
3874 }
3875 
3876 Process::SettingsController::~SettingsController ()
3877 {
3878 }
3879 
3880 lldb::InstanceSettingsSP
3881 Process::SettingsController::CreateInstanceSettings (const char *instance_name)
3882 {
3883     ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3884                                                                          false,
3885                                                                          instance_name);
3886     lldb::InstanceSettingsSP new_settings_sp (new_settings);
3887     return new_settings_sp;
3888 }
3889 
3890 //--------------------------------------------------------------
3891 // class ProcessInstanceSettings
3892 //--------------------------------------------------------------
3893 
3894 ProcessInstanceSettings::ProcessInstanceSettings
3895 (
3896     UserSettingsController &owner,
3897     bool live_instance,
3898     const char *name
3899 ) :
3900     InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
3901     m_run_args (),
3902     m_env_vars (),
3903     m_input_path (),
3904     m_output_path (),
3905     m_error_path (),
3906     m_disable_aslr (true),
3907     m_disable_stdio (false),
3908     m_inherit_host_env (true),
3909     m_got_host_env (false)
3910 {
3911     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3912     // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3913     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
3914     // This is true for CreateInstanceName() too.
3915 
3916     if (GetInstanceName () == InstanceSettings::InvalidName())
3917     {
3918         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3919         m_owner.RegisterInstanceSettings (this);
3920     }
3921 
3922     if (live_instance)
3923     {
3924         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3925         CopyInstanceSettings (pending_settings,false);
3926         //m_owner.RemovePendingSettings (m_instance_name);
3927     }
3928 }
3929 
3930 ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
3931     InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
3932     m_run_args (rhs.m_run_args),
3933     m_env_vars (rhs.m_env_vars),
3934     m_input_path (rhs.m_input_path),
3935     m_output_path (rhs.m_output_path),
3936     m_error_path (rhs.m_error_path),
3937     m_disable_aslr (rhs.m_disable_aslr),
3938     m_disable_stdio (rhs.m_disable_stdio)
3939 {
3940     if (m_instance_name != InstanceSettings::GetDefaultName())
3941     {
3942         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3943         CopyInstanceSettings (pending_settings,false);
3944         m_owner.RemovePendingSettings (m_instance_name);
3945     }
3946 }
3947 
3948 ProcessInstanceSettings::~ProcessInstanceSettings ()
3949 {
3950 }
3951 
3952 ProcessInstanceSettings&
3953 ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
3954 {
3955     if (this != &rhs)
3956     {
3957         m_run_args = rhs.m_run_args;
3958         m_env_vars = rhs.m_env_vars;
3959         m_input_path = rhs.m_input_path;
3960         m_output_path = rhs.m_output_path;
3961         m_error_path = rhs.m_error_path;
3962         m_disable_aslr = rhs.m_disable_aslr;
3963         m_disable_stdio = rhs.m_disable_stdio;
3964         m_inherit_host_env = rhs.m_inherit_host_env;
3965     }
3966 
3967     return *this;
3968 }
3969 
3970 
3971 void
3972 ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
3973                                                          const char *index_value,
3974                                                          const char *value,
3975                                                          const ConstString &instance_name,
3976                                                          const SettingEntry &entry,
3977                                                          VarSetOperationType op,
3978                                                          Error &err,
3979                                                          bool pending)
3980 {
3981     if (var_name == RunArgsVarName())
3982         UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
3983     else if (var_name == EnvVarsVarName())
3984     {
3985         // This is nice for local debugging, but it is isn't correct for
3986         // remote debugging. We need to stop process.env-vars from being
3987         // populated with the host environment and add this as a launch option
3988         // and get the correct environment from the Target's platform.
3989         // GetHostEnvironmentIfNeeded ();
3990         UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
3991     }
3992     else if (var_name == InputPathVarName())
3993         UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
3994     else if (var_name == OutputPathVarName())
3995         UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
3996     else if (var_name == ErrorPathVarName())
3997         UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
3998     else if (var_name == DisableASLRVarName())
3999         UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, err);
4000     else if (var_name == DisableSTDIOVarName ())
4001         UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, err);
4002 }
4003 
4004 void
4005 ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4006                                                bool pending)
4007 {
4008     if (new_settings.get() == NULL)
4009         return;
4010 
4011     ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4012 
4013     m_run_args = new_process_settings->m_run_args;
4014     m_env_vars = new_process_settings->m_env_vars;
4015     m_input_path = new_process_settings->m_input_path;
4016     m_output_path = new_process_settings->m_output_path;
4017     m_error_path = new_process_settings->m_error_path;
4018     m_disable_aslr = new_process_settings->m_disable_aslr;
4019     m_disable_stdio = new_process_settings->m_disable_stdio;
4020 }
4021 
4022 bool
4023 ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4024                                                    const ConstString &var_name,
4025                                                    StringList &value,
4026                                                    Error *err)
4027 {
4028     if (var_name == RunArgsVarName())
4029     {
4030         if (m_run_args.GetArgumentCount() > 0)
4031         {
4032             for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4033                 value.AppendString (m_run_args.GetArgumentAtIndex (i));
4034         }
4035     }
4036     else if (var_name == EnvVarsVarName())
4037     {
4038         GetHostEnvironmentIfNeeded ();
4039 
4040         if (m_env_vars.size() > 0)
4041         {
4042             std::map<std::string, std::string>::iterator pos;
4043             for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4044             {
4045                 StreamString value_str;
4046                 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4047                 value.AppendString (value_str.GetData());
4048             }
4049         }
4050     }
4051     else if (var_name == InputPathVarName())
4052     {
4053         value.AppendString (m_input_path.c_str());
4054     }
4055     else if (var_name == OutputPathVarName())
4056     {
4057         value.AppendString (m_output_path.c_str());
4058     }
4059     else if (var_name == ErrorPathVarName())
4060     {
4061         value.AppendString (m_error_path.c_str());
4062     }
4063     else if (var_name == InheritHostEnvVarName())
4064     {
4065         if (m_inherit_host_env)
4066             value.AppendString ("true");
4067         else
4068             value.AppendString ("false");
4069     }
4070     else if (var_name == DisableASLRVarName())
4071     {
4072         if (m_disable_aslr)
4073             value.AppendString ("true");
4074         else
4075             value.AppendString ("false");
4076     }
4077     else if (var_name == DisableSTDIOVarName())
4078     {
4079         if (m_disable_stdio)
4080             value.AppendString ("true");
4081         else
4082             value.AppendString ("false");
4083     }
4084     else
4085     {
4086         if (err)
4087             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4088         return false;
4089     }
4090     return true;
4091 }
4092 
4093 const ConstString
4094 ProcessInstanceSettings::CreateInstanceName ()
4095 {
4096     static int instance_count = 1;
4097     StreamString sstr;
4098 
4099     sstr.Printf ("process_%d", instance_count);
4100     ++instance_count;
4101 
4102     const ConstString ret_val (sstr.GetData());
4103     return ret_val;
4104 }
4105 
4106 const ConstString &
4107 ProcessInstanceSettings::RunArgsVarName ()
4108 {
4109     static ConstString run_args_var_name ("run-args");
4110 
4111     return run_args_var_name;
4112 }
4113 
4114 const ConstString &
4115 ProcessInstanceSettings::EnvVarsVarName ()
4116 {
4117     static ConstString env_vars_var_name ("env-vars");
4118 
4119     return env_vars_var_name;
4120 }
4121 
4122 const ConstString &
4123 ProcessInstanceSettings::InheritHostEnvVarName ()
4124 {
4125     static ConstString g_name ("inherit-env");
4126 
4127     return g_name;
4128 }
4129 
4130 const ConstString &
4131 ProcessInstanceSettings::InputPathVarName ()
4132 {
4133   static ConstString input_path_var_name ("input-path");
4134 
4135     return input_path_var_name;
4136 }
4137 
4138 const ConstString &
4139 ProcessInstanceSettings::OutputPathVarName ()
4140 {
4141     static ConstString output_path_var_name ("output-path");
4142 
4143     return output_path_var_name;
4144 }
4145 
4146 const ConstString &
4147 ProcessInstanceSettings::ErrorPathVarName ()
4148 {
4149     static ConstString error_path_var_name ("error-path");
4150 
4151     return error_path_var_name;
4152 }
4153 
4154 const ConstString &
4155 ProcessInstanceSettings::DisableASLRVarName ()
4156 {
4157     static ConstString disable_aslr_var_name ("disable-aslr");
4158 
4159     return disable_aslr_var_name;
4160 }
4161 
4162 const ConstString &
4163 ProcessInstanceSettings::DisableSTDIOVarName ()
4164 {
4165     static ConstString disable_stdio_var_name ("disable-stdio");
4166 
4167     return disable_stdio_var_name;
4168 }
4169 
4170 //--------------------------------------------------
4171 // SettingsController Variable Tables
4172 //--------------------------------------------------
4173 
4174 SettingEntry
4175 Process::SettingsController::global_settings_table[] =
4176 {
4177   //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
4178     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4179 };
4180 
4181 
4182 SettingEntry
4183 Process::SettingsController::instance_settings_table[] =
4184 {
4185   //{ "var-name",       var-type,              "default",       enum-table, init'd, hidden, "help-text"},
4186     { "run-args",       eSetVarTypeArray,       NULL,           NULL,       false,  false,  "A list containing all the arguments to be passed to the executable when it is run." },
4187     { "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." },
4188     { "inherit-env",    eSetVarTypeBoolean,     "true",         NULL,       false,  false,  "Inherit the environment from the process that is running LLDB." },
4189     { "input-path",     eSetVarTypeString,      NULL,           NULL,       false,  false,  "The file/path to be used by the executable program for reading its input." },
4190     { "output-path",    eSetVarTypeString,      NULL,           NULL,       false,  false,  "The file/path to be used by the executable program for writing its output." },
4191     { "error-path",     eSetVarTypeString,      NULL,           NULL,       false,  false,  "The file/path to be used by the executable program for writings its error messages." },
4192     { "plugin",         eSetVarTypeEnum,        NULL,           NULL,       false,  false,  "The plugin to be used to run the process." },
4193     { "disable-aslr",   eSetVarTypeBoolean,     "true",         NULL,       false,  false,  "Disable Address Space Layout Randomization (ASLR)" },
4194     { "disable-stdio",  eSetVarTypeBoolean,     "false",        NULL,       false,  false,  "Disable stdin/stdout for process (e.g. for a GUI application)" },
4195     {  NULL,            eSetVarTypeNone,        NULL,           NULL,       false,  false,  NULL }
4196 };
4197 
4198 
4199 
4200