1254721Semaste//===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2254721Semaste//
3254721Semaste//                     The LLVM Compiler Infrastructure
4254721Semaste//
5254721Semaste// This file is distributed under the University of Illinois Open Source
6254721Semaste// License. See LICENSE.TXT for details.
7254721Semaste//
8254721Semaste//===----------------------------------------------------------------------===//
9254721Semaste
10254721Semaste#include "lldb/lldb-python.h"
11254721Semaste
12254721Semaste#include "lldb/Core/Debugger.h"
13254721Semaste
14254721Semaste#include <map>
15254721Semaste
16254721Semaste#include "clang/AST/DeclCXX.h"
17254721Semaste#include "clang/AST/Type.h"
18254721Semaste
19254721Semaste#include "lldb/lldb-private.h"
20254721Semaste#include "lldb/Core/ConnectionFileDescriptor.h"
21254721Semaste#include "lldb/Core/Module.h"
22254721Semaste#include "lldb/Core/PluginManager.h"
23254721Semaste#include "lldb/Core/RegisterValue.h"
24254721Semaste#include "lldb/Core/State.h"
25254721Semaste#include "lldb/Core/StreamAsynchronousIO.h"
26254721Semaste#include "lldb/Core/StreamCallback.h"
27269024Semaste#include "lldb/Core/StreamFile.h"
28254721Semaste#include "lldb/Core/StreamString.h"
29254721Semaste#include "lldb/Core/Timer.h"
30254721Semaste#include "lldb/Core/ValueObject.h"
31254721Semaste#include "lldb/Core/ValueObjectVariable.h"
32254721Semaste#include "lldb/DataFormatters/DataVisualization.h"
33254721Semaste#include "lldb/DataFormatters/FormatManager.h"
34254721Semaste#include "lldb/Host/DynamicLibrary.h"
35254721Semaste#include "lldb/Host/Terminal.h"
36254721Semaste#include "lldb/Interpreter/CommandInterpreter.h"
37254721Semaste#include "lldb/Interpreter/OptionValueSInt64.h"
38254721Semaste#include "lldb/Interpreter/OptionValueString.h"
39254721Semaste#include "lldb/Symbol/ClangASTContext.h"
40254721Semaste#include "lldb/Symbol/CompileUnit.h"
41254721Semaste#include "lldb/Symbol/Function.h"
42254721Semaste#include "lldb/Symbol/Symbol.h"
43254721Semaste#include "lldb/Symbol/VariableList.h"
44254721Semaste#include "lldb/Target/TargetList.h"
45254721Semaste#include "lldb/Target/Process.h"
46254721Semaste#include "lldb/Target/RegisterContext.h"
47263367Semaste#include "lldb/Target/SectionLoadList.h"
48254721Semaste#include "lldb/Target/StopInfo.h"
49254721Semaste#include "lldb/Target/Target.h"
50254721Semaste#include "lldb/Target/Thread.h"
51254721Semaste#include "lldb/Utility/AnsiTerminal.h"
52254721Semaste
53254721Semasteusing namespace lldb;
54254721Semasteusing namespace lldb_private;
55254721Semaste
56254721Semaste
57254721Semastestatic uint32_t g_shared_debugger_refcount = 0;
58254721Semastestatic lldb::user_id_t g_unique_id = 1;
59254721Semaste
60254721Semaste#pragma mark Static Functions
61254721Semaste
62254721Semastestatic Mutex &
63254721SemasteGetDebuggerListMutex ()
64254721Semaste{
65254721Semaste    static Mutex g_mutex(Mutex::eMutexTypeRecursive);
66254721Semaste    return g_mutex;
67254721Semaste}
68254721Semaste
69254721Semastetypedef std::vector<DebuggerSP> DebuggerList;
70254721Semaste
71254721Semastestatic DebuggerList &
72254721SemasteGetDebuggerList()
73254721Semaste{
74254721Semaste    // hide the static debugger list inside a singleton accessor to avoid
75254721Semaste    // global init contructors
76254721Semaste    static DebuggerList g_list;
77254721Semaste    return g_list;
78254721Semaste}
79254721Semaste
80254721SemasteOptionEnumValueElement
81254721Semasteg_show_disassembly_enum_values[] =
82254721Semaste{
83254721Semaste    { Debugger::eStopDisassemblyTypeNever,    "never",     "Never show disassembly when displaying a stop context."},
84254721Semaste    { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
85254721Semaste    { Debugger::eStopDisassemblyTypeAlways,   "always",    "Always show disassembly when displaying a stop context."},
86254721Semaste    { 0, NULL, NULL }
87254721Semaste};
88254721Semaste
89254721SemasteOptionEnumValueElement
90254721Semasteg_language_enumerators[] =
91254721Semaste{
92254721Semaste    { eScriptLanguageNone,      "none",     "Disable scripting languages."},
93254721Semaste    { eScriptLanguagePython,    "python",   "Select python as the default scripting language."},
94254721Semaste    { eScriptLanguageDefault,   "default",  "Select the lldb default as the default scripting language."},
95254721Semaste    { 0, NULL, NULL }
96254721Semaste};
97254721Semaste
98254721Semaste#define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
99254721Semaste#define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
100254721Semaste
101254721Semaste#define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
102254721Semaste    "{, ${frame.pc}}"\
103254721Semaste    MODULE_WITH_FUNC\
104254721Semaste    FILE_AND_LINE\
105254721Semaste    "{, name = '${thread.name}'}"\
106254721Semaste    "{, queue = '${thread.queue}'}"\
107254721Semaste    "{, stop reason = ${thread.stop-reason}}"\
108254721Semaste    "{\\nReturn value: ${thread.return-value}}"\
109254721Semaste    "\\n"
110254721Semaste
111254721Semaste#define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
112254721Semaste    MODULE_WITH_FUNC\
113254721Semaste    FILE_AND_LINE\
114254721Semaste    "\\n"
115254721Semaste
116254721Semaste
117254721Semaste
118254721Semastestatic PropertyDefinition
119254721Semasteg_properties[] =
120254721Semaste{
121254721Semaste{   "auto-confirm",             OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
122254721Semaste{   "frame-format",             OptionValue::eTypeString , true, 0    , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
123254721Semaste{   "notify-void",              OptionValue::eTypeBoolean, true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
124254721Semaste{   "prompt",                   OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
125254721Semaste{   "script-lang",              OptionValue::eTypeEnum   , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
126254721Semaste{   "stop-disassembly-count",   OptionValue::eTypeSInt64 , true, 4    , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
127254721Semaste{   "stop-disassembly-display", OptionValue::eTypeEnum   , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
128254721Semaste{   "stop-line-count-after",    OptionValue::eTypeSInt64 , true, 3    , NULL, NULL, "The number of sources lines to display that come after the current source line when displaying a stopped context." },
129254721Semaste{   "stop-line-count-before",   OptionValue::eTypeSInt64 , true, 3    , NULL, NULL, "The number of sources lines to display that come before the current source line when displaying a stopped context." },
130254721Semaste{   "term-width",               OptionValue::eTypeSInt64 , true, 80   , NULL, NULL, "The maximum number of columns to use for displaying text." },
131254721Semaste{   "thread-format",            OptionValue::eTypeString , true, 0    , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
132254721Semaste{   "use-external-editor",      OptionValue::eTypeBoolean, true, false, NULL, NULL, "Whether to use an external editor or not." },
133254721Semaste{   "use-color",                OptionValue::eTypeBoolean, true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
134263363Semaste{   "auto-one-line-summaries",     OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
135254721Semaste
136254721Semaste    {   NULL,                       OptionValue::eTypeInvalid, true, 0    , NULL, NULL, NULL }
137254721Semaste};
138254721Semaste
139254721Semasteenum
140254721Semaste{
141254721Semaste    ePropertyAutoConfirm = 0,
142254721Semaste    ePropertyFrameFormat,
143254721Semaste    ePropertyNotiftVoid,
144254721Semaste    ePropertyPrompt,
145254721Semaste    ePropertyScriptLanguage,
146254721Semaste    ePropertyStopDisassemblyCount,
147254721Semaste    ePropertyStopDisassemblyDisplay,
148254721Semaste    ePropertyStopLineCountAfter,
149254721Semaste    ePropertyStopLineCountBefore,
150254721Semaste    ePropertyTerminalWidth,
151254721Semaste    ePropertyThreadFormat,
152254721Semaste    ePropertyUseExternalEditor,
153254721Semaste    ePropertyUseColor,
154263363Semaste    ePropertyAutoOneLineSummaries
155254721Semaste};
156254721Semaste
157263367SemasteDebugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
158254721Semaste
159254721SemasteError
160254721SemasteDebugger::SetPropertyValue (const ExecutionContext *exe_ctx,
161254721Semaste                            VarSetOperationType op,
162254721Semaste                            const char *property_path,
163254721Semaste                            const char *value)
164254721Semaste{
165254721Semaste    bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
166254721Semaste    TargetSP target_sp;
167254721Semaste    LoadScriptFromSymFile load_script_old_value;
168254721Semaste    if (is_load_script && exe_ctx->GetTargetSP())
169254721Semaste    {
170254721Semaste        target_sp = exe_ctx->GetTargetSP();
171254721Semaste        load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
172254721Semaste    }
173254721Semaste    Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
174254721Semaste    if (error.Success())
175254721Semaste    {
176254721Semaste        // FIXME it would be nice to have "on-change" callbacks for properties
177254721Semaste        if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
178254721Semaste        {
179254721Semaste            const char *new_prompt = GetPrompt();
180254721Semaste            std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
181254721Semaste            if (str.length())
182254721Semaste                new_prompt = str.c_str();
183269024Semaste            GetCommandInterpreter().UpdatePrompt(new_prompt);
184254721Semaste            EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
185254721Semaste            GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
186254721Semaste        }
187254721Semaste        else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
188254721Semaste        {
189254721Semaste			// use-color changed. Ping the prompt so it can reset the ansi terminal codes.
190254721Semaste            SetPrompt (GetPrompt());
191254721Semaste        }
192254721Semaste        else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
193254721Semaste        {
194254721Semaste            if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
195254721Semaste            {
196254721Semaste                std::list<Error> errors;
197254721Semaste                StreamString feedback_stream;
198254721Semaste                if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
199254721Semaste                {
200269024Semaste                    StreamFileSP stream_sp (GetErrorFile());
201269024Semaste                    if (stream_sp)
202254721Semaste                    {
203269024Semaste                        for (auto error : errors)
204269024Semaste                        {
205269024Semaste                            stream_sp->Printf("%s\n",error.AsCString());
206269024Semaste                        }
207269024Semaste                        if (feedback_stream.GetSize())
208269024Semaste                            stream_sp->Printf("%s",feedback_stream.GetData());
209254721Semaste                    }
210254721Semaste                }
211254721Semaste            }
212254721Semaste        }
213254721Semaste    }
214254721Semaste    return error;
215254721Semaste}
216254721Semaste
217254721Semastebool
218254721SemasteDebugger::GetAutoConfirm () const
219254721Semaste{
220254721Semaste    const uint32_t idx = ePropertyAutoConfirm;
221254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
222254721Semaste}
223254721Semaste
224254721Semasteconst char *
225254721SemasteDebugger::GetFrameFormat() const
226254721Semaste{
227254721Semaste    const uint32_t idx = ePropertyFrameFormat;
228254721Semaste    return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
229254721Semaste}
230254721Semaste
231254721Semastebool
232254721SemasteDebugger::GetNotifyVoid () const
233254721Semaste{
234254721Semaste    const uint32_t idx = ePropertyNotiftVoid;
235254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
236254721Semaste}
237254721Semaste
238254721Semasteconst char *
239254721SemasteDebugger::GetPrompt() const
240254721Semaste{
241254721Semaste    const uint32_t idx = ePropertyPrompt;
242254721Semaste    return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
243254721Semaste}
244254721Semaste
245254721Semastevoid
246254721SemasteDebugger::SetPrompt(const char *p)
247254721Semaste{
248254721Semaste    const uint32_t idx = ePropertyPrompt;
249254721Semaste    m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
250254721Semaste    const char *new_prompt = GetPrompt();
251254721Semaste    std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
252254721Semaste    if (str.length())
253254721Semaste        new_prompt = str.c_str();
254269024Semaste    GetCommandInterpreter().UpdatePrompt(new_prompt);
255254721Semaste}
256254721Semaste
257254721Semasteconst char *
258254721SemasteDebugger::GetThreadFormat() const
259254721Semaste{
260254721Semaste    const uint32_t idx = ePropertyThreadFormat;
261254721Semaste    return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
262254721Semaste}
263254721Semaste
264254721Semastelldb::ScriptLanguage
265254721SemasteDebugger::GetScriptLanguage() const
266254721Semaste{
267254721Semaste    const uint32_t idx = ePropertyScriptLanguage;
268254721Semaste    return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
269254721Semaste}
270254721Semaste
271254721Semastebool
272254721SemasteDebugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
273254721Semaste{
274254721Semaste    const uint32_t idx = ePropertyScriptLanguage;
275254721Semaste    return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
276254721Semaste}
277254721Semaste
278254721Semasteuint32_t
279254721SemasteDebugger::GetTerminalWidth () const
280254721Semaste{
281254721Semaste    const uint32_t idx = ePropertyTerminalWidth;
282254721Semaste    return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
283254721Semaste}
284254721Semaste
285254721Semastebool
286254721SemasteDebugger::SetTerminalWidth (uint32_t term_width)
287254721Semaste{
288254721Semaste    const uint32_t idx = ePropertyTerminalWidth;
289254721Semaste    return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
290254721Semaste}
291254721Semaste
292254721Semastebool
293254721SemasteDebugger::GetUseExternalEditor () const
294254721Semaste{
295254721Semaste    const uint32_t idx = ePropertyUseExternalEditor;
296254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
297254721Semaste}
298254721Semaste
299254721Semastebool
300254721SemasteDebugger::SetUseExternalEditor (bool b)
301254721Semaste{
302254721Semaste    const uint32_t idx = ePropertyUseExternalEditor;
303254721Semaste    return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
304254721Semaste}
305254721Semaste
306254721Semastebool
307254721SemasteDebugger::GetUseColor () const
308254721Semaste{
309254721Semaste    const uint32_t idx = ePropertyUseColor;
310254721Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
311254721Semaste}
312254721Semaste
313254721Semastebool
314254721SemasteDebugger::SetUseColor (bool b)
315254721Semaste{
316254721Semaste    const uint32_t idx = ePropertyUseColor;
317254721Semaste    bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
318254721Semaste    SetPrompt (GetPrompt());
319254721Semaste    return ret;
320254721Semaste}
321254721Semaste
322254721Semasteuint32_t
323254721SemasteDebugger::GetStopSourceLineCount (bool before) const
324254721Semaste{
325254721Semaste    const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
326254721Semaste    return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
327254721Semaste}
328254721Semaste
329254721SemasteDebugger::StopDisassemblyType
330254721SemasteDebugger::GetStopDisassemblyDisplay () const
331254721Semaste{
332254721Semaste    const uint32_t idx = ePropertyStopDisassemblyDisplay;
333254721Semaste    return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
334254721Semaste}
335254721Semaste
336254721Semasteuint32_t
337254721SemasteDebugger::GetDisassemblyLineCount () const
338254721Semaste{
339254721Semaste    const uint32_t idx = ePropertyStopDisassemblyCount;
340254721Semaste    return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
341254721Semaste}
342254721Semaste
343263363Semastebool
344263363SemasteDebugger::GetAutoOneLineSummaries () const
345263363Semaste{
346263363Semaste    const uint32_t idx = ePropertyAutoOneLineSummaries;
347263363Semaste    return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
348263363Semaste
349263363Semaste}
350263363Semaste
351254721Semaste#pragma mark Debugger
352254721Semaste
353254721Semaste//const DebuggerPropertiesSP &
354254721Semaste//Debugger::GetSettings() const
355254721Semaste//{
356254721Semaste//    return m_properties_sp;
357254721Semaste//}
358254721Semaste//
359254721Semaste
360254721Semasteint
361254721SemasteDebugger::TestDebuggerRefCount ()
362254721Semaste{
363254721Semaste    return g_shared_debugger_refcount;
364254721Semaste}
365254721Semaste
366254721Semastevoid
367263367SemasteDebugger::Initialize (LoadPluginCallbackType load_plugin_callback)
368254721Semaste{
369263367Semaste    g_load_plugin_callback = load_plugin_callback;
370254721Semaste    if (g_shared_debugger_refcount++ == 0)
371254721Semaste        lldb_private::Initialize();
372254721Semaste}
373254721Semaste
374254721Semastevoid
375254721SemasteDebugger::Terminate ()
376254721Semaste{
377254721Semaste    if (g_shared_debugger_refcount > 0)
378254721Semaste    {
379254721Semaste        g_shared_debugger_refcount--;
380254721Semaste        if (g_shared_debugger_refcount == 0)
381254721Semaste        {
382254721Semaste            lldb_private::WillTerminate();
383254721Semaste            lldb_private::Terminate();
384254721Semaste
385254721Semaste            // Clear our master list of debugger objects
386254721Semaste            Mutex::Locker locker (GetDebuggerListMutex ());
387254721Semaste            GetDebuggerList().clear();
388254721Semaste        }
389254721Semaste    }
390254721Semaste}
391254721Semaste
392254721Semastevoid
393254721SemasteDebugger::SettingsInitialize ()
394254721Semaste{
395254721Semaste    Target::SettingsInitialize ();
396254721Semaste}
397254721Semaste
398254721Semastevoid
399254721SemasteDebugger::SettingsTerminate ()
400254721Semaste{
401254721Semaste    Target::SettingsTerminate ();
402254721Semaste}
403254721Semaste
404254721Semastebool
405254721SemasteDebugger::LoadPlugin (const FileSpec& spec, Error& error)
406254721Semaste{
407263367Semaste    if (g_load_plugin_callback)
408254721Semaste    {
409263367Semaste        lldb::DynamicLibrarySP dynlib_sp = g_load_plugin_callback (shared_from_this(), spec, error);
410263367Semaste        if (dynlib_sp)
411263367Semaste        {
412263367Semaste            m_loaded_plugins.push_back(dynlib_sp);
413263367Semaste            return true;
414263367Semaste        }
415254721Semaste    }
416263367Semaste    else
417254721Semaste    {
418263367Semaste        // The g_load_plugin_callback is registered in SBDebugger::Initialize()
419263367Semaste        // and if the public API layer isn't available (code is linking against
420263367Semaste        // all of the internal LLDB static libraries), then we can't load plugins
421263367Semaste        error.SetErrorString("Public API layer is not available");
422254721Semaste    }
423254721Semaste    return false;
424254721Semaste}
425254721Semaste
426254721Semastestatic FileSpec::EnumerateDirectoryResult
427254721SemasteLoadPluginCallback
428254721Semaste(
429254721Semaste void *baton,
430254721Semaste FileSpec::FileType file_type,
431254721Semaste const FileSpec &file_spec
432254721Semaste )
433254721Semaste{
434254721Semaste    Error error;
435254721Semaste
436254721Semaste    static ConstString g_dylibext("dylib");
437254721Semaste    static ConstString g_solibext("so");
438254721Semaste
439254721Semaste    if (!baton)
440254721Semaste        return FileSpec::eEnumerateDirectoryResultQuit;
441254721Semaste
442254721Semaste    Debugger *debugger = (Debugger*)baton;
443254721Semaste
444254721Semaste    // If we have a regular file, a symbolic link or unknown file type, try
445254721Semaste    // and process the file. We must handle unknown as sometimes the directory
446254721Semaste    // enumeration might be enumerating a file system that doesn't have correct
447254721Semaste    // file type information.
448254721Semaste    if (file_type == FileSpec::eFileTypeRegular         ||
449254721Semaste        file_type == FileSpec::eFileTypeSymbolicLink    ||
450254721Semaste        file_type == FileSpec::eFileTypeUnknown          )
451254721Semaste    {
452254721Semaste        FileSpec plugin_file_spec (file_spec);
453254721Semaste        plugin_file_spec.ResolvePath ();
454254721Semaste
455254721Semaste        if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
456254721Semaste            plugin_file_spec.GetFileNameExtension() != g_solibext)
457254721Semaste        {
458254721Semaste            return FileSpec::eEnumerateDirectoryResultNext;
459254721Semaste        }
460254721Semaste
461254721Semaste        Error plugin_load_error;
462254721Semaste        debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
463254721Semaste
464254721Semaste        return FileSpec::eEnumerateDirectoryResultNext;
465254721Semaste    }
466254721Semaste
467254721Semaste    else if (file_type == FileSpec::eFileTypeUnknown     ||
468254721Semaste        file_type == FileSpec::eFileTypeDirectory   ||
469254721Semaste        file_type == FileSpec::eFileTypeSymbolicLink )
470254721Semaste    {
471254721Semaste        // Try and recurse into anything that a directory or symbolic link.
472254721Semaste        // We must also do this for unknown as sometimes the directory enumeration
473254721Semaste        // might be enurating a file system that doesn't have correct file type
474254721Semaste        // information.
475254721Semaste        return FileSpec::eEnumerateDirectoryResultEnter;
476254721Semaste    }
477254721Semaste
478254721Semaste    return FileSpec::eEnumerateDirectoryResultNext;
479254721Semaste}
480254721Semaste
481254721Semastevoid
482254721SemasteDebugger::InstanceInitialize ()
483254721Semaste{
484254721Semaste    FileSpec dir_spec;
485254721Semaste    const bool find_directories = true;
486254721Semaste    const bool find_files = true;
487254721Semaste    const bool find_other = true;
488254721Semaste    char dir_path[PATH_MAX];
489254721Semaste    if (Host::GetLLDBPath (ePathTypeLLDBSystemPlugins, dir_spec))
490254721Semaste    {
491254721Semaste        if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
492254721Semaste        {
493254721Semaste            FileSpec::EnumerateDirectory (dir_path,
494254721Semaste                                          find_directories,
495254721Semaste                                          find_files,
496254721Semaste                                          find_other,
497254721Semaste                                          LoadPluginCallback,
498254721Semaste                                          this);
499254721Semaste        }
500254721Semaste    }
501254721Semaste
502254721Semaste    if (Host::GetLLDBPath (ePathTypeLLDBUserPlugins, dir_spec))
503254721Semaste    {
504254721Semaste        if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
505254721Semaste        {
506254721Semaste            FileSpec::EnumerateDirectory (dir_path,
507254721Semaste                                          find_directories,
508254721Semaste                                          find_files,
509254721Semaste                                          find_other,
510254721Semaste                                          LoadPluginCallback,
511254721Semaste                                          this);
512254721Semaste        }
513254721Semaste    }
514254721Semaste
515254721Semaste    PluginManager::DebuggerInitialize (*this);
516254721Semaste}
517254721Semaste
518254721SemasteDebuggerSP
519254721SemasteDebugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
520254721Semaste{
521254721Semaste    DebuggerSP debugger_sp (new Debugger(log_callback, baton));
522254721Semaste    if (g_shared_debugger_refcount > 0)
523254721Semaste    {
524254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
525254721Semaste        GetDebuggerList().push_back(debugger_sp);
526254721Semaste    }
527254721Semaste    debugger_sp->InstanceInitialize ();
528254721Semaste    return debugger_sp;
529254721Semaste}
530254721Semaste
531254721Semastevoid
532254721SemasteDebugger::Destroy (DebuggerSP &debugger_sp)
533254721Semaste{
534254721Semaste    if (debugger_sp.get() == NULL)
535254721Semaste        return;
536254721Semaste
537254721Semaste    debugger_sp->Clear();
538254721Semaste
539254721Semaste    if (g_shared_debugger_refcount > 0)
540254721Semaste    {
541254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
542254721Semaste        DebuggerList &debugger_list = GetDebuggerList ();
543254721Semaste        DebuggerList::iterator pos, end = debugger_list.end();
544254721Semaste        for (pos = debugger_list.begin (); pos != end; ++pos)
545254721Semaste        {
546254721Semaste            if ((*pos).get() == debugger_sp.get())
547254721Semaste            {
548254721Semaste                debugger_list.erase (pos);
549254721Semaste                return;
550254721Semaste            }
551254721Semaste        }
552254721Semaste    }
553254721Semaste}
554254721Semaste
555254721SemasteDebuggerSP
556254721SemasteDebugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
557254721Semaste{
558254721Semaste    DebuggerSP debugger_sp;
559254721Semaste    if (g_shared_debugger_refcount > 0)
560254721Semaste    {
561254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
562254721Semaste        DebuggerList &debugger_list = GetDebuggerList();
563254721Semaste        DebuggerList::iterator pos, end = debugger_list.end();
564254721Semaste
565254721Semaste        for (pos = debugger_list.begin(); pos != end; ++pos)
566254721Semaste        {
567254721Semaste            if ((*pos).get()->m_instance_name == instance_name)
568254721Semaste            {
569254721Semaste                debugger_sp = *pos;
570254721Semaste                break;
571254721Semaste            }
572254721Semaste        }
573254721Semaste    }
574254721Semaste    return debugger_sp;
575254721Semaste}
576254721Semaste
577254721SemasteTargetSP
578254721SemasteDebugger::FindTargetWithProcessID (lldb::pid_t pid)
579254721Semaste{
580254721Semaste    TargetSP target_sp;
581254721Semaste    if (g_shared_debugger_refcount > 0)
582254721Semaste    {
583254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
584254721Semaste        DebuggerList &debugger_list = GetDebuggerList();
585254721Semaste        DebuggerList::iterator pos, end = debugger_list.end();
586254721Semaste        for (pos = debugger_list.begin(); pos != end; ++pos)
587254721Semaste        {
588254721Semaste            target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
589254721Semaste            if (target_sp)
590254721Semaste                break;
591254721Semaste        }
592254721Semaste    }
593254721Semaste    return target_sp;
594254721Semaste}
595254721Semaste
596254721SemasteTargetSP
597254721SemasteDebugger::FindTargetWithProcess (Process *process)
598254721Semaste{
599254721Semaste    TargetSP target_sp;
600254721Semaste    if (g_shared_debugger_refcount > 0)
601254721Semaste    {
602254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
603254721Semaste        DebuggerList &debugger_list = GetDebuggerList();
604254721Semaste        DebuggerList::iterator pos, end = debugger_list.end();
605254721Semaste        for (pos = debugger_list.begin(); pos != end; ++pos)
606254721Semaste        {
607254721Semaste            target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
608254721Semaste            if (target_sp)
609254721Semaste                break;
610254721Semaste        }
611254721Semaste    }
612254721Semaste    return target_sp;
613254721Semaste}
614254721Semaste
615254721SemasteDebugger::Debugger (lldb::LogOutputCallback log_callback, void *baton) :
616254721Semaste    UserID (g_unique_id++),
617254721Semaste    Properties(OptionValuePropertiesSP(new OptionValueProperties())),
618269024Semaste    m_input_file_sp (new StreamFile (stdin, false)),
619269024Semaste    m_output_file_sp (new StreamFile (stdout, false)),
620269024Semaste    m_error_file_sp (new StreamFile (stderr, false)),
621254721Semaste    m_terminal_state (),
622254721Semaste    m_target_list (*this),
623254721Semaste    m_platform_list (),
624254721Semaste    m_listener ("lldb.Debugger"),
625254721Semaste    m_source_manager_ap(),
626254721Semaste    m_source_file_cache(),
627254721Semaste    m_command_interpreter_ap (new CommandInterpreter (*this, eScriptLanguageDefault, false)),
628254721Semaste    m_input_reader_stack (),
629269024Semaste    m_instance_name (),
630269024Semaste    m_loaded_plugins (),
631269024Semaste    m_event_handler_thread (LLDB_INVALID_HOST_THREAD),
632269024Semaste    m_io_handler_thread (LLDB_INVALID_HOST_THREAD),
633269024Semaste    m_event_handler_thread_alive(false)
634254721Semaste{
635254721Semaste    char instance_cstr[256];
636254721Semaste    snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
637254721Semaste    m_instance_name.SetCString(instance_cstr);
638254721Semaste    if (log_callback)
639254721Semaste        m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
640254721Semaste    m_command_interpreter_ap->Initialize ();
641254721Semaste    // Always add our default platform to the platform list
642254721Semaste    PlatformSP default_platform_sp (Platform::GetDefaultPlatform());
643254721Semaste    assert (default_platform_sp.get());
644254721Semaste    m_platform_list.Append (default_platform_sp, true);
645254721Semaste
646254721Semaste    m_collection_sp->Initialize (g_properties);
647254721Semaste    m_collection_sp->AppendProperty (ConstString("target"),
648254721Semaste                                     ConstString("Settings specify to debugging targets."),
649254721Semaste                                     true,
650254721Semaste                                     Target::GetGlobalProperties()->GetValueProperties());
651254721Semaste    if (m_command_interpreter_ap.get())
652254721Semaste    {
653254721Semaste        m_collection_sp->AppendProperty (ConstString("interpreter"),
654254721Semaste                                         ConstString("Settings specify to the debugger's command interpreter."),
655254721Semaste                                         true,
656254721Semaste                                         m_command_interpreter_ap->GetValueProperties());
657254721Semaste    }
658254721Semaste    OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
659254721Semaste    term_width->SetMinimumValue(10);
660254721Semaste    term_width->SetMaximumValue(1024);
661254721Semaste
662254721Semaste    // Turn off use-color if this is a dumb terminal.
663254721Semaste    const char *term = getenv ("TERM");
664254721Semaste    if (term && !strcmp (term, "dumb"))
665254721Semaste        SetUseColor (false);
666254721Semaste}
667254721Semaste
668254721SemasteDebugger::~Debugger ()
669254721Semaste{
670254721Semaste    Clear();
671254721Semaste}
672254721Semaste
673254721Semastevoid
674254721SemasteDebugger::Clear()
675254721Semaste{
676269024Semaste    ClearIOHandlers();
677269024Semaste    StopIOHandlerThread();
678269024Semaste    StopEventHandlerThread();
679254721Semaste    m_listener.Clear();
680254721Semaste    int num_targets = m_target_list.GetNumTargets();
681254721Semaste    for (int i = 0; i < num_targets; i++)
682254721Semaste    {
683254721Semaste        TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
684254721Semaste        if (target_sp)
685254721Semaste        {
686254721Semaste            ProcessSP process_sp (target_sp->GetProcessSP());
687254721Semaste            if (process_sp)
688254721Semaste                process_sp->Finalize();
689254721Semaste            target_sp->Destroy();
690254721Semaste        }
691254721Semaste    }
692254721Semaste    BroadcasterManager::Clear ();
693254721Semaste
694254721Semaste    // Close the input file _before_ we close the input read communications class
695254721Semaste    // as it does NOT own the input file, our m_input_file does.
696254721Semaste    m_terminal_state.Clear();
697269024Semaste    if (m_input_file_sp)
698269024Semaste        m_input_file_sp->GetFile().Close ();
699254721Semaste}
700254721Semaste
701254721Semastebool
702254721SemasteDebugger::GetCloseInputOnEOF () const
703254721Semaste{
704269024Semaste//    return m_input_comm.GetCloseOnEOF();
705269024Semaste    return false;
706254721Semaste}
707254721Semaste
708254721Semastevoid
709254721SemasteDebugger::SetCloseInputOnEOF (bool b)
710254721Semaste{
711269024Semaste//    m_input_comm.SetCloseOnEOF(b);
712254721Semaste}
713254721Semaste
714254721Semastebool
715254721SemasteDebugger::GetAsyncExecution ()
716254721Semaste{
717254721Semaste    return !m_command_interpreter_ap->GetSynchronous();
718254721Semaste}
719254721Semaste
720254721Semastevoid
721254721SemasteDebugger::SetAsyncExecution (bool async_execution)
722254721Semaste{
723254721Semaste    m_command_interpreter_ap->SetSynchronous (!async_execution);
724254721Semaste}
725254721Semaste
726254721Semaste
727254721Semastevoid
728254721SemasteDebugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
729254721Semaste{
730269024Semaste    if (m_input_file_sp)
731269024Semaste        m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
732269024Semaste    else
733269024Semaste        m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
734269024Semaste
735269024Semaste    File &in_file = m_input_file_sp->GetFile();
736254721Semaste    if (in_file.IsValid() == false)
737254721Semaste        in_file.SetStream (stdin, true);
738254721Semaste
739254721Semaste    // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
740254721Semaste    SaveInputTerminalState ();
741254721Semaste}
742254721Semaste
743254721Semastevoid
744254721SemasteDebugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
745254721Semaste{
746269024Semaste    if (m_output_file_sp)
747269024Semaste        m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
748269024Semaste    else
749269024Semaste        m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
750269024Semaste
751269024Semaste    File &out_file = m_output_file_sp->GetFile();
752254721Semaste    if (out_file.IsValid() == false)
753254721Semaste        out_file.SetStream (stdout, false);
754254721Semaste
755254721Semaste    // do not create the ScriptInterpreter just for setting the output file handle
756254721Semaste    // as the constructor will know how to do the right thing on its own
757254721Semaste    const bool can_create = false;
758254721Semaste    ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
759254721Semaste    if (script_interpreter)
760254721Semaste        script_interpreter->ResetOutputFileHandle (fh);
761254721Semaste}
762254721Semaste
763254721Semastevoid
764254721SemasteDebugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
765254721Semaste{
766269024Semaste    if (m_error_file_sp)
767269024Semaste        m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
768269024Semaste    else
769269024Semaste        m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
770269024Semaste
771269024Semaste    File &err_file = m_error_file_sp->GetFile();
772254721Semaste    if (err_file.IsValid() == false)
773254721Semaste        err_file.SetStream (stderr, false);
774254721Semaste}
775254721Semaste
776254721Semastevoid
777254721SemasteDebugger::SaveInputTerminalState ()
778254721Semaste{
779269024Semaste    if (m_input_file_sp)
780269024Semaste    {
781269024Semaste        File &in_file = m_input_file_sp->GetFile();
782269024Semaste        if (in_file.GetDescriptor() != File::kInvalidDescriptor)
783269024Semaste            m_terminal_state.Save(in_file.GetDescriptor(), true);
784269024Semaste    }
785254721Semaste}
786254721Semaste
787254721Semastevoid
788254721SemasteDebugger::RestoreInputTerminalState ()
789254721Semaste{
790254721Semaste    m_terminal_state.Restore();
791254721Semaste}
792254721Semaste
793254721SemasteExecutionContext
794254721SemasteDebugger::GetSelectedExecutionContext ()
795254721Semaste{
796254721Semaste    ExecutionContext exe_ctx;
797254721Semaste    TargetSP target_sp(GetSelectedTarget());
798254721Semaste    exe_ctx.SetTargetSP (target_sp);
799254721Semaste
800254721Semaste    if (target_sp)
801254721Semaste    {
802254721Semaste        ProcessSP process_sp (target_sp->GetProcessSP());
803254721Semaste        exe_ctx.SetProcessSP (process_sp);
804254721Semaste        if (process_sp && process_sp->IsRunning() == false)
805254721Semaste        {
806254721Semaste            ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
807254721Semaste            if (thread_sp)
808254721Semaste            {
809254721Semaste                exe_ctx.SetThreadSP (thread_sp);
810254721Semaste                exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
811254721Semaste                if (exe_ctx.GetFramePtr() == NULL)
812254721Semaste                    exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
813254721Semaste            }
814254721Semaste        }
815254721Semaste    }
816254721Semaste    return exe_ctx;
817254721Semaste}
818254721Semaste
819254721Semastevoid
820254721SemasteDebugger::DispatchInputInterrupt ()
821254721Semaste{
822269024Semaste    Mutex::Locker locker (m_input_reader_stack.GetMutex());
823269024Semaste    IOHandlerSP reader_sp (m_input_reader_stack.Top());
824254721Semaste    if (reader_sp)
825269024Semaste        reader_sp->Interrupt();
826254721Semaste}
827254721Semaste
828254721Semastevoid
829254721SemasteDebugger::DispatchInputEndOfFile ()
830254721Semaste{
831269024Semaste    Mutex::Locker locker (m_input_reader_stack.GetMutex());
832269024Semaste    IOHandlerSP reader_sp (m_input_reader_stack.Top());
833254721Semaste    if (reader_sp)
834269024Semaste        reader_sp->GotEOF();
835254721Semaste}
836254721Semaste
837254721Semastevoid
838269024SemasteDebugger::ClearIOHandlers ()
839254721Semaste{
840254721Semaste    // The bottom input reader should be the main debugger input reader.  We do not want to close that one here.
841269024Semaste    Mutex::Locker locker (m_input_reader_stack.GetMutex());
842254721Semaste    while (m_input_reader_stack.GetSize() > 1)
843254721Semaste    {
844269024Semaste        IOHandlerSP reader_sp (m_input_reader_stack.Top());
845254721Semaste        if (reader_sp)
846254721Semaste        {
847269024Semaste            m_input_reader_stack.Pop();
848269024Semaste            reader_sp->SetIsDone(true);
849269024Semaste            reader_sp->Cancel();
850254721Semaste        }
851254721Semaste    }
852254721Semaste}
853254721Semaste
854254721Semastevoid
855269024SemasteDebugger::ExecuteIOHanders()
856254721Semaste{
857269024Semaste
858269024Semaste    while (1)
859269024Semaste    {
860269024Semaste        IOHandlerSP reader_sp(m_input_reader_stack.Top());
861269024Semaste        if (!reader_sp)
862269024Semaste            break;
863254721Semaste
864269024Semaste        reader_sp->Activate();
865269024Semaste        reader_sp->Run();
866269024Semaste        reader_sp->Deactivate();
867269024Semaste
868269024Semaste        // Remove all input readers that are done from the top of the stack
869269024Semaste        while (1)
870269024Semaste        {
871269024Semaste            IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
872269024Semaste            if (top_reader_sp && top_reader_sp->GetIsDone())
873269024Semaste                m_input_reader_stack.Pop();
874269024Semaste            else
875269024Semaste                break;
876269024Semaste        }
877254721Semaste    }
878269024Semaste    ClearIOHandlers();
879254721Semaste}
880254721Semaste
881254721Semastebool
882269024SemasteDebugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
883254721Semaste{
884269024Semaste    return m_input_reader_stack.IsTop (reader_sp);
885269024Semaste}
886254721Semaste
887269024Semaste
888269024SemasteConstString
889269024SemasteDebugger::GetTopIOHandlerControlSequence(char ch)
890269024Semaste{
891269024Semaste    return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
892254721Semaste}
893254721Semaste
894254721Semastevoid
895269024SemasteDebugger::RunIOHandler (const IOHandlerSP& reader_sp)
896254721Semaste{
897269024Semaste    Mutex::Locker locker (m_input_reader_stack.GetMutex());
898269024Semaste    PushIOHandler (reader_sp);
899269024Semaste    reader_sp->Activate();
900269024Semaste    reader_sp->Run();
901269024Semaste    PopIOHandler (reader_sp);
902269024Semaste}
903254721Semaste
904269024Semastevoid
905269024SemasteDebugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
906269024Semaste{
907269024Semaste    // Before an IOHandler runs, it must have in/out/err streams.
908269024Semaste    // This function is called when one ore more of the streams
909269024Semaste    // are NULL. We use the top input reader's in/out/err streams,
910269024Semaste    // or fall back to the debugger file handles, or we fall back
911269024Semaste    // onto stdin/stdout/stderr as a last resort.
912269024Semaste
913269024Semaste    Mutex::Locker locker (m_input_reader_stack.GetMutex());
914269024Semaste    IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
915269024Semaste    // If no STDIN has been set, then set it appropriately
916269024Semaste    if (!in)
917254721Semaste    {
918269024Semaste        if (top_reader_sp)
919269024Semaste            in = top_reader_sp->GetInputStreamFile();
920254721Semaste        else
921269024Semaste            in = GetInputFile();
922269024Semaste
923269024Semaste        // If there is nothing, use stdin
924269024Semaste        if (!in)
925269024Semaste            in = StreamFileSP(new StreamFile(stdin, false));
926254721Semaste    }
927269024Semaste    // If no STDOUT has been set, then set it appropriately
928269024Semaste    if (!out)
929269024Semaste    {
930269024Semaste        if (top_reader_sp)
931269024Semaste            out = top_reader_sp->GetOutputStreamFile();
932269024Semaste        else
933269024Semaste            out = GetOutputFile();
934269024Semaste
935269024Semaste        // If there is nothing, use stdout
936269024Semaste        if (!out)
937269024Semaste            out = StreamFileSP(new StreamFile(stdout, false));
938269024Semaste    }
939269024Semaste    // If no STDERR has been set, then set it appropriately
940269024Semaste    if (!err)
941269024Semaste    {
942269024Semaste        if (top_reader_sp)
943269024Semaste            err = top_reader_sp->GetErrorStreamFile();
944269024Semaste        else
945269024Semaste            err = GetErrorFile();
946269024Semaste
947269024Semaste        // If there is nothing, use stderr
948269024Semaste        if (!err)
949269024Semaste            err = StreamFileSP(new StreamFile(stdout, false));
950269024Semaste
951269024Semaste    }
952254721Semaste}
953254721Semaste
954254721Semastevoid
955269024SemasteDebugger::PushIOHandler (const IOHandlerSP& reader_sp)
956254721Semaste{
957254721Semaste    if (!reader_sp)
958254721Semaste        return;
959254721Semaste
960269024Semaste    // Got the current top input reader...
961269024Semaste    IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
962254721Semaste
963269024Semaste    // Push our new input reader
964269024Semaste    m_input_reader_stack.Push (reader_sp);
965269024Semaste
966269024Semaste    // Interrupt the top input reader to it will exit its Run() function
967269024Semaste    // and let this new input reader take over
968254721Semaste    if (top_reader_sp)
969269024Semaste        top_reader_sp->Deactivate();
970254721Semaste}
971254721Semaste
972254721Semastebool
973269024SemasteDebugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
974254721Semaste{
975254721Semaste    bool result = false;
976269024Semaste
977269024Semaste    Mutex::Locker locker (m_input_reader_stack.GetMutex());
978254721Semaste
979254721Semaste    // The reader on the stop of the stack is done, so let the next
980254721Semaste    // read on the stack referesh its prompt and if there is one...
981254721Semaste    if (!m_input_reader_stack.IsEmpty())
982254721Semaste    {
983269024Semaste        IOHandlerSP reader_sp(m_input_reader_stack.Top());
984254721Semaste
985254721Semaste        if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
986254721Semaste        {
987269024Semaste            reader_sp->Deactivate();
988254721Semaste            m_input_reader_stack.Pop ();
989269024Semaste
990269024Semaste            reader_sp = m_input_reader_stack.Top();
991269024Semaste            if (reader_sp)
992269024Semaste                reader_sp->Activate();
993269024Semaste
994254721Semaste            result = true;
995254721Semaste        }
996254721Semaste    }
997254721Semaste    return result;
998254721Semaste}
999254721Semaste
1000254721Semastebool
1001269024SemasteDebugger::HideTopIOHandler()
1002254721Semaste{
1003269024Semaste    Mutex::Locker locker;
1004269024Semaste
1005269024Semaste    if (locker.TryLock(m_input_reader_stack.GetMutex()))
1006254721Semaste    {
1007269024Semaste        IOHandlerSP reader_sp(m_input_reader_stack.Top());
1008269024Semaste        if (reader_sp)
1009269024Semaste            reader_sp->Hide();
1010269024Semaste        return true;
1011254721Semaste    }
1012269024Semaste    return false;
1013254721Semaste}
1014254721Semaste
1015254721Semastevoid
1016269024SemasteDebugger::RefreshTopIOHandler()
1017254721Semaste{
1018269024Semaste    IOHandlerSP reader_sp(m_input_reader_stack.Top());
1019269024Semaste    if (reader_sp)
1020269024Semaste        reader_sp->Refresh();
1021269024Semaste}
1022254721Semaste
1023254721Semaste
1024254721SemasteStreamSP
1025254721SemasteDebugger::GetAsyncOutputStream ()
1026254721Semaste{
1027254721Semaste    return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1028254721Semaste                                               CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1029254721Semaste}
1030254721Semaste
1031254721SemasteStreamSP
1032254721SemasteDebugger::GetAsyncErrorStream ()
1033254721Semaste{
1034254721Semaste    return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1035254721Semaste                                               CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1036254721Semaste}
1037254721Semaste
1038254721Semastesize_t
1039254721SemasteDebugger::GetNumDebuggers()
1040254721Semaste{
1041254721Semaste    if (g_shared_debugger_refcount > 0)
1042254721Semaste    {
1043254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
1044254721Semaste        return GetDebuggerList().size();
1045254721Semaste    }
1046254721Semaste    return 0;
1047254721Semaste}
1048254721Semaste
1049254721Semastelldb::DebuggerSP
1050254721SemasteDebugger::GetDebuggerAtIndex (size_t index)
1051254721Semaste{
1052254721Semaste    DebuggerSP debugger_sp;
1053254721Semaste
1054254721Semaste    if (g_shared_debugger_refcount > 0)
1055254721Semaste    {
1056254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
1057254721Semaste        DebuggerList &debugger_list = GetDebuggerList();
1058254721Semaste
1059254721Semaste        if (index < debugger_list.size())
1060254721Semaste            debugger_sp = debugger_list[index];
1061254721Semaste    }
1062254721Semaste
1063254721Semaste    return debugger_sp;
1064254721Semaste}
1065254721Semaste
1066254721SemasteDebuggerSP
1067254721SemasteDebugger::FindDebuggerWithID (lldb::user_id_t id)
1068254721Semaste{
1069254721Semaste    DebuggerSP debugger_sp;
1070254721Semaste
1071254721Semaste    if (g_shared_debugger_refcount > 0)
1072254721Semaste    {
1073254721Semaste        Mutex::Locker locker (GetDebuggerListMutex ());
1074254721Semaste        DebuggerList &debugger_list = GetDebuggerList();
1075254721Semaste        DebuggerList::iterator pos, end = debugger_list.end();
1076254721Semaste        for (pos = debugger_list.begin(); pos != end; ++pos)
1077254721Semaste        {
1078254721Semaste            if ((*pos).get()->GetID() == id)
1079254721Semaste            {
1080254721Semaste                debugger_sp = *pos;
1081254721Semaste                break;
1082254721Semaste            }
1083254721Semaste        }
1084254721Semaste    }
1085254721Semaste    return debugger_sp;
1086254721Semaste}
1087254721Semaste
1088254721Semastestatic void
1089254721SemasteTestPromptFormats (StackFrame *frame)
1090254721Semaste{
1091254721Semaste    if (frame == NULL)
1092254721Semaste        return;
1093254721Semaste
1094254721Semaste    StreamString s;
1095254721Semaste    const char *prompt_format =
1096254721Semaste    "{addr = '${addr}'\n}"
1097254721Semaste    "{process.id = '${process.id}'\n}"
1098254721Semaste    "{process.name = '${process.name}'\n}"
1099254721Semaste    "{process.file.basename = '${process.file.basename}'\n}"
1100254721Semaste    "{process.file.fullpath = '${process.file.fullpath}'\n}"
1101254721Semaste    "{thread.id = '${thread.id}'\n}"
1102254721Semaste    "{thread.index = '${thread.index}'\n}"
1103254721Semaste    "{thread.name = '${thread.name}'\n}"
1104254721Semaste    "{thread.queue = '${thread.queue}'\n}"
1105254721Semaste    "{thread.stop-reason = '${thread.stop-reason}'\n}"
1106254721Semaste    "{target.arch = '${target.arch}'\n}"
1107254721Semaste    "{module.file.basename = '${module.file.basename}'\n}"
1108254721Semaste    "{module.file.fullpath = '${module.file.fullpath}'\n}"
1109254721Semaste    "{file.basename = '${file.basename}'\n}"
1110254721Semaste    "{file.fullpath = '${file.fullpath}'\n}"
1111254721Semaste    "{frame.index = '${frame.index}'\n}"
1112254721Semaste    "{frame.pc = '${frame.pc}'\n}"
1113254721Semaste    "{frame.sp = '${frame.sp}'\n}"
1114254721Semaste    "{frame.fp = '${frame.fp}'\n}"
1115254721Semaste    "{frame.flags = '${frame.flags}'\n}"
1116254721Semaste    "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1117254721Semaste    "{frame.reg.rip = '${frame.reg.rip}'\n}"
1118254721Semaste    "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1119254721Semaste    "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1120254721Semaste    "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1121254721Semaste    "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1122254721Semaste    "{frame.reg.carp = '${frame.reg.carp}'\n}"
1123254721Semaste    "{function.id = '${function.id}'\n}"
1124254721Semaste    "{function.name = '${function.name}'\n}"
1125254721Semaste    "{function.name-with-args = '${function.name-with-args}'\n}"
1126254721Semaste    "{function.addr-offset = '${function.addr-offset}'\n}"
1127254721Semaste    "{function.line-offset = '${function.line-offset}'\n}"
1128254721Semaste    "{function.pc-offset = '${function.pc-offset}'\n}"
1129254721Semaste    "{line.file.basename = '${line.file.basename}'\n}"
1130254721Semaste    "{line.file.fullpath = '${line.file.fullpath}'\n}"
1131254721Semaste    "{line.number = '${line.number}'\n}"
1132254721Semaste    "{line.start-addr = '${line.start-addr}'\n}"
1133254721Semaste    "{line.end-addr = '${line.end-addr}'\n}"
1134254721Semaste;
1135254721Semaste
1136254721Semaste    SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1137254721Semaste    ExecutionContext exe_ctx;
1138254721Semaste    frame->CalculateExecutionContext(exe_ctx);
1139254721Semaste    if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1140254721Semaste    {
1141254721Semaste        printf("%s\n", s.GetData());
1142254721Semaste    }
1143254721Semaste    else
1144254721Semaste    {
1145254721Semaste        printf ("what we got: %s\n", s.GetData());
1146254721Semaste    }
1147254721Semaste}
1148254721Semaste
1149254721Semastestatic bool
1150254721SemasteScanFormatDescriptor (const char* var_name_begin,
1151254721Semaste                      const char* var_name_end,
1152254721Semaste                      const char** var_name_final,
1153254721Semaste                      const char** percent_position,
1154254721Semaste                      Format* custom_format,
1155254721Semaste                      ValueObject::ValueObjectRepresentationStyle* val_obj_display)
1156254721Semaste{
1157254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1158254721Semaste    *percent_position = ::strchr(var_name_begin,'%');
1159254721Semaste    if (!*percent_position || *percent_position > var_name_end)
1160254721Semaste    {
1161254721Semaste        if (log)
1162254721Semaste            log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
1163254721Semaste        *var_name_final = var_name_end;
1164254721Semaste    }
1165254721Semaste    else
1166254721Semaste    {
1167254721Semaste        *var_name_final = *percent_position;
1168254721Semaste        std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
1169254721Semaste        if (log)
1170254721Semaste            log->Printf("[ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
1171254721Semaste        if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
1172254721Semaste                                                  true,
1173254721Semaste                                                  *custom_format) )
1174254721Semaste        {
1175254721Semaste            if (log)
1176254721Semaste                log->Printf("[ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
1177254721Semaste
1178254721Semaste            switch (format_name.front())
1179254721Semaste            {
1180254721Semaste                case '@':             // if this is an @ sign, print ObjC description
1181254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1182254721Semaste                    break;
1183254721Semaste                case 'V': // if this is a V, print the value using the default format
1184254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1185254721Semaste                    break;
1186254721Semaste                case 'L': // if this is an L, print the location of the value
1187254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1188254721Semaste                    break;
1189254721Semaste                case 'S': // if this is an S, print the summary after all
1190254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1191254721Semaste                    break;
1192254721Semaste                case '#': // if this is a '#', print the number of children
1193254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1194254721Semaste                    break;
1195254721Semaste                case 'T': // if this is a 'T', print the type
1196254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1197254721Semaste                    break;
1198254721Semaste                case 'N': // if this is a 'N', print the name
1199254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleName;
1200254721Semaste                    break;
1201254721Semaste                case '>': // if this is a '>', print the name
1202254721Semaste                    *val_obj_display = ValueObject::eValueObjectRepresentationStyleExpressionPath;
1203254721Semaste                    break;
1204254721Semaste                default:
1205254721Semaste                    if (log)
1206254721Semaste                        log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
1207254721Semaste                    break;
1208254721Semaste            }
1209254721Semaste        }
1210254721Semaste        // a good custom format tells us to print the value using it
1211254721Semaste        else
1212254721Semaste        {
1213254721Semaste            if (log)
1214254721Semaste                log->Printf("[ScanFormatDescriptor] will display value for this VO");
1215254721Semaste            *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1216254721Semaste        }
1217254721Semaste    }
1218254721Semaste    if (log)
1219254721Semaste        log->Printf("[ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
1220254721Semaste                    *custom_format,
1221254721Semaste                    *val_obj_display);
1222254721Semaste    return true;
1223254721Semaste}
1224254721Semaste
1225254721Semastestatic bool
1226254721SemasteScanBracketedRange (const char* var_name_begin,
1227254721Semaste                    const char* var_name_end,
1228254721Semaste                    const char* var_name_final,
1229254721Semaste                    const char** open_bracket_position,
1230254721Semaste                    const char** separator_position,
1231254721Semaste                    const char** close_bracket_position,
1232254721Semaste                    const char** var_name_final_if_array_range,
1233254721Semaste                    int64_t* index_lower,
1234254721Semaste                    int64_t* index_higher)
1235254721Semaste{
1236254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1237254721Semaste    *open_bracket_position = ::strchr(var_name_begin,'[');
1238254721Semaste    if (*open_bracket_position && *open_bracket_position < var_name_final)
1239254721Semaste    {
1240254721Semaste        *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1241254721Semaste        *close_bracket_position = ::strchr(*open_bracket_position,']');
1242254721Semaste        // as usual, we assume that [] will come before %
1243254721Semaste        //printf("trying to expand a []\n");
1244254721Semaste        *var_name_final_if_array_range = *open_bracket_position;
1245254721Semaste        if (*close_bracket_position - *open_bracket_position == 1)
1246254721Semaste        {
1247254721Semaste            if (log)
1248254721Semaste                log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
1249254721Semaste            *index_lower = 0;
1250254721Semaste        }
1251254721Semaste        else if (*separator_position == NULL || *separator_position > var_name_end)
1252254721Semaste        {
1253254721Semaste            char *end = NULL;
1254254721Semaste            *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1255254721Semaste            *index_higher = *index_lower;
1256254721Semaste            if (log)
1257254721Semaste                log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
1258254721Semaste        }
1259254721Semaste        else if (*close_bracket_position && *close_bracket_position < var_name_end)
1260254721Semaste        {
1261254721Semaste            char *end = NULL;
1262254721Semaste            *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1263254721Semaste            *index_higher = ::strtoul (*separator_position+1, &end, 0);
1264254721Semaste            if (log)
1265254721Semaste                log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
1266254721Semaste        }
1267254721Semaste        else
1268254721Semaste        {
1269254721Semaste            if (log)
1270254721Semaste                log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
1271254721Semaste            return false;
1272254721Semaste        }
1273254721Semaste        if (*index_lower > *index_higher && *index_higher > 0)
1274254721Semaste        {
1275254721Semaste            if (log)
1276254721Semaste                log->Printf("[ScanBracketedRange] swapping indices");
1277254721Semaste            int64_t temp = *index_lower;
1278254721Semaste            *index_lower = *index_higher;
1279254721Semaste            *index_higher = temp;
1280254721Semaste        }
1281254721Semaste    }
1282254721Semaste    else if (log)
1283254721Semaste            log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
1284254721Semaste    return true;
1285254721Semaste}
1286254721Semaste
1287254721Semastetemplate <typename T>
1288254721Semastestatic bool RunScriptFormatKeyword(Stream &s, ScriptInterpreter *script_interpreter, T t, const std::string& script_name)
1289254721Semaste{
1290254721Semaste    if (script_interpreter)
1291254721Semaste    {
1292254721Semaste        Error script_error;
1293254721Semaste        std::string script_output;
1294254721Semaste
1295254721Semaste        if (script_interpreter->RunScriptFormatKeyword(script_name.c_str(), t, script_output, script_error) && script_error.Success())
1296254721Semaste        {
1297254721Semaste            s.Printf("%s", script_output.c_str());
1298254721Semaste            return true;
1299254721Semaste        }
1300254721Semaste        else
1301254721Semaste        {
1302254721Semaste            s.Printf("<error: %s>",script_error.AsCString());
1303254721Semaste        }
1304254721Semaste    }
1305254721Semaste    return false;
1306254721Semaste}
1307254721Semaste
1308254721Semastestatic ValueObjectSP
1309254721SemasteExpandIndexedExpression (ValueObject* valobj,
1310254721Semaste                         size_t index,
1311254721Semaste                         StackFrame* frame,
1312254721Semaste                         bool deref_pointer)
1313254721Semaste{
1314254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1315254721Semaste    const char* ptr_deref_format = "[%d]";
1316254721Semaste    std::string ptr_deref_buffer(10,0);
1317254721Semaste    ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
1318254721Semaste    if (log)
1319254721Semaste        log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
1320254721Semaste    const char* first_unparsed;
1321254721Semaste    ValueObject::GetValueForExpressionPathOptions options;
1322254721Semaste    ValueObject::ExpressionPathEndResultType final_value_type;
1323254721Semaste    ValueObject::ExpressionPathScanEndReason reason_to_stop;
1324254721Semaste    ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1325254721Semaste    ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
1326254721Semaste                                                          &first_unparsed,
1327254721Semaste                                                          &reason_to_stop,
1328254721Semaste                                                          &final_value_type,
1329254721Semaste                                                          options,
1330254721Semaste                                                          &what_next);
1331254721Semaste    if (!item)
1332254721Semaste    {
1333254721Semaste        if (log)
1334254721Semaste            log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
1335254721Semaste               " final_value_type %d",
1336254721Semaste               first_unparsed, reason_to_stop, final_value_type);
1337254721Semaste    }
1338254721Semaste    else
1339254721Semaste    {
1340254721Semaste        if (log)
1341254721Semaste            log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1342254721Semaste               " final_value_type %d",
1343254721Semaste               first_unparsed, reason_to_stop, final_value_type);
1344254721Semaste    }
1345254721Semaste    return item;
1346254721Semaste}
1347254721Semaste
1348254721Semastestatic inline bool
1349254721SemasteIsToken(const char *var_name_begin, const char *var)
1350254721Semaste{
1351254721Semaste    return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1352254721Semaste}
1353254721Semaste
1354254721Semastestatic bool
1355254721SemasteIsTokenWithFormat(const char *var_name_begin, const char *var, std::string &format, const char *default_format,
1356254721Semaste    const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1357254721Semaste{
1358254721Semaste    int var_len = strlen(var);
1359254721Semaste    if (::strncmp (var_name_begin, var, var_len) == 0)
1360254721Semaste    {
1361254721Semaste        var_name_begin += var_len;
1362254721Semaste        if (*var_name_begin == '}')
1363254721Semaste        {
1364254721Semaste            format = default_format;
1365254721Semaste            return true;
1366254721Semaste        }
1367254721Semaste        else if (*var_name_begin == '%')
1368254721Semaste        {
1369254721Semaste            // Allow format specifiers: x|X|u with optional width specifiers.
1370254721Semaste            //   ${thread.id%x}    ; hex
1371254721Semaste            //   ${thread.id%X}    ; uppercase hex
1372254721Semaste            //   ${thread.id%u}    ; unsigned decimal
1373254721Semaste            //   ${thread.id%8.8X} ; width.precision + specifier
1374254721Semaste            //   ${thread.id%tid}  ; unsigned on FreeBSD/Linux, otherwise default_format (0x%4.4x for thread.id)
1375254721Semaste            int dot_count = 0;
1376254721Semaste            const char *specifier = NULL;
1377254721Semaste            int width_precision_length = 0;
1378254721Semaste            const char *width_precision = ++var_name_begin;
1379254721Semaste            while (isdigit(*var_name_begin) || *var_name_begin == '.')
1380254721Semaste            {
1381254721Semaste                dot_count += (*var_name_begin == '.');
1382254721Semaste                if (dot_count > 1)
1383254721Semaste                    break;
1384254721Semaste                var_name_begin++;
1385254721Semaste                width_precision_length++;
1386254721Semaste            }
1387254721Semaste
1388254721Semaste            if (IsToken (var_name_begin, "tid}"))
1389254721Semaste            {
1390254721Semaste                Target *target = Target::GetTargetFromContexts (exe_ctx_ptr, sc_ptr);
1391254721Semaste                if (target)
1392254721Semaste                {
1393254721Semaste                    ArchSpec arch (target->GetArchitecture ());
1394254721Semaste                    llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1395254721Semaste                    if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1396254721Semaste                        specifier = PRIu64;
1397254721Semaste                }
1398254721Semaste                if (!specifier)
1399254721Semaste                {
1400254721Semaste                    format = default_format;
1401254721Semaste                    return true;
1402254721Semaste                }
1403254721Semaste            }
1404254721Semaste            else if (IsToken (var_name_begin, "x}"))
1405254721Semaste                specifier = PRIx64;
1406254721Semaste            else if (IsToken (var_name_begin, "X}"))
1407254721Semaste                specifier = PRIX64;
1408254721Semaste            else if (IsToken (var_name_begin, "u}"))
1409254721Semaste                specifier = PRIu64;
1410254721Semaste
1411254721Semaste            if (specifier)
1412254721Semaste            {
1413254721Semaste                format = "%";
1414254721Semaste                if (width_precision_length)
1415254721Semaste                    format += std::string(width_precision, width_precision_length);
1416254721Semaste                format += specifier;
1417254721Semaste                return true;
1418254721Semaste            }
1419254721Semaste        }
1420254721Semaste    }
1421254721Semaste    return false;
1422254721Semaste}
1423254721Semaste
1424254721Semastestatic bool
1425254721SemasteFormatPromptRecurse
1426254721Semaste(
1427254721Semaste    const char *format,
1428254721Semaste    const SymbolContext *sc,
1429254721Semaste    const ExecutionContext *exe_ctx,
1430254721Semaste    const Address *addr,
1431254721Semaste    Stream &s,
1432254721Semaste    const char **end,
1433254721Semaste    ValueObject* valobj
1434254721Semaste)
1435254721Semaste{
1436254721Semaste    ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
1437254721Semaste    bool success = true;
1438254721Semaste    const char *p;
1439254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1440254721Semaste
1441254721Semaste    for (p = format; *p != '\0'; ++p)
1442254721Semaste    {
1443254721Semaste        if (realvalobj)
1444254721Semaste        {
1445254721Semaste            valobj = realvalobj;
1446254721Semaste            realvalobj = NULL;
1447254721Semaste        }
1448254721Semaste        size_t non_special_chars = ::strcspn (p, "${}\\");
1449254721Semaste        if (non_special_chars > 0)
1450254721Semaste        {
1451254721Semaste            if (success)
1452254721Semaste                s.Write (p, non_special_chars);
1453254721Semaste            p += non_special_chars;
1454254721Semaste        }
1455254721Semaste
1456254721Semaste        if (*p == '\0')
1457254721Semaste        {
1458254721Semaste            break;
1459254721Semaste        }
1460254721Semaste        else if (*p == '{')
1461254721Semaste        {
1462254721Semaste            // Start a new scope that must have everything it needs if it is to
1463254721Semaste            // to make it into the final output stream "s". If you want to make
1464254721Semaste            // a format that only prints out the function or symbol name if there
1465254721Semaste            // is one in the symbol context you can use:
1466254721Semaste            //      "{function =${function.name}}"
1467254721Semaste            // The first '{' starts a new scope that end with the matching '}' at
1468254721Semaste            // the end of the string. The contents "function =${function.name}"
1469254721Semaste            // will then be evaluated and only be output if there is a function
1470254721Semaste            // or symbol with a valid name.
1471254721Semaste            StreamString sub_strm;
1472254721Semaste
1473254721Semaste            ++p;  // Skip the '{'
1474254721Semaste
1475254721Semaste            if (FormatPromptRecurse (p, sc, exe_ctx, addr, sub_strm, &p, valobj))
1476254721Semaste            {
1477254721Semaste                // The stream had all it needed
1478254721Semaste                s.Write(sub_strm.GetData(), sub_strm.GetSize());
1479254721Semaste            }
1480254721Semaste            if (*p != '}')
1481254721Semaste            {
1482254721Semaste                success = false;
1483254721Semaste                break;
1484254721Semaste            }
1485254721Semaste        }
1486254721Semaste        else if (*p == '}')
1487254721Semaste        {
1488254721Semaste            // End of a enclosing scope
1489254721Semaste            break;
1490254721Semaste        }
1491254721Semaste        else if (*p == '$')
1492254721Semaste        {
1493254721Semaste            // We have a prompt variable to print
1494254721Semaste            ++p;
1495254721Semaste            if (*p == '{')
1496254721Semaste            {
1497254721Semaste                ++p;
1498254721Semaste                const char *var_name_begin = p;
1499254721Semaste                const char *var_name_end = ::strchr (p, '}');
1500254721Semaste
1501254721Semaste                if (var_name_end && var_name_begin < var_name_end)
1502254721Semaste                {
1503254721Semaste                    // if we have already failed to parse, skip this variable
1504254721Semaste                    if (success)
1505254721Semaste                    {
1506254721Semaste                        const char *cstr = NULL;
1507254721Semaste                        std::string token_format;
1508254721Semaste                        Address format_addr;
1509254721Semaste                        bool calculate_format_addr_function_offset = false;
1510254721Semaste                        // Set reg_kind and reg_num to invalid values
1511254721Semaste                        RegisterKind reg_kind = kNumRegisterKinds;
1512254721Semaste                        uint32_t reg_num = LLDB_INVALID_REGNUM;
1513254721Semaste                        FileSpec format_file_spec;
1514254721Semaste                        const RegisterInfo *reg_info = NULL;
1515254721Semaste                        RegisterContext *reg_ctx = NULL;
1516254721Semaste                        bool do_deref_pointer = false;
1517254721Semaste                        ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1518254721Semaste                        ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
1519254721Semaste
1520254721Semaste                        // Each variable must set success to true below...
1521254721Semaste                        bool var_success = false;
1522254721Semaste                        switch (var_name_begin[0])
1523254721Semaste                        {
1524254721Semaste                        case '*':
1525254721Semaste                        case 'v':
1526254721Semaste                        case 's':
1527254721Semaste                            {
1528254721Semaste                                if (!valobj)
1529254721Semaste                                    break;
1530254721Semaste
1531254721Semaste                                if (log)
1532254721Semaste                                    log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1533254721Semaste
1534254721Semaste                                // check for *var and *svar
1535254721Semaste                                if (*var_name_begin == '*')
1536254721Semaste                                {
1537254721Semaste                                    do_deref_pointer = true;
1538254721Semaste                                    var_name_begin++;
1539254721Semaste                                    if (log)
1540254721Semaste                                        log->Printf("[Debugger::FormatPrompt] found a deref, new string is: %s",var_name_begin);
1541254721Semaste                                }
1542254721Semaste
1543254721Semaste                                if (*var_name_begin == 's')
1544254721Semaste                                {
1545254721Semaste                                    if (!valobj->IsSynthetic())
1546254721Semaste                                        valobj = valobj->GetSyntheticValue().get();
1547254721Semaste                                    if (!valobj)
1548254721Semaste                                        break;
1549254721Semaste                                    var_name_begin++;
1550254721Semaste                                    if (log)
1551254721Semaste                                        log->Printf("[Debugger::FormatPrompt] found a synthetic, new string is: %s",var_name_begin);
1552254721Semaste                                }
1553254721Semaste
1554254721Semaste                                // should be a 'v' by now
1555254721Semaste                                if (*var_name_begin != 'v')
1556254721Semaste                                    break;
1557254721Semaste
1558254721Semaste                                if (log)
1559254721Semaste                                    log->Printf("[Debugger::FormatPrompt] string I am working with: %s",var_name_begin);
1560254721Semaste
1561254721Semaste                                ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
1562254721Semaste                                                                                  ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1563254721Semaste                                ValueObject::GetValueForExpressionPathOptions options;
1564254721Semaste                                options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
1565254721Semaste                                ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1566254721Semaste                                ValueObject* target = NULL;
1567254721Semaste                                Format custom_format = eFormatInvalid;
1568254721Semaste                                const char* var_name_final = NULL;
1569254721Semaste                                const char* var_name_final_if_array_range = NULL;
1570254721Semaste                                const char* close_bracket_position = NULL;
1571254721Semaste                                int64_t index_lower = -1;
1572254721Semaste                                int64_t index_higher = -1;
1573254721Semaste                                bool is_array_range = false;
1574254721Semaste                                const char* first_unparsed;
1575254721Semaste                                bool was_plain_var = false;
1576254721Semaste                                bool was_var_format = false;
1577254721Semaste                                bool was_var_indexed = false;
1578254721Semaste
1579254721Semaste                                if (!valobj) break;
1580254721Semaste                                // simplest case ${var}, just print valobj's value
1581254721Semaste                                if (IsToken (var_name_begin, "var}"))
1582254721Semaste                                {
1583254721Semaste                                    was_plain_var = true;
1584254721Semaste                                    target = valobj;
1585254721Semaste                                    val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1586254721Semaste                                }
1587254721Semaste                                else if (IsToken (var_name_begin,"var%"))
1588254721Semaste                                {
1589254721Semaste                                    was_var_format = true;
1590254721Semaste                                    // this is a variable with some custom format applied to it
1591254721Semaste                                    const char* percent_position;
1592254721Semaste                                    target = valobj;
1593254721Semaste                                    val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1594254721Semaste                                    ScanFormatDescriptor (var_name_begin,
1595254721Semaste                                                          var_name_end,
1596254721Semaste                                                          &var_name_final,
1597254721Semaste                                                          &percent_position,
1598254721Semaste                                                          &custom_format,
1599254721Semaste                                                          &val_obj_display);
1600254721Semaste                                }
1601254721Semaste                                    // this is ${var.something} or multiple .something nested
1602254721Semaste                                else if (IsToken (var_name_begin, "var"))
1603254721Semaste                                {
1604254721Semaste                                    if (IsToken (var_name_begin, "var["))
1605254721Semaste                                        was_var_indexed = true;
1606254721Semaste                                    const char* percent_position;
1607254721Semaste                                    ScanFormatDescriptor (var_name_begin,
1608254721Semaste                                                          var_name_end,
1609254721Semaste                                                          &var_name_final,
1610254721Semaste                                                          &percent_position,
1611254721Semaste                                                          &custom_format,
1612254721Semaste                                                          &val_obj_display);
1613254721Semaste
1614254721Semaste                                    const char* open_bracket_position;
1615254721Semaste                                    const char* separator_position;
1616254721Semaste                                    ScanBracketedRange (var_name_begin,
1617254721Semaste                                                        var_name_end,
1618254721Semaste                                                        var_name_final,
1619254721Semaste                                                        &open_bracket_position,
1620254721Semaste                                                        &separator_position,
1621254721Semaste                                                        &close_bracket_position,
1622254721Semaste                                                        &var_name_final_if_array_range,
1623254721Semaste                                                        &index_lower,
1624254721Semaste                                                        &index_higher);
1625254721Semaste
1626254721Semaste                                    Error error;
1627254721Semaste
1628254721Semaste                                    std::string expr_path(var_name_final-var_name_begin-1,0);
1629254721Semaste                                    memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1630254721Semaste
1631254721Semaste                                    if (log)
1632254721Semaste                                        log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1633254721Semaste
1634254721Semaste                                    target = valobj->GetValueForExpressionPath(expr_path.c_str(),
1635254721Semaste                                                                             &first_unparsed,
1636254721Semaste                                                                             &reason_to_stop,
1637254721Semaste                                                                             &final_value_type,
1638254721Semaste                                                                             options,
1639254721Semaste                                                                             &what_next).get();
1640254721Semaste
1641254721Semaste                                    if (!target)
1642254721Semaste                                    {
1643254721Semaste                                        if (log)
1644254721Semaste                                            log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
1645254721Semaste                                               " final_value_type %d",
1646254721Semaste                                               first_unparsed, reason_to_stop, final_value_type);
1647254721Semaste                                        break;
1648254721Semaste                                    }
1649254721Semaste                                    else
1650254721Semaste                                    {
1651254721Semaste                                        if (log)
1652254721Semaste                                            log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1653254721Semaste                                               " final_value_type %d",
1654254721Semaste                                               first_unparsed, reason_to_stop, final_value_type);
1655254721Semaste                                    }
1656254721Semaste                                }
1657254721Semaste                                else
1658254721Semaste                                    break;
1659254721Semaste
1660254721Semaste                                is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1661254721Semaste                                                  final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
1662254721Semaste
1663254721Semaste                                do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
1664254721Semaste
1665254721Semaste                                if (do_deref_pointer && !is_array_range)
1666254721Semaste                                {
1667254721Semaste                                    // I have not deref-ed yet, let's do it
1668254721Semaste                                    // this happens when we are not going through GetValueForVariableExpressionPath
1669254721Semaste                                    // to get to the target ValueObject
1670254721Semaste                                    Error error;
1671254721Semaste                                    target = target->Dereference(error).get();
1672254721Semaste                                    if (error.Fail())
1673254721Semaste                                    {
1674254721Semaste                                        if (log)
1675254721Semaste                                            log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
1676254721Semaste                                        break;
1677254721Semaste                                    }
1678254721Semaste                                    do_deref_pointer = false;
1679254721Semaste                                }
1680254721Semaste
1681254721Semaste                                // we do not want to use the summary for a bitfield of type T:n
1682254721Semaste                                // if we were originally dealing with just a T - that would get
1683254721Semaste                                // us into an endless recursion
1684254721Semaste                                if (target->IsBitfield() && was_var_indexed)
1685254721Semaste                                {
1686254721Semaste                                    // TODO: check for a (T:n)-specific summary - we should still obey that
1687254721Semaste                                    StreamString bitfield_name;
1688254721Semaste                                    bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1689254721Semaste                                    lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1690254721Semaste                                    if (!DataVisualization::GetSummaryForType(type_sp))
1691254721Semaste                                        val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1692254721Semaste                                }
1693254721Semaste
1694254721Semaste                                // TODO use flags for these
1695254721Semaste                                const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
1696254721Semaste                                bool is_array = (type_info_flags & ClangASTType::eTypeIsArray) != 0;
1697254721Semaste                                bool is_pointer = (type_info_flags & ClangASTType::eTypeIsPointer) != 0;
1698254721Semaste                                bool is_aggregate = target->GetClangType().IsAggregateType();
1699254721Semaste
1700254721Semaste                                if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
1701254721Semaste                                {
1702254721Semaste                                    StreamString str_temp;
1703254721Semaste                                    if (log)
1704254721Semaste                                        log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
1705254721Semaste
1706254721Semaste                                    if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
1707254721Semaste                                    {
1708254721Semaste                                        // try to use the special cases
1709254721Semaste                                        var_success = target->DumpPrintableRepresentation(str_temp,
1710254721Semaste                                                                                          val_obj_display,
1711254721Semaste                                                                                          custom_format);
1712254721Semaste                                        if (log)
1713254721Semaste                                            log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
1714254721Semaste
1715254721Semaste                                        // should not happen
1716254721Semaste                                        if (var_success)
1717254721Semaste                                            s << str_temp.GetData();
1718254721Semaste                                        var_success = true;
1719254721Semaste                                        break;
1720254721Semaste                                    }
1721254721Semaste                                    else
1722254721Semaste                                    {
1723254721Semaste                                        if (was_plain_var) // if ${var}
1724254721Semaste                                        {
1725254721Semaste                                            s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1726254721Semaste                                        }
1727254721Semaste                                        else if (is_pointer) // if pointer, value is the address stored
1728254721Semaste                                        {
1729254721Semaste                                            target->DumpPrintableRepresentation (s,
1730254721Semaste                                                                                 val_obj_display,
1731254721Semaste                                                                                 custom_format,
1732254721Semaste                                                                                 ValueObject::ePrintableRepresentationSpecialCasesDisable);
1733254721Semaste                                        }
1734254721Semaste                                        var_success = true;
1735254721Semaste                                        break;
1736254721Semaste                                    }
1737254721Semaste                                }
1738254721Semaste
1739254721Semaste                                // if directly trying to print ${var}, and this is an aggregate, display a nice
1740254721Semaste                                // type @ location message
1741254721Semaste                                if (is_aggregate && was_plain_var)
1742254721Semaste                                {
1743254721Semaste                                    s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1744254721Semaste                                    var_success = true;
1745254721Semaste                                    break;
1746254721Semaste                                }
1747254721Semaste
1748254721Semaste                                // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
1749254721Semaste                                if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
1750254721Semaste                                {
1751254721Semaste                                    s << "<invalid use of aggregate type>";
1752254721Semaste                                    var_success = true;
1753254721Semaste                                    break;
1754254721Semaste                                }
1755254721Semaste
1756254721Semaste                                if (!is_array_range)
1757254721Semaste                                {
1758254721Semaste                                    if (log)
1759254721Semaste                                        log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
1760254721Semaste                                    var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1761254721Semaste                                }
1762254721Semaste                                else
1763254721Semaste                                {
1764254721Semaste                                    if (log)
1765254721Semaste                                        log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
1766254721Semaste                                    if (!is_array && !is_pointer)
1767254721Semaste                                        break;
1768254721Semaste                                    if (log)
1769254721Semaste                                        log->Printf("[Debugger::FormatPrompt] handle as array");
1770254721Semaste                                    const char* special_directions = NULL;
1771254721Semaste                                    StreamString special_directions_writer;
1772254721Semaste                                    if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1773254721Semaste                                    {
1774254721Semaste                                        ConstString additional_data;
1775254721Semaste                                        additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1776254721Semaste                                        special_directions_writer.Printf("${%svar%s}",
1777254721Semaste                                                                         do_deref_pointer ? "*" : "",
1778254721Semaste                                                                         additional_data.GetCString());
1779254721Semaste                                        special_directions = special_directions_writer.GetData();
1780254721Semaste                                    }
1781254721Semaste
1782254721Semaste                                    // let us display items index_lower thru index_higher of this array
1783254721Semaste                                    s.PutChar('[');
1784254721Semaste                                    var_success = true;
1785254721Semaste
1786254721Semaste                                    if (index_higher < 0)
1787254721Semaste                                        index_higher = valobj->GetNumChildren() - 1;
1788254721Semaste
1789254721Semaste                                    uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
1790254721Semaste
1791254721Semaste                                    for (;index_lower<=index_higher;index_lower++)
1792254721Semaste                                    {
1793254721Semaste                                        ValueObject* item = ExpandIndexedExpression (target,
1794254721Semaste                                                                                     index_lower,
1795254721Semaste                                                                                     exe_ctx->GetFramePtr(),
1796254721Semaste                                                                                     false).get();
1797254721Semaste
1798254721Semaste                                        if (!item)
1799254721Semaste                                        {
1800254721Semaste                                            if (log)
1801254721Semaste                                                log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
1802254721Semaste                                        }
1803254721Semaste                                        else
1804254721Semaste                                        {
1805254721Semaste                                            if (log)
1806254721Semaste                                                log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
1807254721Semaste                                        }
1808254721Semaste
1809254721Semaste                                        if (!special_directions)
1810254721Semaste                                            var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1811254721Semaste                                        else
1812254721Semaste                                            var_success &= FormatPromptRecurse(special_directions, sc, exe_ctx, addr, s, NULL, item);
1813254721Semaste
1814254721Semaste                                        if (--max_num_children == 0)
1815254721Semaste                                        {
1816254721Semaste                                            s.PutCString(", ...");
1817254721Semaste                                            break;
1818254721Semaste                                        }
1819254721Semaste
1820254721Semaste                                        if (index_lower < index_higher)
1821254721Semaste                                            s.PutChar(',');
1822254721Semaste                                    }
1823254721Semaste                                    s.PutChar(']');
1824254721Semaste                                }
1825254721Semaste                            }
1826254721Semaste                            break;
1827254721Semaste                        case 'a':
1828254721Semaste                            if (IsToken (var_name_begin, "addr}"))
1829254721Semaste                            {
1830254721Semaste                                if (addr && addr->IsValid())
1831254721Semaste                                {
1832254721Semaste                                    var_success = true;
1833254721Semaste                                    format_addr = *addr;
1834254721Semaste                                }
1835254721Semaste                            }
1836254721Semaste                            break;
1837254721Semaste
1838254721Semaste                        case 'p':
1839254721Semaste                            if (IsToken (var_name_begin, "process."))
1840254721Semaste                            {
1841254721Semaste                                if (exe_ctx)
1842254721Semaste                                {
1843254721Semaste                                    Process *process = exe_ctx->GetProcessPtr();
1844254721Semaste                                    if (process)
1845254721Semaste                                    {
1846254721Semaste                                        var_name_begin += ::strlen ("process.");
1847254721Semaste                                        if (IsTokenWithFormat (var_name_begin, "id", token_format, "%" PRIu64, exe_ctx, sc))
1848254721Semaste                                        {
1849254721Semaste                                            s.Printf(token_format.c_str(), process->GetID());
1850254721Semaste                                            var_success = true;
1851254721Semaste                                        }
1852254721Semaste                                        else if ((IsToken (var_name_begin, "name}")) ||
1853254721Semaste                                                (IsToken (var_name_begin, "file.basename}")) ||
1854254721Semaste                                                (IsToken (var_name_begin, "file.fullpath}")))
1855254721Semaste                                        {
1856254721Semaste                                            Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1857254721Semaste                                            if (exe_module)
1858254721Semaste                                            {
1859254721Semaste                                                if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
1860254721Semaste                                                {
1861254721Semaste                                                    format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
1862263363Semaste                                                    var_success = (bool)format_file_spec;
1863254721Semaste                                                }
1864254721Semaste                                                else
1865254721Semaste                                                {
1866254721Semaste                                                    format_file_spec = exe_module->GetFileSpec();
1867263363Semaste                                                    var_success = (bool)format_file_spec;
1868254721Semaste                                                }
1869254721Semaste                                            }
1870254721Semaste                                        }
1871254721Semaste                                        else if (IsToken (var_name_begin, "script:"))
1872254721Semaste                                        {
1873254721Semaste                                            var_name_begin += ::strlen("script:");
1874254721Semaste                                            std::string script_name(var_name_begin,var_name_end);
1875254721Semaste                                            ScriptInterpreter* script_interpreter = process->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1876254721Semaste                                            if (RunScriptFormatKeyword (s, script_interpreter, process, script_name))
1877254721Semaste                                                var_success = true;
1878254721Semaste                                        }
1879254721Semaste                                    }
1880254721Semaste                                }
1881254721Semaste                            }
1882254721Semaste                            break;
1883254721Semaste
1884254721Semaste                        case 't':
1885254721Semaste                           if (IsToken (var_name_begin, "thread."))
1886254721Semaste                            {
1887254721Semaste                                if (exe_ctx)
1888254721Semaste                                {
1889254721Semaste                                    Thread *thread = exe_ctx->GetThreadPtr();
1890254721Semaste                                    if (thread)
1891254721Semaste                                    {
1892254721Semaste                                        var_name_begin += ::strlen ("thread.");
1893254721Semaste                                        if (IsTokenWithFormat (var_name_begin, "id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1894254721Semaste                                        {
1895254721Semaste                                            s.Printf(token_format.c_str(), thread->GetID());
1896254721Semaste                                            var_success = true;
1897254721Semaste                                        }
1898254721Semaste                                        else if (IsTokenWithFormat (var_name_begin, "protocol_id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1899254721Semaste                                        {
1900254721Semaste                                            s.Printf(token_format.c_str(), thread->GetProtocolID());
1901254721Semaste                                            var_success = true;
1902254721Semaste                                        }
1903254721Semaste                                        else if (IsTokenWithFormat (var_name_begin, "index", token_format, "%" PRIu64, exe_ctx, sc))
1904254721Semaste                                        {
1905254721Semaste                                            s.Printf(token_format.c_str(), (uint64_t)thread->GetIndexID());
1906254721Semaste                                            var_success = true;
1907254721Semaste                                        }
1908254721Semaste                                        else if (IsToken (var_name_begin, "name}"))
1909254721Semaste                                        {
1910254721Semaste                                            cstr = thread->GetName();
1911254721Semaste                                            var_success = cstr && cstr[0];
1912254721Semaste                                            if (var_success)
1913254721Semaste                                                s.PutCString(cstr);
1914254721Semaste                                        }
1915254721Semaste                                        else if (IsToken (var_name_begin, "queue}"))
1916254721Semaste                                        {
1917254721Semaste                                            cstr = thread->GetQueueName();
1918254721Semaste                                            var_success = cstr && cstr[0];
1919254721Semaste                                            if (var_success)
1920254721Semaste                                                s.PutCString(cstr);
1921254721Semaste                                        }
1922254721Semaste                                        else if (IsToken (var_name_begin, "stop-reason}"))
1923254721Semaste                                        {
1924254721Semaste                                            StopInfoSP stop_info_sp = thread->GetStopInfo ();
1925254721Semaste                                            if (stop_info_sp && stop_info_sp->IsValid())
1926254721Semaste                                            {
1927254721Semaste                                                cstr = stop_info_sp->GetDescription();
1928254721Semaste                                                if (cstr && cstr[0])
1929254721Semaste                                                {
1930254721Semaste                                                    s.PutCString(cstr);
1931254721Semaste                                                    var_success = true;
1932254721Semaste                                                }
1933254721Semaste                                            }
1934254721Semaste                                        }
1935254721Semaste                                        else if (IsToken (var_name_begin, "return-value}"))
1936254721Semaste                                        {
1937254721Semaste                                            StopInfoSP stop_info_sp = thread->GetStopInfo ();
1938254721Semaste                                            if (stop_info_sp && stop_info_sp->IsValid())
1939254721Semaste                                            {
1940254721Semaste                                                ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
1941254721Semaste                                                if (return_valobj_sp)
1942254721Semaste                                                {
1943263363Semaste                                                    return_valobj_sp->Dump(s);
1944254721Semaste                                                    var_success = true;
1945254721Semaste                                                }
1946254721Semaste                                            }
1947254721Semaste                                        }
1948254721Semaste                                        else if (IsToken (var_name_begin, "script:"))
1949254721Semaste                                        {
1950254721Semaste                                            var_name_begin += ::strlen("script:");
1951254721Semaste                                            std::string script_name(var_name_begin,var_name_end);
1952254721Semaste                                            ScriptInterpreter* script_interpreter = thread->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1953254721Semaste                                            if (RunScriptFormatKeyword (s, script_interpreter, thread, script_name))
1954254721Semaste                                                var_success = true;
1955254721Semaste                                        }
1956254721Semaste                                    }
1957254721Semaste                                }
1958254721Semaste                            }
1959254721Semaste                            else if (IsToken (var_name_begin, "target."))
1960254721Semaste                            {
1961254721Semaste                                // TODO: hookup properties
1962254721Semaste//                                if (!target_properties_sp)
1963254721Semaste//                                {
1964254721Semaste//                                    Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
1965254721Semaste//                                    if (target)
1966254721Semaste//                                        target_properties_sp = target->GetProperties();
1967254721Semaste//                                }
1968254721Semaste//
1969254721Semaste//                                if (target_properties_sp)
1970254721Semaste//                                {
1971254721Semaste//                                    var_name_begin += ::strlen ("target.");
1972254721Semaste//                                    const char *end_property = strchr(var_name_begin, '}');
1973254721Semaste//                                    if (end_property)
1974254721Semaste//                                    {
1975254721Semaste//                                        ConstString property_name(var_name_begin, end_property - var_name_begin);
1976254721Semaste//                                        std::string property_value (target_properties_sp->GetPropertyValue(property_name));
1977254721Semaste//                                        if (!property_value.empty())
1978254721Semaste//                                        {
1979254721Semaste//                                            s.PutCString (property_value.c_str());
1980254721Semaste//                                            var_success = true;
1981254721Semaste//                                        }
1982254721Semaste//                                    }
1983254721Semaste//                                }
1984254721Semaste                                Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
1985254721Semaste                                if (target)
1986254721Semaste                                {
1987254721Semaste                                    var_name_begin += ::strlen ("target.");
1988254721Semaste                                    if (IsToken (var_name_begin, "arch}"))
1989254721Semaste                                    {
1990254721Semaste                                        ArchSpec arch (target->GetArchitecture ());
1991254721Semaste                                        if (arch.IsValid())
1992254721Semaste                                        {
1993254721Semaste                                            s.PutCString (arch.GetArchitectureName());
1994254721Semaste                                            var_success = true;
1995254721Semaste                                        }
1996254721Semaste                                    }
1997254721Semaste                                    else if (IsToken (var_name_begin, "script:"))
1998254721Semaste                                    {
1999254721Semaste                                        var_name_begin += ::strlen("script:");
2000254721Semaste                                        std::string script_name(var_name_begin,var_name_end);
2001254721Semaste                                        ScriptInterpreter* script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2002254721Semaste                                        if (RunScriptFormatKeyword (s, script_interpreter, target, script_name))
2003254721Semaste                                            var_success = true;
2004254721Semaste                                    }
2005254721Semaste                                }
2006254721Semaste                            }
2007254721Semaste                            break;
2008254721Semaste
2009254721Semaste
2010254721Semaste                        case 'm':
2011254721Semaste                           if (IsToken (var_name_begin, "module."))
2012254721Semaste                            {
2013254721Semaste                                if (sc && sc->module_sp.get())
2014254721Semaste                                {
2015254721Semaste                                    Module *module = sc->module_sp.get();
2016254721Semaste                                    var_name_begin += ::strlen ("module.");
2017254721Semaste
2018254721Semaste                                    if (IsToken (var_name_begin, "file."))
2019254721Semaste                                    {
2020254721Semaste                                        if (module->GetFileSpec())
2021254721Semaste                                        {
2022254721Semaste                                            var_name_begin += ::strlen ("file.");
2023254721Semaste
2024254721Semaste                                            if (IsToken (var_name_begin, "basename}"))
2025254721Semaste                                            {
2026254721Semaste                                                format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
2027263363Semaste                                                var_success = (bool)format_file_spec;
2028254721Semaste                                            }
2029254721Semaste                                            else if (IsToken (var_name_begin, "fullpath}"))
2030254721Semaste                                            {
2031254721Semaste                                                format_file_spec = module->GetFileSpec();
2032263363Semaste                                                var_success = (bool)format_file_spec;
2033254721Semaste                                            }
2034254721Semaste                                        }
2035254721Semaste                                    }
2036254721Semaste                                }
2037254721Semaste                            }
2038254721Semaste                            break;
2039254721Semaste
2040254721Semaste
2041254721Semaste                        case 'f':
2042254721Semaste                           if (IsToken (var_name_begin, "file."))
2043254721Semaste                            {
2044254721Semaste                                if (sc && sc->comp_unit != NULL)
2045254721Semaste                                {
2046254721Semaste                                    var_name_begin += ::strlen ("file.");
2047254721Semaste
2048254721Semaste                                    if (IsToken (var_name_begin, "basename}"))
2049254721Semaste                                    {
2050254721Semaste                                        format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
2051263363Semaste                                        var_success = (bool)format_file_spec;
2052254721Semaste                                    }
2053254721Semaste                                    else if (IsToken (var_name_begin, "fullpath}"))
2054254721Semaste                                    {
2055254721Semaste                                        format_file_spec = *sc->comp_unit;
2056263363Semaste                                        var_success = (bool)format_file_spec;
2057254721Semaste                                    }
2058254721Semaste                                }
2059254721Semaste                            }
2060254721Semaste                           else if (IsToken (var_name_begin, "frame."))
2061254721Semaste                            {
2062254721Semaste                                if (exe_ctx)
2063254721Semaste                                {
2064254721Semaste                                    StackFrame *frame = exe_ctx->GetFramePtr();
2065254721Semaste                                    if (frame)
2066254721Semaste                                    {
2067254721Semaste                                        var_name_begin += ::strlen ("frame.");
2068254721Semaste                                        if (IsToken (var_name_begin, "index}"))
2069254721Semaste                                        {
2070254721Semaste                                            s.Printf("%u", frame->GetFrameIndex());
2071254721Semaste                                            var_success = true;
2072254721Semaste                                        }
2073254721Semaste                                        else if (IsToken (var_name_begin, "pc}"))
2074254721Semaste                                        {
2075254721Semaste                                            reg_kind = eRegisterKindGeneric;
2076254721Semaste                                            reg_num = LLDB_REGNUM_GENERIC_PC;
2077254721Semaste                                            var_success = true;
2078254721Semaste                                        }
2079254721Semaste                                        else if (IsToken (var_name_begin, "sp}"))
2080254721Semaste                                        {
2081254721Semaste                                            reg_kind = eRegisterKindGeneric;
2082254721Semaste                                            reg_num = LLDB_REGNUM_GENERIC_SP;
2083254721Semaste                                            var_success = true;
2084254721Semaste                                        }
2085254721Semaste                                        else if (IsToken (var_name_begin, "fp}"))
2086254721Semaste                                        {
2087254721Semaste                                            reg_kind = eRegisterKindGeneric;
2088254721Semaste                                            reg_num = LLDB_REGNUM_GENERIC_FP;
2089254721Semaste                                            var_success = true;
2090254721Semaste                                        }
2091254721Semaste                                        else if (IsToken (var_name_begin, "flags}"))
2092254721Semaste                                        {
2093254721Semaste                                            reg_kind = eRegisterKindGeneric;
2094254721Semaste                                            reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2095254721Semaste                                            var_success = true;
2096254721Semaste                                        }
2097254721Semaste                                        else if (IsToken (var_name_begin, "reg."))
2098254721Semaste                                        {
2099254721Semaste                                            reg_ctx = frame->GetRegisterContext().get();
2100254721Semaste                                            if (reg_ctx)
2101254721Semaste                                            {
2102254721Semaste                                                var_name_begin += ::strlen ("reg.");
2103254721Semaste                                                if (var_name_begin < var_name_end)
2104254721Semaste                                                {
2105254721Semaste                                                    std::string reg_name (var_name_begin, var_name_end);
2106254721Semaste                                                    reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2107254721Semaste                                                    if (reg_info)
2108254721Semaste                                                        var_success = true;
2109254721Semaste                                                }
2110254721Semaste                                            }
2111254721Semaste                                        }
2112254721Semaste                                        else if (IsToken (var_name_begin, "script:"))
2113254721Semaste                                        {
2114254721Semaste                                            var_name_begin += ::strlen("script:");
2115254721Semaste                                            std::string script_name(var_name_begin,var_name_end);
2116254721Semaste                                            ScriptInterpreter* script_interpreter = frame->GetThread()->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2117254721Semaste                                            if (RunScriptFormatKeyword (s, script_interpreter, frame, script_name))
2118254721Semaste                                                var_success = true;
2119254721Semaste                                        }
2120254721Semaste                                    }
2121254721Semaste                                }
2122254721Semaste                            }
2123254721Semaste                            else if (IsToken (var_name_begin, "function."))
2124254721Semaste                            {
2125254721Semaste                                if (sc && (sc->function != NULL || sc->symbol != NULL))
2126254721Semaste                                {
2127254721Semaste                                    var_name_begin += ::strlen ("function.");
2128254721Semaste                                    if (IsToken (var_name_begin, "id}"))
2129254721Semaste                                    {
2130254721Semaste                                        if (sc->function)
2131254721Semaste                                            s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
2132254721Semaste                                        else
2133254721Semaste                                            s.Printf("symbol[%u]", sc->symbol->GetID());
2134254721Semaste
2135254721Semaste                                        var_success = true;
2136254721Semaste                                    }
2137254721Semaste                                    else if (IsToken (var_name_begin, "name}"))
2138254721Semaste                                    {
2139254721Semaste                                        if (sc->function)
2140254721Semaste                                            cstr = sc->function->GetName().AsCString (NULL);
2141254721Semaste                                        else if (sc->symbol)
2142254721Semaste                                            cstr = sc->symbol->GetName().AsCString (NULL);
2143254721Semaste                                        if (cstr)
2144254721Semaste                                        {
2145254721Semaste                                            s.PutCString(cstr);
2146254721Semaste
2147254721Semaste                                            if (sc->block)
2148254721Semaste                                            {
2149254721Semaste                                                Block *inline_block = sc->block->GetContainingInlinedBlock ();
2150254721Semaste                                                if (inline_block)
2151254721Semaste                                                {
2152254721Semaste                                                    const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2153254721Semaste                                                    if (inline_info)
2154254721Semaste                                                    {
2155254721Semaste                                                        s.PutCString(" [inlined] ");
2156254721Semaste                                                        inline_info->GetName().Dump(&s);
2157254721Semaste                                                    }
2158254721Semaste                                                }
2159254721Semaste                                            }
2160254721Semaste                                            var_success = true;
2161254721Semaste                                        }
2162254721Semaste                                    }
2163254721Semaste                                    else if (IsToken (var_name_begin, "name-with-args}"))
2164254721Semaste                                    {
2165254721Semaste                                        // Print the function name with arguments in it
2166254721Semaste
2167254721Semaste                                        if (sc->function)
2168254721Semaste                                        {
2169254721Semaste                                            var_success = true;
2170254721Semaste                                            ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2171254721Semaste                                            cstr = sc->function->GetName().AsCString (NULL);
2172254721Semaste                                            if (cstr)
2173254721Semaste                                            {
2174254721Semaste                                                const InlineFunctionInfo *inline_info = NULL;
2175254721Semaste                                                VariableListSP variable_list_sp;
2176254721Semaste                                                bool get_function_vars = true;
2177254721Semaste                                                if (sc->block)
2178254721Semaste                                                {
2179254721Semaste                                                    Block *inline_block = sc->block->GetContainingInlinedBlock ();
2180254721Semaste
2181254721Semaste                                                    if (inline_block)
2182254721Semaste                                                    {
2183254721Semaste                                                        get_function_vars = false;
2184254721Semaste                                                        inline_info = sc->block->GetInlinedFunctionInfo();
2185254721Semaste                                                        if (inline_info)
2186254721Semaste                                                            variable_list_sp = inline_block->GetBlockVariableList (true);
2187254721Semaste                                                    }
2188254721Semaste                                                }
2189254721Semaste
2190254721Semaste                                                if (get_function_vars)
2191254721Semaste                                                {
2192254721Semaste                                                    variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2193254721Semaste                                                }
2194254721Semaste
2195254721Semaste                                                if (inline_info)
2196254721Semaste                                                {
2197254721Semaste                                                    s.PutCString (cstr);
2198254721Semaste                                                    s.PutCString (" [inlined] ");
2199254721Semaste                                                    cstr = inline_info->GetName().GetCString();
2200254721Semaste                                                }
2201254721Semaste
2202254721Semaste                                                VariableList args;
2203254721Semaste                                                if (variable_list_sp)
2204254721Semaste                                                    variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
2205254721Semaste                                                if (args.GetSize() > 0)
2206254721Semaste                                                {
2207254721Semaste                                                    const char *open_paren = strchr (cstr, '(');
2208254721Semaste                                                    const char *close_paren = NULL;
2209254721Semaste                                                    if (open_paren)
2210254721Semaste                                                    {
2211254721Semaste                                                        if (IsToken (open_paren, "(anonymous namespace)"))
2212254721Semaste                                                        {
2213254721Semaste                                                            open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2214254721Semaste                                                            if (open_paren)
2215254721Semaste                                                                close_paren = strchr (open_paren, ')');
2216254721Semaste                                                        }
2217254721Semaste                                                        else
2218254721Semaste                                                            close_paren = strchr (open_paren, ')');
2219254721Semaste                                                    }
2220254721Semaste
2221254721Semaste                                                    if (open_paren)
2222254721Semaste                                                        s.Write(cstr, open_paren - cstr + 1);
2223254721Semaste                                                    else
2224254721Semaste                                                    {
2225254721Semaste                                                        s.PutCString (cstr);
2226254721Semaste                                                        s.PutChar ('(');
2227254721Semaste                                                    }
2228254721Semaste                                                    const size_t num_args = args.GetSize();
2229254721Semaste                                                    for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2230254721Semaste                                                    {
2231254721Semaste                                                        VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2232254721Semaste                                                        ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
2233254721Semaste                                                        const char *var_name = var_value_sp->GetName().GetCString();
2234254721Semaste                                                        const char *var_value = var_value_sp->GetValueAsCString();
2235254721Semaste                                                        if (arg_idx > 0)
2236254721Semaste                                                            s.PutCString (", ");
2237254721Semaste                                                        if (var_value_sp->GetError().Success())
2238254721Semaste                                                        {
2239254721Semaste                                                            if (var_value)
2240254721Semaste                                                                s.Printf ("%s=%s", var_name, var_value);
2241254721Semaste                                                            else
2242254721Semaste                                                                s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2243254721Semaste                                                        }
2244254721Semaste                                                        else
2245254721Semaste                                                            s.Printf ("%s=<unavailable>", var_name);
2246254721Semaste                                                    }
2247254721Semaste
2248254721Semaste                                                    if (close_paren)
2249254721Semaste                                                        s.PutCString (close_paren);
2250254721Semaste                                                    else
2251254721Semaste                                                        s.PutChar(')');
2252254721Semaste
2253254721Semaste                                                }
2254254721Semaste                                                else
2255254721Semaste                                                {
2256254721Semaste                                                    s.PutCString(cstr);
2257254721Semaste                                                }
2258254721Semaste                                            }
2259254721Semaste                                        }
2260254721Semaste                                        else if (sc->symbol)
2261254721Semaste                                        {
2262254721Semaste                                            cstr = sc->symbol->GetName().AsCString (NULL);
2263254721Semaste                                            if (cstr)
2264254721Semaste                                            {
2265254721Semaste                                                s.PutCString(cstr);
2266254721Semaste                                                var_success = true;
2267254721Semaste                                            }
2268254721Semaste                                        }
2269254721Semaste                                    }
2270254721Semaste                                    else if (IsToken (var_name_begin, "addr-offset}"))
2271254721Semaste                                    {
2272254721Semaste                                        var_success = addr != NULL;
2273254721Semaste                                        if (var_success)
2274254721Semaste                                        {
2275254721Semaste                                            format_addr = *addr;
2276254721Semaste                                            calculate_format_addr_function_offset = true;
2277254721Semaste                                        }
2278254721Semaste                                    }
2279254721Semaste                                    else if (IsToken (var_name_begin, "line-offset}"))
2280254721Semaste                                    {
2281254721Semaste                                        var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2282254721Semaste                                        if (var_success)
2283254721Semaste                                        {
2284254721Semaste                                            format_addr = sc->line_entry.range.GetBaseAddress();
2285254721Semaste                                            calculate_format_addr_function_offset = true;
2286254721Semaste                                        }
2287254721Semaste                                    }
2288254721Semaste                                    else if (IsToken (var_name_begin, "pc-offset}"))
2289254721Semaste                                    {
2290254721Semaste                                        StackFrame *frame = exe_ctx->GetFramePtr();
2291254721Semaste                                        var_success = frame != NULL;
2292254721Semaste                                        if (var_success)
2293254721Semaste                                        {
2294254721Semaste                                            format_addr = frame->GetFrameCodeAddress();
2295254721Semaste                                            calculate_format_addr_function_offset = true;
2296254721Semaste                                        }
2297254721Semaste                                    }
2298254721Semaste                                }
2299254721Semaste                            }
2300254721Semaste                            break;
2301254721Semaste
2302254721Semaste                        case 'l':
2303254721Semaste                            if (IsToken (var_name_begin, "line."))
2304254721Semaste                            {
2305254721Semaste                                if (sc && sc->line_entry.IsValid())
2306254721Semaste                                {
2307254721Semaste                                    var_name_begin += ::strlen ("line.");
2308254721Semaste                                    if (IsToken (var_name_begin, "file."))
2309254721Semaste                                    {
2310254721Semaste                                        var_name_begin += ::strlen ("file.");
2311254721Semaste
2312254721Semaste                                        if (IsToken (var_name_begin, "basename}"))
2313254721Semaste                                        {
2314254721Semaste                                            format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
2315263363Semaste                                            var_success = (bool)format_file_spec;
2316254721Semaste                                        }
2317254721Semaste                                        else if (IsToken (var_name_begin, "fullpath}"))
2318254721Semaste                                        {
2319254721Semaste                                            format_file_spec = sc->line_entry.file;
2320263363Semaste                                            var_success = (bool)format_file_spec;
2321254721Semaste                                        }
2322254721Semaste                                    }
2323254721Semaste                                    else if (IsTokenWithFormat (var_name_begin, "number", token_format, "%" PRIu64, exe_ctx, sc))
2324254721Semaste                                    {
2325254721Semaste                                        var_success = true;
2326254721Semaste                                        s.Printf(token_format.c_str(), (uint64_t)sc->line_entry.line);
2327254721Semaste                                    }
2328254721Semaste                                    else if ((IsToken (var_name_begin, "start-addr}")) ||
2329254721Semaste                                             (IsToken (var_name_begin, "end-addr}")))
2330254721Semaste                                    {
2331254721Semaste                                        var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2332254721Semaste                                        if (var_success)
2333254721Semaste                                        {
2334254721Semaste                                            format_addr = sc->line_entry.range.GetBaseAddress();
2335254721Semaste                                            if (var_name_begin[0] == 'e')
2336254721Semaste                                                format_addr.Slide (sc->line_entry.range.GetByteSize());
2337254721Semaste                                        }
2338254721Semaste                                    }
2339254721Semaste                                }
2340254721Semaste                            }
2341254721Semaste                            break;
2342254721Semaste                        }
2343254721Semaste
2344254721Semaste                        if (var_success)
2345254721Semaste                        {
2346254721Semaste                            // If format addr is valid, then we need to print an address
2347254721Semaste                            if (reg_num != LLDB_INVALID_REGNUM)
2348254721Semaste                            {
2349254721Semaste                                StackFrame *frame = exe_ctx->GetFramePtr();
2350254721Semaste                                // We have a register value to display...
2351254721Semaste                                if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2352254721Semaste                                {
2353254721Semaste                                    format_addr = frame->GetFrameCodeAddress();
2354254721Semaste                                }
2355254721Semaste                                else
2356254721Semaste                                {
2357254721Semaste                                    if (reg_ctx == NULL)
2358254721Semaste                                        reg_ctx = frame->GetRegisterContext().get();
2359254721Semaste
2360254721Semaste                                    if (reg_ctx)
2361254721Semaste                                    {
2362254721Semaste                                        if (reg_kind != kNumRegisterKinds)
2363254721Semaste                                            reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2364254721Semaste                                        reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2365254721Semaste                                        var_success = reg_info != NULL;
2366254721Semaste                                    }
2367254721Semaste                                }
2368254721Semaste                            }
2369254721Semaste
2370254721Semaste                            if (reg_info != NULL)
2371254721Semaste                            {
2372254721Semaste                                RegisterValue reg_value;
2373254721Semaste                                var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2374254721Semaste                                if (var_success)
2375254721Semaste                                {
2376254721Semaste                                    reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
2377254721Semaste                                }
2378254721Semaste                            }
2379254721Semaste
2380254721Semaste                            if (format_file_spec)
2381254721Semaste                            {
2382254721Semaste                                s << format_file_spec;
2383254721Semaste                            }
2384254721Semaste
2385254721Semaste                            // If format addr is valid, then we need to print an address
2386254721Semaste                            if (format_addr.IsValid())
2387254721Semaste                            {
2388254721Semaste                                var_success = false;
2389254721Semaste
2390254721Semaste                                if (calculate_format_addr_function_offset)
2391254721Semaste                                {
2392254721Semaste                                    Address func_addr;
2393254721Semaste
2394254721Semaste                                    if (sc)
2395254721Semaste                                    {
2396254721Semaste                                        if (sc->function)
2397254721Semaste                                        {
2398254721Semaste                                            func_addr = sc->function->GetAddressRange().GetBaseAddress();
2399254721Semaste                                            if (sc->block)
2400254721Semaste                                            {
2401254721Semaste                                                // Check to make sure we aren't in an inline
2402254721Semaste                                                // function. If we are, use the inline block
2403254721Semaste                                                // range that contains "format_addr" since
2404254721Semaste                                                // blocks can be discontiguous.
2405254721Semaste                                                Block *inline_block = sc->block->GetContainingInlinedBlock ();
2406254721Semaste                                                AddressRange inline_range;
2407254721Semaste                                                if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2408254721Semaste                                                    func_addr = inline_range.GetBaseAddress();
2409254721Semaste                                            }
2410254721Semaste                                        }
2411254721Semaste                                        else if (sc->symbol && sc->symbol->ValueIsAddress())
2412254721Semaste                                            func_addr = sc->symbol->GetAddress();
2413254721Semaste                                    }
2414254721Semaste
2415254721Semaste                                    if (func_addr.IsValid())
2416254721Semaste                                    {
2417254721Semaste                                        if (func_addr.GetSection() == format_addr.GetSection())
2418254721Semaste                                        {
2419254721Semaste                                            addr_t func_file_addr = func_addr.GetFileAddress();
2420254721Semaste                                            addr_t addr_file_addr = format_addr.GetFileAddress();
2421254721Semaste                                            if (addr_file_addr > func_file_addr)
2422254721Semaste                                                s.Printf(" + %" PRIu64, addr_file_addr - func_file_addr);
2423254721Semaste                                            else if (addr_file_addr < func_file_addr)
2424254721Semaste                                                s.Printf(" - %" PRIu64, func_file_addr - addr_file_addr);
2425254721Semaste                                            var_success = true;
2426254721Semaste                                        }
2427254721Semaste                                        else
2428254721Semaste                                        {
2429254721Semaste                                            Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2430254721Semaste                                            if (target)
2431254721Semaste                                            {
2432254721Semaste                                                addr_t func_load_addr = func_addr.GetLoadAddress (target);
2433254721Semaste                                                addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2434254721Semaste                                                if (addr_load_addr > func_load_addr)
2435254721Semaste                                                    s.Printf(" + %" PRIu64, addr_load_addr - func_load_addr);
2436254721Semaste                                                else if (addr_load_addr < func_load_addr)
2437254721Semaste                                                    s.Printf(" - %" PRIu64, func_load_addr - addr_load_addr);
2438254721Semaste                                                var_success = true;
2439254721Semaste                                            }
2440254721Semaste                                        }
2441254721Semaste                                    }
2442254721Semaste                                }
2443254721Semaste                                else
2444254721Semaste                                {
2445254721Semaste                                    Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2446254721Semaste                                    addr_t vaddr = LLDB_INVALID_ADDRESS;
2447254721Semaste                                    if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2448254721Semaste                                        vaddr = format_addr.GetLoadAddress (target);
2449254721Semaste                                    if (vaddr == LLDB_INVALID_ADDRESS)
2450254721Semaste                                        vaddr = format_addr.GetFileAddress ();
2451254721Semaste
2452254721Semaste                                    if (vaddr != LLDB_INVALID_ADDRESS)
2453254721Semaste                                    {
2454254721Semaste                                        int addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
2455254721Semaste                                        if (addr_width == 0)
2456254721Semaste                                            addr_width = 16;
2457254721Semaste                                        s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
2458254721Semaste                                        var_success = true;
2459254721Semaste                                    }
2460254721Semaste                                }
2461254721Semaste                            }
2462254721Semaste                        }
2463254721Semaste
2464254721Semaste                        if (var_success == false)
2465254721Semaste                            success = false;
2466254721Semaste                    }
2467254721Semaste                    p = var_name_end;
2468254721Semaste                }
2469254721Semaste                else
2470254721Semaste                    break;
2471254721Semaste            }
2472254721Semaste            else
2473254721Semaste            {
2474254721Semaste                // We got a dollar sign with no '{' after it, it must just be a dollar sign
2475254721Semaste                s.PutChar(*p);
2476254721Semaste            }
2477254721Semaste        }
2478254721Semaste        else if (*p == '\\')
2479254721Semaste        {
2480254721Semaste            ++p; // skip the slash
2481254721Semaste            switch (*p)
2482254721Semaste            {
2483254721Semaste            case 'a': s.PutChar ('\a'); break;
2484254721Semaste            case 'b': s.PutChar ('\b'); break;
2485254721Semaste            case 'f': s.PutChar ('\f'); break;
2486254721Semaste            case 'n': s.PutChar ('\n'); break;
2487254721Semaste            case 'r': s.PutChar ('\r'); break;
2488254721Semaste            case 't': s.PutChar ('\t'); break;
2489254721Semaste            case 'v': s.PutChar ('\v'); break;
2490254721Semaste            case '\'': s.PutChar ('\''); break;
2491254721Semaste            case '\\': s.PutChar ('\\'); break;
2492254721Semaste            case '0':
2493254721Semaste                // 1 to 3 octal chars
2494254721Semaste                {
2495254721Semaste                    // Make a string that can hold onto the initial zero char,
2496254721Semaste                    // up to 3 octal digits, and a terminating NULL.
2497254721Semaste                    char oct_str[5] = { 0, 0, 0, 0, 0 };
2498254721Semaste
2499254721Semaste                    int i;
2500254721Semaste                    for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2501254721Semaste                        oct_str[i] = p[i];
2502254721Semaste
2503254721Semaste                    // We don't want to consume the last octal character since
2504254721Semaste                    // the main for loop will do this for us, so we advance p by
2505254721Semaste                    // one less than i (even if i is zero)
2506254721Semaste                    p += i - 1;
2507254721Semaste                    unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2508254721Semaste                    if (octal_value <= UINT8_MAX)
2509254721Semaste                    {
2510254721Semaste                        s.PutChar((char)octal_value);
2511254721Semaste                    }
2512254721Semaste                }
2513254721Semaste                break;
2514254721Semaste
2515254721Semaste            case 'x':
2516254721Semaste                // hex number in the format
2517254721Semaste                if (isxdigit(p[1]))
2518254721Semaste                {
2519254721Semaste                    ++p;    // Skip the 'x'
2520254721Semaste
2521254721Semaste                    // Make a string that can hold onto two hex chars plus a
2522254721Semaste                    // NULL terminator
2523254721Semaste                    char hex_str[3] = { 0,0,0 };
2524254721Semaste                    hex_str[0] = *p;
2525254721Semaste                    if (isxdigit(p[1]))
2526254721Semaste                    {
2527254721Semaste                        ++p; // Skip the first of the two hex chars
2528254721Semaste                        hex_str[1] = *p;
2529254721Semaste                    }
2530254721Semaste
2531254721Semaste                    unsigned long hex_value = strtoul (hex_str, NULL, 16);
2532254721Semaste                    if (hex_value <= UINT8_MAX)
2533254721Semaste                        s.PutChar ((char)hex_value);
2534254721Semaste                }
2535254721Semaste                else
2536254721Semaste                {
2537254721Semaste                    s.PutChar('x');
2538254721Semaste                }
2539254721Semaste                break;
2540254721Semaste
2541254721Semaste            default:
2542254721Semaste                // Just desensitize any other character by just printing what
2543254721Semaste                // came after the '\'
2544254721Semaste                s << *p;
2545254721Semaste                break;
2546254721Semaste
2547254721Semaste            }
2548254721Semaste
2549254721Semaste        }
2550254721Semaste    }
2551254721Semaste    if (end)
2552254721Semaste        *end = p;
2553254721Semaste    return success;
2554254721Semaste}
2555254721Semaste
2556254721Semastebool
2557254721SemasteDebugger::FormatPrompt
2558254721Semaste(
2559254721Semaste    const char *format,
2560254721Semaste    const SymbolContext *sc,
2561254721Semaste    const ExecutionContext *exe_ctx,
2562254721Semaste    const Address *addr,
2563254721Semaste    Stream &s,
2564254721Semaste    ValueObject* valobj
2565254721Semaste)
2566254721Semaste{
2567254721Semaste    bool use_color = exe_ctx ? exe_ctx->GetTargetRef().GetDebugger().GetUseColor() : true;
2568254721Semaste    std::string format_str = lldb_utility::ansi::FormatAnsiTerminalCodes (format, use_color);
2569254721Semaste    if (format_str.length())
2570254721Semaste        format = format_str.c_str();
2571254721Semaste    return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, valobj);
2572254721Semaste}
2573254721Semaste
2574254721Semastevoid
2575254721SemasteDebugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2576254721Semaste{
2577254721Semaste    // For simplicity's sake, I am not going to deal with how to close down any
2578254721Semaste    // open logging streams, I just redirect everything from here on out to the
2579254721Semaste    // callback.
2580254721Semaste    m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2581254721Semaste}
2582254721Semaste
2583254721Semastebool
2584254721SemasteDebugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2585254721Semaste{
2586254721Semaste    Log::Callbacks log_callbacks;
2587254721Semaste
2588254721Semaste    StreamSP log_stream_sp;
2589254721Semaste    if (m_log_callback_stream_sp)
2590254721Semaste    {
2591254721Semaste        log_stream_sp = m_log_callback_stream_sp;
2592254721Semaste        // For now when using the callback mode you always get thread & timestamp.
2593254721Semaste        log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2594254721Semaste    }
2595254721Semaste    else if (log_file == NULL || *log_file == '\0')
2596254721Semaste    {
2597269024Semaste        log_stream_sp = GetOutputFile();
2598254721Semaste    }
2599254721Semaste    else
2600254721Semaste    {
2601254721Semaste        LogStreamMap::iterator pos = m_log_streams.find(log_file);
2602254721Semaste        if (pos != m_log_streams.end())
2603254721Semaste            log_stream_sp = pos->second.lock();
2604254721Semaste        if (!log_stream_sp)
2605254721Semaste        {
2606254721Semaste            log_stream_sp.reset (new StreamFile (log_file));
2607254721Semaste            m_log_streams[log_file] = log_stream_sp;
2608254721Semaste        }
2609254721Semaste    }
2610254721Semaste    assert (log_stream_sp.get());
2611254721Semaste
2612254721Semaste    if (log_options == 0)
2613254721Semaste        log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2614254721Semaste
2615254721Semaste    if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
2616254721Semaste    {
2617254721Semaste        log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2618254721Semaste        return true;
2619254721Semaste    }
2620254721Semaste    else
2621254721Semaste    {
2622254721Semaste        LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2623254721Semaste        if (log_channel_sp)
2624254721Semaste        {
2625254721Semaste            if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2626254721Semaste            {
2627254721Semaste                return true;
2628254721Semaste            }
2629254721Semaste            else
2630254721Semaste            {
2631254721Semaste                error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2632254721Semaste                return false;
2633254721Semaste            }
2634254721Semaste        }
2635254721Semaste        else
2636254721Semaste        {
2637254721Semaste            error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2638254721Semaste            return false;
2639254721Semaste        }
2640254721Semaste    }
2641254721Semaste    return false;
2642254721Semaste}
2643254721Semaste
2644254721SemasteSourceManager &
2645254721SemasteDebugger::GetSourceManager ()
2646254721Semaste{
2647254721Semaste    if (m_source_manager_ap.get() == NULL)
2648254721Semaste        m_source_manager_ap.reset (new SourceManager (shared_from_this()));
2649254721Semaste    return *m_source_manager_ap;
2650254721Semaste}
2651254721Semaste
2652254721Semaste
2653269024Semaste
2654269024Semaste// This function handles events that were broadcast by the process.
2655269024Semastevoid
2656269024SemasteDebugger::HandleBreakpointEvent (const EventSP &event_sp)
2657269024Semaste{
2658269024Semaste    using namespace lldb;
2659269024Semaste    const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
2660269024Semaste
2661269024Semaste//    if (event_type & eBreakpointEventTypeAdded
2662269024Semaste//        || event_type & eBreakpointEventTypeRemoved
2663269024Semaste//        || event_type & eBreakpointEventTypeEnabled
2664269024Semaste//        || event_type & eBreakpointEventTypeDisabled
2665269024Semaste//        || event_type & eBreakpointEventTypeCommandChanged
2666269024Semaste//        || event_type & eBreakpointEventTypeConditionChanged
2667269024Semaste//        || event_type & eBreakpointEventTypeIgnoreChanged
2668269024Semaste//        || event_type & eBreakpointEventTypeLocationsResolved)
2669269024Semaste//    {
2670269024Semaste//        // Don't do anything about these events, since the breakpoint commands already echo these actions.
2671269024Semaste//    }
2672269024Semaste//
2673269024Semaste    if (event_type & eBreakpointEventTypeLocationsAdded)
2674269024Semaste    {
2675269024Semaste        uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
2676269024Semaste        if (num_new_locations > 0)
2677269024Semaste        {
2678269024Semaste            BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
2679269024Semaste            StreamFileSP output_sp (GetOutputFile());
2680269024Semaste            if (output_sp)
2681269024Semaste            {
2682269024Semaste                output_sp->Printf("%d location%s added to breakpoint %d\n",
2683269024Semaste                                  num_new_locations,
2684269024Semaste                                  num_new_locations == 1 ? "" : "s",
2685269024Semaste                                  breakpoint->GetID());
2686269024Semaste                RefreshTopIOHandler();
2687269024Semaste            }
2688269024Semaste        }
2689269024Semaste    }
2690269024Semaste//    else if (event_type & eBreakpointEventTypeLocationsRemoved)
2691269024Semaste//    {
2692269024Semaste//        // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
2693269024Semaste//    }
2694269024Semaste//    else if (event_type & eBreakpointEventTypeLocationsResolved)
2695269024Semaste//    {
2696269024Semaste//        // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
2697269024Semaste//    }
2698269024Semaste}
2699269024Semaste
2700269024Semastesize_t
2701269024SemasteDebugger::GetProcessSTDOUT (Process *process, Stream *stream)
2702269024Semaste{
2703269024Semaste    size_t total_bytes = 0;
2704269024Semaste    if (stream == NULL)
2705269024Semaste        stream = GetOutputFile().get();
2706269024Semaste
2707269024Semaste    if (stream)
2708269024Semaste    {
2709269024Semaste        //  The process has stuff waiting for stdout; get it and write it out to the appropriate place.
2710269024Semaste        if (process == NULL)
2711269024Semaste        {
2712269024Semaste            TargetSP target_sp = GetTargetList().GetSelectedTarget();
2713269024Semaste            if (target_sp)
2714269024Semaste                process = target_sp->GetProcessSP().get();
2715269024Semaste        }
2716269024Semaste        if (process)
2717269024Semaste        {
2718269024Semaste            Error error;
2719269024Semaste            size_t len;
2720269024Semaste            char stdio_buffer[1024];
2721269024Semaste            while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2722269024Semaste            {
2723269024Semaste                stream->Write(stdio_buffer, len);
2724269024Semaste                total_bytes += len;
2725269024Semaste            }
2726269024Semaste        }
2727269024Semaste        stream->Flush();
2728269024Semaste    }
2729269024Semaste    return total_bytes;
2730269024Semaste}
2731269024Semaste
2732269024Semastesize_t
2733269024SemasteDebugger::GetProcessSTDERR (Process *process, Stream *stream)
2734269024Semaste{
2735269024Semaste    size_t total_bytes = 0;
2736269024Semaste    if (stream == NULL)
2737269024Semaste        stream = GetOutputFile().get();
2738269024Semaste
2739269024Semaste    if (stream)
2740269024Semaste    {
2741269024Semaste        //  The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2742269024Semaste        if (process == NULL)
2743269024Semaste        {
2744269024Semaste            TargetSP target_sp = GetTargetList().GetSelectedTarget();
2745269024Semaste            if (target_sp)
2746269024Semaste                process = target_sp->GetProcessSP().get();
2747269024Semaste        }
2748269024Semaste        if (process)
2749269024Semaste        {
2750269024Semaste            Error error;
2751269024Semaste            size_t len;
2752269024Semaste            char stdio_buffer[1024];
2753269024Semaste            while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2754269024Semaste            {
2755269024Semaste                stream->Write(stdio_buffer, len);
2756269024Semaste                total_bytes += len;
2757269024Semaste            }
2758269024Semaste        }
2759269024Semaste        stream->Flush();
2760269024Semaste    }
2761269024Semaste    return total_bytes;
2762269024Semaste}
2763269024Semaste
2764269024Semaste// This function handles events that were broadcast by the process.
2765269024Semastevoid
2766269024SemasteDebugger::HandleProcessEvent (const EventSP &event_sp)
2767269024Semaste{
2768269024Semaste    using namespace lldb;
2769269024Semaste    const uint32_t event_type = event_sp->GetType();
2770269024Semaste    ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
2771269024Semaste
2772269024Semaste    const bool gui_enabled = IsForwardingEvents();
2773269024Semaste    bool top_io_handler_hid = false;
2774269024Semaste    if (gui_enabled == false)
2775269024Semaste        top_io_handler_hid = HideTopIOHandler();
2776269024Semaste
2777269024Semaste    assert (process_sp);
2778269024Semaste
2779269024Semaste    if (event_type & Process::eBroadcastBitSTDOUT)
2780269024Semaste    {
2781269024Semaste        // The process has stdout available, get it and write it out to the
2782269024Semaste        // appropriate place.
2783269024Semaste        if (top_io_handler_hid)
2784269024Semaste            GetProcessSTDOUT (process_sp.get(), NULL);
2785269024Semaste    }
2786269024Semaste    else if (event_type & Process::eBroadcastBitSTDERR)
2787269024Semaste    {
2788269024Semaste        // The process has stderr available, get it and write it out to the
2789269024Semaste        // appropriate place.
2790269024Semaste        if (top_io_handler_hid)
2791269024Semaste            GetProcessSTDERR (process_sp.get(), NULL);
2792269024Semaste    }
2793269024Semaste    else if (event_type & Process::eBroadcastBitStateChanged)
2794269024Semaste    {
2795269024Semaste        // Drain all stout and stderr so we don't see any output come after
2796269024Semaste        // we print our prompts
2797269024Semaste        if (top_io_handler_hid)
2798269024Semaste        {
2799269024Semaste            StreamFileSP stream_sp (GetOutputFile());
2800269024Semaste            GetProcessSTDOUT (process_sp.get(), stream_sp.get());
2801269024Semaste            GetProcessSTDERR (process_sp.get(), NULL);
2802269024Semaste            // Something changed in the process;  get the event and report the process's current status and location to
2803269024Semaste            // the user.
2804269024Semaste            StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
2805269024Semaste            if (event_state == eStateInvalid)
2806269024Semaste                return;
2807269024Semaste
2808269024Semaste            switch (event_state)
2809269024Semaste            {
2810269024Semaste                case eStateInvalid:
2811269024Semaste                case eStateUnloaded:
2812269024Semaste                case eStateConnected:
2813269024Semaste                case eStateAttaching:
2814269024Semaste                case eStateLaunching:
2815269024Semaste                case eStateStepping:
2816269024Semaste                case eStateDetached:
2817269024Semaste                    {
2818269024Semaste                        stream_sp->Printf("Process %" PRIu64 " %s\n",
2819269024Semaste                                          process_sp->GetID(),
2820269024Semaste                                          StateAsCString (event_state));
2821269024Semaste                    }
2822269024Semaste                    break;
2823269024Semaste
2824269024Semaste                case eStateRunning:
2825269024Semaste                    // Don't be chatty when we run...
2826269024Semaste                    break;
2827269024Semaste
2828269024Semaste                case eStateExited:
2829269024Semaste                    process_sp->GetStatus(*stream_sp);
2830269024Semaste                    break;
2831269024Semaste
2832269024Semaste                case eStateStopped:
2833269024Semaste                case eStateCrashed:
2834269024Semaste                case eStateSuspended:
2835269024Semaste                    // Make sure the program hasn't been auto-restarted:
2836269024Semaste                    if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
2837269024Semaste                    {
2838269024Semaste                        size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
2839269024Semaste                        if (num_reasons > 0)
2840269024Semaste                        {
2841269024Semaste                            // FIXME: Do we want to report this, or would that just be annoyingly chatty?
2842269024Semaste                            if (num_reasons == 1)
2843269024Semaste                            {
2844269024Semaste                                const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
2845269024Semaste                                stream_sp->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
2846269024Semaste                                                  process_sp->GetID(),
2847269024Semaste                                                  reason ? reason : "<UNKNOWN REASON>");
2848269024Semaste                            }
2849269024Semaste                            else
2850269024Semaste                            {
2851269024Semaste                                stream_sp->Printf("Process %" PRIu64 " stopped and restarted, reasons:\n",
2852269024Semaste                                                   process_sp->GetID());
2853269024Semaste
2854269024Semaste
2855269024Semaste                                for (size_t i = 0; i < num_reasons; i++)
2856269024Semaste                                {
2857269024Semaste                                    const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
2858269024Semaste                                    stream_sp->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
2859269024Semaste                                }
2860269024Semaste                            }
2861269024Semaste                        }
2862269024Semaste                    }
2863269024Semaste                    else
2864269024Semaste                    {
2865269024Semaste                        // Lock the thread list so it doesn't change on us
2866269024Semaste                        ThreadList &thread_list = process_sp->GetThreadList();
2867269024Semaste                        Mutex::Locker locker (thread_list.GetMutex());
2868269024Semaste
2869269024Semaste                        ThreadSP curr_thread (thread_list.GetSelectedThread());
2870269024Semaste                        ThreadSP thread;
2871269024Semaste                        StopReason curr_thread_stop_reason = eStopReasonInvalid;
2872269024Semaste                        if (curr_thread)
2873269024Semaste                            curr_thread_stop_reason = curr_thread->GetStopReason();
2874269024Semaste                        if (!curr_thread ||
2875269024Semaste                            !curr_thread->IsValid() ||
2876269024Semaste                            curr_thread_stop_reason == eStopReasonInvalid ||
2877269024Semaste                            curr_thread_stop_reason == eStopReasonNone)
2878269024Semaste                        {
2879269024Semaste                            // Prefer a thread that has just completed its plan over another thread as current thread.
2880269024Semaste                            ThreadSP plan_thread;
2881269024Semaste                            ThreadSP other_thread;
2882269024Semaste                            const size_t num_threads = thread_list.GetSize();
2883269024Semaste                            size_t i;
2884269024Semaste                            for (i = 0; i < num_threads; ++i)
2885269024Semaste                            {
2886269024Semaste                                thread = thread_list.GetThreadAtIndex(i);
2887269024Semaste                                StopReason thread_stop_reason = thread->GetStopReason();
2888269024Semaste                                switch (thread_stop_reason)
2889269024Semaste                                {
2890269024Semaste                                    case eStopReasonInvalid:
2891269024Semaste                                    case eStopReasonNone:
2892269024Semaste                                        break;
2893269024Semaste
2894269024Semaste                                    case eStopReasonTrace:
2895269024Semaste                                    case eStopReasonBreakpoint:
2896269024Semaste                                    case eStopReasonWatchpoint:
2897269024Semaste                                    case eStopReasonSignal:
2898269024Semaste                                    case eStopReasonException:
2899269024Semaste                                    case eStopReasonExec:
2900269024Semaste                                    case eStopReasonThreadExiting:
2901269024Semaste                                        if (!other_thread)
2902269024Semaste                                            other_thread = thread;
2903269024Semaste                                        break;
2904269024Semaste                                    case eStopReasonPlanComplete:
2905269024Semaste                                        if (!plan_thread)
2906269024Semaste                                            plan_thread = thread;
2907269024Semaste                                        break;
2908269024Semaste                                }
2909269024Semaste                            }
2910269024Semaste                            if (plan_thread)
2911269024Semaste                                thread_list.SetSelectedThreadByID (plan_thread->GetID());
2912269024Semaste                            else if (other_thread)
2913269024Semaste                                thread_list.SetSelectedThreadByID (other_thread->GetID());
2914269024Semaste                            else
2915269024Semaste                            {
2916269024Semaste                                if (curr_thread && curr_thread->IsValid())
2917269024Semaste                                    thread = curr_thread;
2918269024Semaste                                else
2919269024Semaste                                    thread = thread_list.GetThreadAtIndex(0);
2920269024Semaste
2921269024Semaste                                if (thread)
2922269024Semaste                                    thread_list.SetSelectedThreadByID (thread->GetID());
2923269024Semaste                            }
2924269024Semaste                        }
2925269024Semaste
2926269024Semaste                        if (GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
2927269024Semaste                        {
2928269024Semaste                            const bool only_threads_with_stop_reason = true;
2929269024Semaste                            const uint32_t start_frame = 0;
2930269024Semaste                            const uint32_t num_frames = 1;
2931269024Semaste                            const uint32_t num_frames_with_source = 1;
2932269024Semaste                            process_sp->GetStatus(*stream_sp);
2933269024Semaste                            process_sp->GetThreadStatus (*stream_sp,
2934269024Semaste                                                         only_threads_with_stop_reason,
2935269024Semaste                                                         start_frame,
2936269024Semaste                                                         num_frames,
2937269024Semaste                                                         num_frames_with_source);
2938269024Semaste                        }
2939269024Semaste                        else
2940269024Semaste                        {
2941269024Semaste                            uint32_t target_idx = GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
2942269024Semaste                            if (target_idx != UINT32_MAX)
2943269024Semaste                                stream_sp->Printf ("Target %d: (", target_idx);
2944269024Semaste                            else
2945269024Semaste                                stream_sp->Printf ("Target <unknown index>: (");
2946269024Semaste                            process_sp->GetTarget().Dump (stream_sp.get(), eDescriptionLevelBrief);
2947269024Semaste                            stream_sp->Printf (") stopped.\n");
2948269024Semaste                        }
2949269024Semaste                    }
2950269024Semaste                    break;
2951269024Semaste            }
2952269024Semaste        }
2953269024Semaste    }
2954269024Semaste
2955269024Semaste    if (top_io_handler_hid)
2956269024Semaste        RefreshTopIOHandler();
2957269024Semaste}
2958269024Semaste
2959269024Semastevoid
2960269024SemasteDebugger::HandleThreadEvent (const EventSP &event_sp)
2961269024Semaste{
2962269024Semaste    // At present the only thread event we handle is the Frame Changed event,
2963269024Semaste    // and all we do for that is just reprint the thread status for that thread.
2964269024Semaste    using namespace lldb;
2965269024Semaste    const uint32_t event_type = event_sp->GetType();
2966269024Semaste    if (event_type == Thread::eBroadcastBitStackChanged   ||
2967269024Semaste        event_type == Thread::eBroadcastBitThreadSelected )
2968269024Semaste    {
2969269024Semaste        ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
2970269024Semaste        if (thread_sp)
2971269024Semaste        {
2972269024Semaste            HideTopIOHandler();
2973269024Semaste            StreamFileSP stream_sp (GetOutputFile());
2974269024Semaste            thread_sp->GetStatus(*stream_sp, 0, 1, 1);
2975269024Semaste            RefreshTopIOHandler();
2976269024Semaste        }
2977269024Semaste    }
2978269024Semaste}
2979269024Semaste
2980269024Semastebool
2981269024SemasteDebugger::IsForwardingEvents ()
2982269024Semaste{
2983269024Semaste    return (bool)m_forward_listener_sp;
2984269024Semaste}
2985269024Semaste
2986269024Semastevoid
2987269024SemasteDebugger::EnableForwardEvents (const ListenerSP &listener_sp)
2988269024Semaste{
2989269024Semaste    m_forward_listener_sp = listener_sp;
2990269024Semaste}
2991269024Semaste
2992269024Semastevoid
2993269024SemasteDebugger::CancelForwardEvents (const ListenerSP &listener_sp)
2994269024Semaste{
2995269024Semaste    m_forward_listener_sp.reset();
2996269024Semaste}
2997269024Semaste
2998269024Semaste
2999269024Semastevoid
3000269024SemasteDebugger::DefaultEventHandler()
3001269024Semaste{
3002269024Semaste    Listener& listener(GetListener());
3003269024Semaste    ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
3004269024Semaste    ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
3005269024Semaste    ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
3006269024Semaste    BroadcastEventSpec target_event_spec (broadcaster_class_target,
3007269024Semaste                                          Target::eBroadcastBitBreakpointChanged);
3008269024Semaste
3009269024Semaste    BroadcastEventSpec process_event_spec (broadcaster_class_process,
3010269024Semaste                                           Process::eBroadcastBitStateChanged   |
3011269024Semaste                                           Process::eBroadcastBitSTDOUT         |
3012269024Semaste                                           Process::eBroadcastBitSTDERR);
3013269024Semaste
3014269024Semaste    BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
3015269024Semaste                                          Thread::eBroadcastBitStackChanged     |
3016269024Semaste                                          Thread::eBroadcastBitThreadSelected   );
3017269024Semaste
3018269024Semaste    listener.StartListeningForEventSpec (*this, target_event_spec);
3019269024Semaste    listener.StartListeningForEventSpec (*this, process_event_spec);
3020269024Semaste    listener.StartListeningForEventSpec (*this, thread_event_spec);
3021269024Semaste    listener.StartListeningForEvents (m_command_interpreter_ap.get(),
3022269024Semaste                                      CommandInterpreter::eBroadcastBitQuitCommandReceived      |
3023269024Semaste                                      CommandInterpreter::eBroadcastBitAsynchronousOutputData   |
3024269024Semaste                                      CommandInterpreter::eBroadcastBitAsynchronousErrorData    );
3025269024Semaste
3026269024Semaste    bool done = false;
3027269024Semaste    while (!done)
3028269024Semaste    {
3029269024Semaste//        Mutex::Locker locker;
3030269024Semaste//        if (locker.TryLock(m_input_reader_stack.GetMutex()))
3031269024Semaste//        {
3032269024Semaste//            if (m_input_reader_stack.IsEmpty())
3033269024Semaste//                break;
3034269024Semaste//        }
3035269024Semaste//
3036269024Semaste        EventSP event_sp;
3037269024Semaste        if (listener.WaitForEvent(NULL, event_sp))
3038269024Semaste        {
3039269024Semaste            if (event_sp)
3040269024Semaste            {
3041269024Semaste                Broadcaster *broadcaster = event_sp->GetBroadcaster();
3042269024Semaste                if (broadcaster)
3043269024Semaste                {
3044269024Semaste                    uint32_t event_type = event_sp->GetType();
3045269024Semaste                    ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
3046269024Semaste                    if (broadcaster_class == broadcaster_class_process)
3047269024Semaste                    {
3048269024Semaste                        HandleProcessEvent (event_sp);
3049269024Semaste                    }
3050269024Semaste                    else if (broadcaster_class == broadcaster_class_target)
3051269024Semaste                    {
3052269024Semaste                        if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
3053269024Semaste                        {
3054269024Semaste                            HandleBreakpointEvent (event_sp);
3055269024Semaste                        }
3056269024Semaste                    }
3057269024Semaste                    else if (broadcaster_class == broadcaster_class_thread)
3058269024Semaste                    {
3059269024Semaste                        HandleThreadEvent (event_sp);
3060269024Semaste                    }
3061269024Semaste                    else if (broadcaster == m_command_interpreter_ap.get())
3062269024Semaste                    {
3063269024Semaste                        if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
3064269024Semaste                        {
3065269024Semaste                            done = true;
3066269024Semaste                        }
3067269024Semaste                        else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
3068269024Semaste                        {
3069269024Semaste                            const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3070269024Semaste                            if (data && data[0])
3071269024Semaste                            {
3072269024Semaste                                StreamFileSP error_sp (GetErrorFile());
3073269024Semaste                                if (error_sp)
3074269024Semaste                                {
3075269024Semaste                                    HideTopIOHandler();
3076269024Semaste                                    error_sp->PutCString(data);
3077269024Semaste                                    error_sp->Flush();
3078269024Semaste                                    RefreshTopIOHandler();
3079269024Semaste                                }
3080269024Semaste                            }
3081269024Semaste                        }
3082269024Semaste                        else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
3083269024Semaste                        {
3084269024Semaste                            const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3085269024Semaste                            if (data && data[0])
3086269024Semaste                            {
3087269024Semaste                                StreamFileSP output_sp (GetOutputFile());
3088269024Semaste                                if (output_sp)
3089269024Semaste                                {
3090269024Semaste                                    HideTopIOHandler();
3091269024Semaste                                    output_sp->PutCString(data);
3092269024Semaste                                    output_sp->Flush();
3093269024Semaste                                    RefreshTopIOHandler();
3094269024Semaste                                }
3095269024Semaste                            }
3096269024Semaste                        }
3097269024Semaste                    }
3098269024Semaste                }
3099269024Semaste
3100269024Semaste                if (m_forward_listener_sp)
3101269024Semaste                    m_forward_listener_sp->AddEvent(event_sp);
3102269024Semaste            }
3103269024Semaste        }
3104269024Semaste    }
3105269024Semaste}
3106269024Semaste
3107269024Semastelldb::thread_result_t
3108269024SemasteDebugger::EventHandlerThread (lldb::thread_arg_t arg)
3109269024Semaste{
3110269024Semaste    ((Debugger *)arg)->DefaultEventHandler();
3111269024Semaste    return NULL;
3112269024Semaste}
3113269024Semaste
3114269024Semastebool
3115269024SemasteDebugger::StartEventHandlerThread()
3116269024Semaste{
3117269024Semaste    if (!IS_VALID_LLDB_HOST_THREAD(m_event_handler_thread))
3118269024Semaste        m_event_handler_thread = Host::ThreadCreate("lldb.debugger.event-handler", EventHandlerThread, this, NULL);
3119269024Semaste    return IS_VALID_LLDB_HOST_THREAD(m_event_handler_thread);
3120269024Semaste}
3121269024Semaste
3122269024Semastevoid
3123269024SemasteDebugger::StopEventHandlerThread()
3124269024Semaste{
3125269024Semaste    if (IS_VALID_LLDB_HOST_THREAD(m_event_handler_thread))
3126269024Semaste    {
3127269024Semaste        GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
3128269024Semaste        Host::ThreadJoin(m_event_handler_thread, NULL, NULL);
3129269024Semaste        m_event_handler_thread = LLDB_INVALID_HOST_THREAD;
3130269024Semaste    }
3131269024Semaste}
3132269024Semaste
3133269024Semaste
3134269024Semastelldb::thread_result_t
3135269024SemasteDebugger::IOHandlerThread (lldb::thread_arg_t arg)
3136269024Semaste{
3137269024Semaste    Debugger *debugger = (Debugger *)arg;
3138269024Semaste    debugger->ExecuteIOHanders();
3139269024Semaste    debugger->StopEventHandlerThread();
3140269024Semaste    return NULL;
3141269024Semaste}
3142269024Semaste
3143269024Semastebool
3144269024SemasteDebugger::StartIOHandlerThread()
3145269024Semaste{
3146269024Semaste    if (!IS_VALID_LLDB_HOST_THREAD(m_io_handler_thread))
3147269024Semaste        m_io_handler_thread = Host::ThreadCreate("lldb.debugger.io-handler", IOHandlerThread, this, NULL);
3148269024Semaste    return IS_VALID_LLDB_HOST_THREAD(m_io_handler_thread);
3149269024Semaste}
3150269024Semaste
3151269024Semastevoid
3152269024SemasteDebugger::StopIOHandlerThread()
3153269024Semaste{
3154269024Semaste    if (IS_VALID_LLDB_HOST_THREAD(m_io_handler_thread))
3155269024Semaste    {
3156269024Semaste        if (m_input_file_sp)
3157269024Semaste            m_input_file_sp->GetFile().Close();
3158269024Semaste        Host::ThreadJoin(m_io_handler_thread, NULL, NULL);
3159269024Semaste        m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
3160269024Semaste    }
3161269024Semaste}
3162269024Semaste
3163269024Semaste
3164