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