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