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