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