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