1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Core/Debugger.h"
11 
12 #include <map>
13 
14 #include "llvm/ADT/StringRef.h"
15 
16 #include "lldb/lldb-private.h"
17 #include "lldb/Core/FormatEntity.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginInterface.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/RegisterValue.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/StreamAsynchronousIO.h"
24 #include "lldb/Core/StreamCallback.h"
25 #include "lldb/Core/StreamFile.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Core/StructuredData.h"
28 #include "lldb/Core/Timer.h"
29 #include "lldb/Core/ValueObject.h"
30 #include "lldb/Core/ValueObjectVariable.h"
31 #include "lldb/DataFormatters/DataVisualization.h"
32 #include "lldb/DataFormatters/FormatManager.h"
33 #include "lldb/DataFormatters/TypeSummary.h"
34 #include "lldb/Expression/REPL.h"
35 #include "lldb/Host/ConnectionFileDescriptor.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Host/Terminal.h"
38 #include "lldb/Host/ThreadLauncher.h"
39 #include "lldb/Interpreter/CommandInterpreter.h"
40 #include "lldb/Interpreter/OptionValueProperties.h"
41 #include "lldb/Interpreter/OptionValueSInt64.h"
42 #include "lldb/Interpreter/OptionValueString.h"
43 #include "lldb/Symbol/CompileUnit.h"
44 #include "lldb/Symbol/Function.h"
45 #include "lldb/Symbol/Symbol.h"
46 #include "lldb/Symbol/VariableList.h"
47 #include "lldb/Target/TargetList.h"
48 #include "lldb/Target/Language.h"
49 #include "lldb/Target/Process.h"
50 #include "lldb/Target/RegisterContext.h"
51 #include "lldb/Target/SectionLoadList.h"
52 #include "lldb/Target/StopInfo.h"
53 #include "lldb/Target/Target.h"
54 #include "lldb/Target/Thread.h"
55 #include "lldb/Utility/AnsiTerminal.h"
56 
57 #include "llvm/Support/DynamicLibrary.h"
58 
59 using namespace lldb;
60 using namespace lldb_private;
61 
62 
63 static lldb::user_id_t g_unique_id = 1;
64 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
65 
66 #pragma mark Static Functions
67 
68 static Mutex &
69 GetDebuggerListMutex ()
70 {
71     static Mutex g_mutex(Mutex::eMutexTypeRecursive);
72     return g_mutex;
73 }
74 
75 typedef std::vector<DebuggerSP> DebuggerList;
76 
77 static DebuggerList &
78 GetDebuggerList()
79 {
80     // hide the static debugger list inside a singleton accessor to avoid
81     // global init constructors
82     static DebuggerList g_list;
83     return g_list;
84 }
85 
86 OptionEnumValueElement
87 g_show_disassembly_enum_values[] =
88 {
89     { Debugger::eStopDisassemblyTypeNever,    "never",     "Never show disassembly when displaying a stop context."},
90     { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
91     { Debugger::eStopDisassemblyTypeAlways,   "always",    "Always show disassembly when displaying a stop context."},
92     { 0, NULL, NULL }
93 };
94 
95 OptionEnumValueElement
96 g_language_enumerators[] =
97 {
98     { eScriptLanguageNone,      "none",     "Disable scripting languages."},
99     { eScriptLanguagePython,    "python",   "Select python as the default scripting language."},
100     { eScriptLanguageDefault,   "default",  "Select the lldb default as the default scripting language."},
101     { 0, NULL, NULL }
102 };
103 
104 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
105 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
106 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
107 
108 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
109     "{, ${frame.pc}}"\
110     MODULE_WITH_FUNC\
111     FILE_AND_LINE\
112     "{, name = '${thread.name}'}"\
113     "{, queue = '${thread.queue}'}"\
114     "{, activity = '${thread.info.activity.name}'}" \
115     "{, ${thread.info.trace_messages} messages}" \
116     "{, stop reason = ${thread.stop-reason}}"\
117     "{\\nReturn value: ${thread.return-value}}"\
118     "{\\nCompleted expression: ${thread.completed-expression}}"\
119     "\\n"
120 
121 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
122     MODULE_WITH_FUNC\
123     FILE_AND_LINE\
124     IS_OPTIMIZED\
125     "\\n"
126 
127 // Three parts to this disassembly format specification:
128 //   1. If this is a new function/symbol (no previous symbol/function), print
129 //      dylib`funcname:\n
130 //   2. If this is a symbol context change (different from previous symbol/function), print
131 //      dylib`funcname:\n
132 //   3. print
133 //      address <+offset>:
134 #define DEFAULT_DISASSEMBLY_FORMAT "{${function.initial-function}{${module.file.basename}`}{${function.name-without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-without-args}}:\n}{${current-pc-arrow} }${addr-file-or-load}{ <${function.concrete-only-addr-offset-no-padding}>}: "
135 
136 // gdb's disassembly format can be emulated with
137 // ${current-pc-arrow}${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}:
138 
139 // lldb's original format for disassembly would look like this format string -
140 // {${function.initial-function}{${module.file.basename}`}{${function.name-without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
141 
142 
143 static PropertyDefinition
144 g_properties[] =
145 {
146 {   "auto-confirm",             OptionValue::eTypeBoolean     , true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
147 {   "disassembly-format",       OptionValue::eTypeFormatEntity, true, 0    , DEFAULT_DISASSEMBLY_FORMAT, NULL, "The default disassembly format string to use when disassembling instruction sequences." },
148 {   "frame-format",             OptionValue::eTypeFormatEntity, true, 0    , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
149 {   "notify-void",              OptionValue::eTypeBoolean     , true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
150 {   "prompt",                   OptionValue::eTypeString      , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
151 {   "script-lang",              OptionValue::eTypeEnum        , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
152 {   "stop-disassembly-count",   OptionValue::eTypeSInt64      , true, 4    , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
153 {   "stop-disassembly-display", OptionValue::eTypeEnum        , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
154 {   "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." },
155 {   "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." },
156 {   "term-width",               OptionValue::eTypeSInt64      , true, 80   , NULL, NULL, "The maximum number of columns to use for displaying text." },
157 {   "thread-format",            OptionValue::eTypeFormatEntity, true, 0    , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
158 {   "use-external-editor",      OptionValue::eTypeBoolean     , true, false, NULL, NULL, "Whether to use an external editor or not." },
159 {   "use-color",                OptionValue::eTypeBoolean     , true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
160 {   "auto-one-line-summaries",  OptionValue::eTypeBoolean     , true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
161 {   "auto-indent",              OptionValue::eTypeBoolean     , true, true , NULL, NULL, "If true, LLDB will auto indent/outdent code. Currently only supported in the REPL (default: true)." },
162 {   "print-decls",              OptionValue::eTypeBoolean     , true, true , NULL, NULL, "If true, LLDB will print the values of variables declared in an expression. Currently only supported in the REPL (default: true)." },
163 {   "tab-size",                 OptionValue::eTypeUInt64      , true, 4    , NULL, NULL, "The tab size to use when indenting code in multi-line input mode (default: 4)." },
164 {   "escape-non-printables",    OptionValue::eTypeBoolean     , true, true, NULL, NULL, "If true, LLDB will automatically escape non-printable and escape characters when formatting strings." },
165 {   NULL,                       OptionValue::eTypeInvalid     , true, 0    , NULL, NULL, NULL }
166 };
167 
168 enum
169 {
170     ePropertyAutoConfirm = 0,
171     ePropertyDisassemblyFormat,
172     ePropertyFrameFormat,
173     ePropertyNotiftVoid,
174     ePropertyPrompt,
175     ePropertyScriptLanguage,
176     ePropertyStopDisassemblyCount,
177     ePropertyStopDisassemblyDisplay,
178     ePropertyStopLineCountAfter,
179     ePropertyStopLineCountBefore,
180     ePropertyTerminalWidth,
181     ePropertyThreadFormat,
182     ePropertyUseExternalEditor,
183     ePropertyUseColor,
184     ePropertyAutoOneLineSummaries,
185     ePropertyAutoIndent,
186     ePropertyPrintDecls,
187     ePropertyTabSize,
188     ePropertyEscapeNonPrintables
189 };
190 
191 LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
192 
193 Error
194 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
195                             VarSetOperationType op,
196                             const char *property_path,
197                             const char *value)
198 {
199     bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
200     bool is_escape_non_printables = strcmp(property_path, "escape-non-printables") == 0;
201     TargetSP target_sp;
202     LoadScriptFromSymFile load_script_old_value;
203     if (is_load_script && exe_ctx->GetTargetSP())
204     {
205         target_sp = exe_ctx->GetTargetSP();
206         load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
207     }
208     Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
209     if (error.Success())
210     {
211         // FIXME it would be nice to have "on-change" callbacks for properties
212         if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
213         {
214             const char *new_prompt = GetPrompt();
215             std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
216             if (str.length())
217                 new_prompt = str.c_str();
218             GetCommandInterpreter().UpdatePrompt(new_prompt);
219             EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
220             GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
221         }
222         else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
223         {
224 			// use-color changed. Ping the prompt so it can reset the ansi terminal codes.
225             SetPrompt (GetPrompt());
226         }
227         else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
228         {
229             if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
230             {
231                 std::list<Error> errors;
232                 StreamString feedback_stream;
233                 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
234                 {
235                     StreamFileSP stream_sp (GetErrorFile());
236                     if (stream_sp)
237                     {
238                         for (auto error : errors)
239                         {
240                             stream_sp->Printf("%s\n",error.AsCString());
241                         }
242                         if (feedback_stream.GetSize())
243                             stream_sp->Printf("%s",feedback_stream.GetData());
244                     }
245                 }
246             }
247         }
248         else if (is_escape_non_printables)
249         {
250             DataVisualization::ForceUpdate();
251         }
252     }
253     return error;
254 }
255 
256 bool
257 Debugger::GetAutoConfirm () const
258 {
259     const uint32_t idx = ePropertyAutoConfirm;
260     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
261 }
262 
263 const FormatEntity::Entry *
264 Debugger::GetDisassemblyFormat() const
265 {
266     const uint32_t idx = ePropertyDisassemblyFormat;
267     return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
268 }
269 
270 const FormatEntity::Entry *
271 Debugger::GetFrameFormat() const
272 {
273     const uint32_t idx = ePropertyFrameFormat;
274     return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
275 }
276 
277 bool
278 Debugger::GetNotifyVoid () const
279 {
280     const uint32_t idx = ePropertyNotiftVoid;
281     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
282 }
283 
284 const char *
285 Debugger::GetPrompt() const
286 {
287     const uint32_t idx = ePropertyPrompt;
288     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
289 }
290 
291 void
292 Debugger::SetPrompt(const char *p)
293 {
294     const uint32_t idx = ePropertyPrompt;
295     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
296     const char *new_prompt = GetPrompt();
297     std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
298     if (str.length())
299         new_prompt = str.c_str();
300     GetCommandInterpreter().UpdatePrompt(new_prompt);
301 }
302 
303 const FormatEntity::Entry *
304 Debugger::GetThreadFormat() const
305 {
306     const uint32_t idx = ePropertyThreadFormat;
307     return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
308 }
309 
310 lldb::ScriptLanguage
311 Debugger::GetScriptLanguage() const
312 {
313     const uint32_t idx = ePropertyScriptLanguage;
314     return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
315 }
316 
317 bool
318 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
319 {
320     const uint32_t idx = ePropertyScriptLanguage;
321     return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
322 }
323 
324 uint32_t
325 Debugger::GetTerminalWidth () const
326 {
327     const uint32_t idx = ePropertyTerminalWidth;
328     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
329 }
330 
331 bool
332 Debugger::SetTerminalWidth (uint32_t term_width)
333 {
334     const uint32_t idx = ePropertyTerminalWidth;
335     return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
336 }
337 
338 bool
339 Debugger::GetUseExternalEditor () const
340 {
341     const uint32_t idx = ePropertyUseExternalEditor;
342     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
343 }
344 
345 bool
346 Debugger::SetUseExternalEditor (bool b)
347 {
348     const uint32_t idx = ePropertyUseExternalEditor;
349     return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
350 }
351 
352 bool
353 Debugger::GetUseColor () const
354 {
355     const uint32_t idx = ePropertyUseColor;
356     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
357 }
358 
359 bool
360 Debugger::SetUseColor (bool b)
361 {
362     const uint32_t idx = ePropertyUseColor;
363     bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
364     SetPrompt (GetPrompt());
365     return ret;
366 }
367 
368 uint32_t
369 Debugger::GetStopSourceLineCount (bool before) const
370 {
371     const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
372     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
373 }
374 
375 Debugger::StopDisassemblyType
376 Debugger::GetStopDisassemblyDisplay () const
377 {
378     const uint32_t idx = ePropertyStopDisassemblyDisplay;
379     return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
380 }
381 
382 uint32_t
383 Debugger::GetDisassemblyLineCount () const
384 {
385     const uint32_t idx = ePropertyStopDisassemblyCount;
386     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
387 }
388 
389 bool
390 Debugger::GetAutoOneLineSummaries () const
391 {
392     const uint32_t idx = ePropertyAutoOneLineSummaries;
393     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
394 }
395 
396 bool
397 Debugger::GetEscapeNonPrintables () const
398 {
399     const uint32_t idx = ePropertyEscapeNonPrintables;
400     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
401 }
402 
403 bool
404 Debugger::GetAutoIndent () const
405 {
406     const uint32_t idx = ePropertyAutoIndent;
407     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
408 }
409 
410 bool
411 Debugger::SetAutoIndent (bool b)
412 {
413     const uint32_t idx = ePropertyAutoIndent;
414     return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
415 }
416 
417 bool
418 Debugger::GetPrintDecls () const
419 {
420     const uint32_t idx = ePropertyPrintDecls;
421     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
422 }
423 
424 bool
425 Debugger::SetPrintDecls (bool b)
426 {
427     const uint32_t idx = ePropertyPrintDecls;
428     return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
429 }
430 
431 uint32_t
432 Debugger::GetTabSize () const
433 {
434     const uint32_t idx = ePropertyTabSize;
435     return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
436 }
437 
438 bool
439 Debugger::SetTabSize (uint32_t tab_size)
440 {
441     const uint32_t idx = ePropertyTabSize;
442     return m_collection_sp->SetPropertyAtIndexAsUInt64 (NULL, idx, tab_size);
443 }
444 
445 
446 #pragma mark Debugger
447 
448 //const DebuggerPropertiesSP &
449 //Debugger::GetSettings() const
450 //{
451 //    return m_properties_sp;
452 //}
453 //
454 
455 static bool lldb_initialized = false;
456 void
457 Debugger::Initialize(LoadPluginCallbackType load_plugin_callback)
458 {
459     assert(!lldb_initialized && "Debugger::Initialize called more than once!");
460 
461     lldb_initialized = true;
462     g_load_plugin_callback = load_plugin_callback;
463 }
464 
465 void
466 Debugger::Terminate ()
467 {
468     assert(lldb_initialized && "Debugger::Terminate called without a matching Debugger::Initialize!");
469 
470     // Clear our master list of debugger objects
471     Mutex::Locker locker (GetDebuggerListMutex ());
472     auto& debuggers = GetDebuggerList();
473     for (const auto& debugger: debuggers)
474         debugger->Clear();
475 
476     debuggers.clear();
477 }
478 
479 void
480 Debugger::SettingsInitialize ()
481 {
482     Target::SettingsInitialize ();
483 }
484 
485 void
486 Debugger::SettingsTerminate ()
487 {
488     Target::SettingsTerminate ();
489 }
490 
491 bool
492 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
493 {
494     if (g_load_plugin_callback)
495     {
496         llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
497         if (dynlib.isValid())
498         {
499             m_loaded_plugins.push_back(dynlib);
500             return true;
501         }
502     }
503     else
504     {
505         // The g_load_plugin_callback is registered in SBDebugger::Initialize()
506         // and if the public API layer isn't available (code is linking against
507         // all of the internal LLDB static libraries), then we can't load plugins
508         error.SetErrorString("Public API layer is not available");
509     }
510     return false;
511 }
512 
513 static FileSpec::EnumerateDirectoryResult
514 LoadPluginCallback
515 (
516  void *baton,
517  FileSpec::FileType file_type,
518  const FileSpec &file_spec
519  )
520 {
521     Error error;
522 
523     static ConstString g_dylibext("dylib");
524     static ConstString g_solibext("so");
525 
526     if (!baton)
527         return FileSpec::eEnumerateDirectoryResultQuit;
528 
529     Debugger *debugger = (Debugger*)baton;
530 
531     // If we have a regular file, a symbolic link or unknown file type, try
532     // and process the file. We must handle unknown as sometimes the directory
533     // enumeration might be enumerating a file system that doesn't have correct
534     // file type information.
535     if (file_type == FileSpec::eFileTypeRegular         ||
536         file_type == FileSpec::eFileTypeSymbolicLink    ||
537         file_type == FileSpec::eFileTypeUnknown          )
538     {
539         FileSpec plugin_file_spec (file_spec);
540         plugin_file_spec.ResolvePath ();
541 
542         if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
543             plugin_file_spec.GetFileNameExtension() != g_solibext)
544         {
545             return FileSpec::eEnumerateDirectoryResultNext;
546         }
547 
548         Error plugin_load_error;
549         debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
550 
551         return FileSpec::eEnumerateDirectoryResultNext;
552     }
553 
554     else if (file_type == FileSpec::eFileTypeUnknown     ||
555         file_type == FileSpec::eFileTypeDirectory   ||
556         file_type == FileSpec::eFileTypeSymbolicLink )
557     {
558         // Try and recurse into anything that a directory or symbolic link.
559         // We must also do this for unknown as sometimes the directory enumeration
560         // might be enumerating a file system that doesn't have correct file type
561         // information.
562         return FileSpec::eEnumerateDirectoryResultEnter;
563     }
564 
565     return FileSpec::eEnumerateDirectoryResultNext;
566 }
567 
568 void
569 Debugger::InstanceInitialize ()
570 {
571     FileSpec dir_spec;
572     const bool find_directories = true;
573     const bool find_files = true;
574     const bool find_other = true;
575     char dir_path[PATH_MAX];
576     if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
577     {
578         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
579         {
580             FileSpec::EnumerateDirectory (dir_path,
581                                           find_directories,
582                                           find_files,
583                                           find_other,
584                                           LoadPluginCallback,
585                                           this);
586         }
587     }
588 
589     if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
590     {
591         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
592         {
593             FileSpec::EnumerateDirectory (dir_path,
594                                           find_directories,
595                                           find_files,
596                                           find_other,
597                                           LoadPluginCallback,
598                                           this);
599         }
600     }
601 
602     PluginManager::DebuggerInitialize (*this);
603 }
604 
605 DebuggerSP
606 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
607 {
608     DebuggerSP debugger_sp (new Debugger(log_callback, baton));
609     if (lldb_initialized)
610     {
611         Mutex::Locker locker (GetDebuggerListMutex ());
612         GetDebuggerList().push_back(debugger_sp);
613     }
614     debugger_sp->InstanceInitialize ();
615     return debugger_sp;
616 }
617 
618 void
619 Debugger::Destroy (DebuggerSP &debugger_sp)
620 {
621     if (debugger_sp.get() == NULL)
622         return;
623 
624     debugger_sp->Clear();
625 
626     if (lldb_initialized)
627     {
628         Mutex::Locker locker (GetDebuggerListMutex ());
629         DebuggerList &debugger_list = GetDebuggerList ();
630         DebuggerList::iterator pos, end = debugger_list.end();
631         for (pos = debugger_list.begin (); pos != end; ++pos)
632         {
633             if ((*pos).get() == debugger_sp.get())
634             {
635                 debugger_list.erase (pos);
636                 return;
637             }
638         }
639     }
640 }
641 
642 DebuggerSP
643 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
644 {
645     DebuggerSP debugger_sp;
646     if (lldb_initialized)
647     {
648         Mutex::Locker locker (GetDebuggerListMutex ());
649         DebuggerList &debugger_list = GetDebuggerList();
650         DebuggerList::iterator pos, end = debugger_list.end();
651 
652         for (pos = debugger_list.begin(); pos != end; ++pos)
653         {
654             if ((*pos).get()->m_instance_name == instance_name)
655             {
656                 debugger_sp = *pos;
657                 break;
658             }
659         }
660     }
661     return debugger_sp;
662 }
663 
664 TargetSP
665 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
666 {
667     TargetSP target_sp;
668     if (lldb_initialized)
669     {
670         Mutex::Locker locker (GetDebuggerListMutex ());
671         DebuggerList &debugger_list = GetDebuggerList();
672         DebuggerList::iterator pos, end = debugger_list.end();
673         for (pos = debugger_list.begin(); pos != end; ++pos)
674         {
675             target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
676             if (target_sp)
677                 break;
678         }
679     }
680     return target_sp;
681 }
682 
683 TargetSP
684 Debugger::FindTargetWithProcess (Process *process)
685 {
686     TargetSP target_sp;
687     if (lldb_initialized)
688     {
689         Mutex::Locker locker (GetDebuggerListMutex ());
690         DebuggerList &debugger_list = GetDebuggerList();
691         DebuggerList::iterator pos, end = debugger_list.end();
692         for (pos = debugger_list.begin(); pos != end; ++pos)
693         {
694             target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
695             if (target_sp)
696                 break;
697         }
698     }
699     return target_sp;
700 }
701 
702 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) :
703     UserID(g_unique_id++),
704     Properties(OptionValuePropertiesSP(new OptionValueProperties())),
705     m_input_file_sp(new StreamFile(stdin, false)),
706     m_output_file_sp(new StreamFile(stdout, false)),
707     m_error_file_sp(new StreamFile(stderr, false)),
708     m_terminal_state(),
709     m_target_list(*this),
710     m_platform_list(),
711     m_listener("lldb.Debugger"),
712     m_source_manager_ap(),
713     m_source_file_cache(),
714     m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)),
715     m_input_reader_stack(),
716     m_instance_name(),
717     m_loaded_plugins(),
718     m_event_handler_thread (),
719     m_io_handler_thread (),
720     m_sync_broadcaster (NULL, "lldb.debugger.sync")
721 {
722     char instance_cstr[256];
723     snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
724     m_instance_name.SetCString(instance_cstr);
725     if (log_callback)
726         m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
727     m_command_interpreter_ap->Initialize ();
728     // Always add our default platform to the platform list
729     PlatformSP default_platform_sp (Platform::GetHostPlatform());
730     assert (default_platform_sp.get());
731     m_platform_list.Append (default_platform_sp, true);
732 
733     m_collection_sp->Initialize (g_properties);
734     m_collection_sp->AppendProperty (ConstString("target"),
735                                      ConstString("Settings specify to debugging targets."),
736                                      true,
737                                      Target::GetGlobalProperties()->GetValueProperties());
738     m_collection_sp->AppendProperty (ConstString("platform"),
739                                      ConstString("Platform settings."),
740                                      true,
741                                      Platform::GetGlobalPlatformProperties()->GetValueProperties());
742     if (m_command_interpreter_ap.get())
743     {
744         m_collection_sp->AppendProperty (ConstString("interpreter"),
745                                          ConstString("Settings specify to the debugger's command interpreter."),
746                                          true,
747                                          m_command_interpreter_ap->GetValueProperties());
748     }
749     OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
750     term_width->SetMinimumValue(10);
751     term_width->SetMaximumValue(1024);
752 
753     // Turn off use-color if this is a dumb terminal.
754     const char *term = getenv ("TERM");
755     if (term && !strcmp (term, "dumb"))
756         SetUseColor (false);
757 }
758 
759 Debugger::~Debugger ()
760 {
761     Clear();
762 }
763 
764 void
765 Debugger::Clear()
766 {
767     ClearIOHandlers();
768     StopIOHandlerThread();
769     StopEventHandlerThread();
770     m_listener.Clear();
771     int num_targets = m_target_list.GetNumTargets();
772     for (int i = 0; i < num_targets; i++)
773     {
774         TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
775         if (target_sp)
776         {
777             ProcessSP process_sp (target_sp->GetProcessSP());
778             if (process_sp)
779                 process_sp->Finalize();
780             target_sp->Destroy();
781         }
782     }
783     BroadcasterManager::Clear ();
784 
785     // Close the input file _before_ we close the input read communications class
786     // as it does NOT own the input file, our m_input_file does.
787     m_terminal_state.Clear();
788     if (m_input_file_sp)
789         m_input_file_sp->GetFile().Close ();
790 
791     m_command_interpreter_ap->Clear();
792 }
793 
794 bool
795 Debugger::GetCloseInputOnEOF () const
796 {
797 //    return m_input_comm.GetCloseOnEOF();
798     return false;
799 }
800 
801 void
802 Debugger::SetCloseInputOnEOF (bool b)
803 {
804 //    m_input_comm.SetCloseOnEOF(b);
805 }
806 
807 bool
808 Debugger::GetAsyncExecution ()
809 {
810     return !m_command_interpreter_ap->GetSynchronous();
811 }
812 
813 void
814 Debugger::SetAsyncExecution (bool async_execution)
815 {
816     m_command_interpreter_ap->SetSynchronous (!async_execution);
817 }
818 
819 
820 void
821 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
822 {
823     if (m_input_file_sp)
824         m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
825     else
826         m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
827 
828     File &in_file = m_input_file_sp->GetFile();
829     if (in_file.IsValid() == false)
830         in_file.SetStream (stdin, true);
831 
832     // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
833     SaveInputTerminalState ();
834 }
835 
836 void
837 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
838 {
839     if (m_output_file_sp)
840         m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
841     else
842         m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
843 
844     File &out_file = m_output_file_sp->GetFile();
845     if (out_file.IsValid() == false)
846         out_file.SetStream (stdout, false);
847 
848     // do not create the ScriptInterpreter just for setting the output file handle
849     // as the constructor will know how to do the right thing on its own
850     const bool can_create = false;
851     ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
852     if (script_interpreter)
853         script_interpreter->ResetOutputFileHandle (fh);
854 }
855 
856 void
857 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
858 {
859     if (m_error_file_sp)
860         m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
861     else
862         m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
863 
864     File &err_file = m_error_file_sp->GetFile();
865     if (err_file.IsValid() == false)
866         err_file.SetStream (stderr, false);
867 }
868 
869 void
870 Debugger::SaveInputTerminalState ()
871 {
872     if (m_input_file_sp)
873     {
874         File &in_file = m_input_file_sp->GetFile();
875         if (in_file.GetDescriptor() != File::kInvalidDescriptor)
876             m_terminal_state.Save(in_file.GetDescriptor(), true);
877     }
878 }
879 
880 void
881 Debugger::RestoreInputTerminalState ()
882 {
883     m_terminal_state.Restore();
884 }
885 
886 ExecutionContext
887 Debugger::GetSelectedExecutionContext ()
888 {
889     ExecutionContext exe_ctx;
890     TargetSP target_sp(GetSelectedTarget());
891     exe_ctx.SetTargetSP (target_sp);
892 
893     if (target_sp)
894     {
895         ProcessSP process_sp (target_sp->GetProcessSP());
896         exe_ctx.SetProcessSP (process_sp);
897         if (process_sp && process_sp->IsRunning() == false)
898         {
899             ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
900             if (thread_sp)
901             {
902                 exe_ctx.SetThreadSP (thread_sp);
903                 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
904                 if (exe_ctx.GetFramePtr() == NULL)
905                     exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
906             }
907         }
908     }
909     return exe_ctx;
910 }
911 
912 void
913 Debugger::DispatchInputInterrupt ()
914 {
915     Mutex::Locker locker (m_input_reader_stack.GetMutex());
916     IOHandlerSP reader_sp (m_input_reader_stack.Top());
917     if (reader_sp)
918         reader_sp->Interrupt();
919 }
920 
921 void
922 Debugger::DispatchInputEndOfFile ()
923 {
924     Mutex::Locker locker (m_input_reader_stack.GetMutex());
925     IOHandlerSP reader_sp (m_input_reader_stack.Top());
926     if (reader_sp)
927         reader_sp->GotEOF();
928 }
929 
930 void
931 Debugger::ClearIOHandlers ()
932 {
933     // The bottom input reader should be the main debugger input reader.  We do not want to close that one here.
934     Mutex::Locker locker (m_input_reader_stack.GetMutex());
935     while (m_input_reader_stack.GetSize() > 1)
936     {
937         IOHandlerSP reader_sp (m_input_reader_stack.Top());
938         if (reader_sp)
939             PopIOHandler (reader_sp);
940     }
941 }
942 
943 void
944 Debugger::ExecuteIOHandlers()
945 {
946     while (1)
947     {
948         IOHandlerSP reader_sp(m_input_reader_stack.Top());
949         if (!reader_sp)
950             break;
951 
952         reader_sp->Run();
953 
954         // Remove all input readers that are done from the top of the stack
955         while (1)
956         {
957             IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
958             if (top_reader_sp && top_reader_sp->GetIsDone())
959                 PopIOHandler (top_reader_sp);
960             else
961                 break;
962         }
963     }
964     ClearIOHandlers();
965 }
966 
967 bool
968 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
969 {
970     return m_input_reader_stack.IsTop (reader_sp);
971 }
972 
973 bool
974 Debugger::CheckTopIOHandlerTypes (IOHandler::Type top_type, IOHandler::Type second_top_type)
975 {
976     return m_input_reader_stack.CheckTopIOHandlerTypes (top_type, second_top_type);
977 }
978 
979 void
980 Debugger::PrintAsync (const char *s, size_t len, bool is_stdout)
981 {
982     lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
983     m_input_reader_stack.PrintAsync(stream.get(), s, len);
984 }
985 
986 ConstString
987 Debugger::GetTopIOHandlerControlSequence(char ch)
988 {
989     return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
990 }
991 
992 const char *
993 Debugger::GetIOHandlerCommandPrefix()
994 {
995     return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
996 }
997 
998 const char *
999 Debugger::GetIOHandlerHelpPrologue()
1000 {
1001     return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1002 }
1003 
1004 void
1005 Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
1006 {
1007     PushIOHandler (reader_sp);
1008 
1009     IOHandlerSP top_reader_sp = reader_sp;
1010     while (top_reader_sp)
1011     {
1012         top_reader_sp->Run();
1013 
1014         if (top_reader_sp.get() == reader_sp.get())
1015         {
1016             if (PopIOHandler (reader_sp))
1017                 break;
1018         }
1019 
1020         while (1)
1021         {
1022             top_reader_sp = m_input_reader_stack.Top();
1023             if (top_reader_sp && top_reader_sp->GetIsDone())
1024                 PopIOHandler (top_reader_sp);
1025             else
1026                 break;
1027         }
1028     }
1029 }
1030 
1031 void
1032 Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
1033 {
1034     // Before an IOHandler runs, it must have in/out/err streams.
1035     // This function is called when one ore more of the streams
1036     // are NULL. We use the top input reader's in/out/err streams,
1037     // or fall back to the debugger file handles, or we fall back
1038     // onto stdin/stdout/stderr as a last resort.
1039 
1040     Mutex::Locker locker (m_input_reader_stack.GetMutex());
1041     IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1042     // If no STDIN has been set, then set it appropriately
1043     if (!in)
1044     {
1045         if (top_reader_sp)
1046             in = top_reader_sp->GetInputStreamFile();
1047         else
1048             in = GetInputFile();
1049 
1050         // If there is nothing, use stdin
1051         if (!in)
1052             in = StreamFileSP(new StreamFile(stdin, false));
1053     }
1054     // If no STDOUT has been set, then set it appropriately
1055     if (!out)
1056     {
1057         if (top_reader_sp)
1058             out = top_reader_sp->GetOutputStreamFile();
1059         else
1060             out = GetOutputFile();
1061 
1062         // If there is nothing, use stdout
1063         if (!out)
1064             out = StreamFileSP(new StreamFile(stdout, false));
1065     }
1066     // If no STDERR has been set, then set it appropriately
1067     if (!err)
1068     {
1069         if (top_reader_sp)
1070             err = top_reader_sp->GetErrorStreamFile();
1071         else
1072             err = GetErrorFile();
1073 
1074         // If there is nothing, use stderr
1075         if (!err)
1076             err = StreamFileSP(new StreamFile(stdout, false));
1077 
1078     }
1079 }
1080 
1081 void
1082 Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
1083 {
1084     if (!reader_sp)
1085         return;
1086 
1087     Mutex::Locker locker (m_input_reader_stack.GetMutex());
1088 
1089     // Get the current top input reader...
1090     IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1091 
1092     // Don't push the same IO handler twice...
1093     if (reader_sp == top_reader_sp)
1094         return;
1095 
1096     // Push our new input reader
1097     m_input_reader_stack.Push (reader_sp);
1098     reader_sp->Activate();
1099 
1100     // Interrupt the top input reader to it will exit its Run() function
1101     // and let this new input reader take over
1102     if (top_reader_sp)
1103     {
1104         top_reader_sp->Deactivate();
1105         top_reader_sp->Cancel();
1106     }
1107 }
1108 
1109 bool
1110 Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
1111 {
1112     if (! pop_reader_sp)
1113         return false;
1114 
1115     Mutex::Locker locker (m_input_reader_stack.GetMutex());
1116 
1117     // The reader on the stop of the stack is done, so let the next
1118     // read on the stack refresh its prompt and if there is one...
1119     if (m_input_reader_stack.IsEmpty())
1120         return false;
1121 
1122     IOHandlerSP reader_sp(m_input_reader_stack.Top());
1123 
1124     if (pop_reader_sp != reader_sp)
1125         return false;
1126 
1127     reader_sp->Deactivate();
1128     reader_sp->Cancel();
1129     m_input_reader_stack.Pop ();
1130 
1131     reader_sp = m_input_reader_stack.Top();
1132     if (reader_sp)
1133         reader_sp->Activate();
1134 
1135     return true;
1136 }
1137 
1138 StreamSP
1139 Debugger::GetAsyncOutputStream ()
1140 {
1141     return StreamSP (new StreamAsynchronousIO (*this, true));
1142 }
1143 
1144 StreamSP
1145 Debugger::GetAsyncErrorStream ()
1146 {
1147     return StreamSP (new StreamAsynchronousIO (*this, false));
1148 }
1149 
1150 size_t
1151 Debugger::GetNumDebuggers()
1152 {
1153     if (lldb_initialized)
1154     {
1155         Mutex::Locker locker (GetDebuggerListMutex ());
1156         return GetDebuggerList().size();
1157     }
1158     return 0;
1159 }
1160 
1161 lldb::DebuggerSP
1162 Debugger::GetDebuggerAtIndex (size_t index)
1163 {
1164     DebuggerSP debugger_sp;
1165 
1166     if (lldb_initialized)
1167     {
1168         Mutex::Locker locker (GetDebuggerListMutex ());
1169         DebuggerList &debugger_list = GetDebuggerList();
1170 
1171         if (index < debugger_list.size())
1172             debugger_sp = debugger_list[index];
1173     }
1174 
1175     return debugger_sp;
1176 }
1177 
1178 DebuggerSP
1179 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1180 {
1181     DebuggerSP debugger_sp;
1182 
1183     if (lldb_initialized)
1184     {
1185         Mutex::Locker locker (GetDebuggerListMutex ());
1186         DebuggerList &debugger_list = GetDebuggerList();
1187         DebuggerList::iterator pos, end = debugger_list.end();
1188         for (pos = debugger_list.begin(); pos != end; ++pos)
1189         {
1190             if ((*pos).get()->GetID() == id)
1191             {
1192                 debugger_sp = *pos;
1193                 break;
1194             }
1195         }
1196     }
1197     return debugger_sp;
1198 }
1199 
1200 #if 0
1201 static void
1202 TestPromptFormats (StackFrame *frame)
1203 {
1204     if (frame == NULL)
1205         return;
1206 
1207     StreamString s;
1208     const char *prompt_format =
1209     "{addr = '${addr}'\n}"
1210     "{addr-file-or-load = '${addr-file-or-load}'\n}"
1211     "{current-pc-arrow = '${current-pc-arrow}'\n}"
1212     "{process.id = '${process.id}'\n}"
1213     "{process.name = '${process.name}'\n}"
1214     "{process.file.basename = '${process.file.basename}'\n}"
1215     "{process.file.fullpath = '${process.file.fullpath}'\n}"
1216     "{thread.id = '${thread.id}'\n}"
1217     "{thread.index = '${thread.index}'\n}"
1218     "{thread.name = '${thread.name}'\n}"
1219     "{thread.queue = '${thread.queue}'\n}"
1220     "{thread.stop-reason = '${thread.stop-reason}'\n}"
1221     "{target.arch = '${target.arch}'\n}"
1222     "{module.file.basename = '${module.file.basename}'\n}"
1223     "{module.file.fullpath = '${module.file.fullpath}'\n}"
1224     "{file.basename = '${file.basename}'\n}"
1225     "{file.fullpath = '${file.fullpath}'\n}"
1226     "{frame.index = '${frame.index}'\n}"
1227     "{frame.pc = '${frame.pc}'\n}"
1228     "{frame.sp = '${frame.sp}'\n}"
1229     "{frame.fp = '${frame.fp}'\n}"
1230     "{frame.flags = '${frame.flags}'\n}"
1231     "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1232     "{frame.reg.rip = '${frame.reg.rip}'\n}"
1233     "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1234     "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1235     "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1236     "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1237     "{frame.reg.carp = '${frame.reg.carp}'\n}"
1238     "{function.id = '${function.id}'\n}"
1239     "{function.changed = '${function.changed}'\n}"
1240     "{function.initial-function = '${function.initial-function}'\n}"
1241     "{function.name = '${function.name}'\n}"
1242     "{function.name-without-args = '${function.name-without-args}'\n}"
1243     "{function.name-with-args = '${function.name-with-args}'\n}"
1244     "{function.addr-offset = '${function.addr-offset}'\n}"
1245     "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
1246     "{function.line-offset = '${function.line-offset}'\n}"
1247     "{function.pc-offset = '${function.pc-offset}'\n}"
1248     "{line.file.basename = '${line.file.basename}'\n}"
1249     "{line.file.fullpath = '${line.file.fullpath}'\n}"
1250     "{line.number = '${line.number}'\n}"
1251     "{line.start-addr = '${line.start-addr}'\n}"
1252     "{line.end-addr = '${line.end-addr}'\n}"
1253 ;
1254 
1255     SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1256     ExecutionContext exe_ctx;
1257     frame->CalculateExecutionContext(exe_ctx);
1258     if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1259     {
1260         printf("%s\n", s.GetData());
1261     }
1262     else
1263     {
1264         printf ("what we got: %s\n", s.GetData());
1265     }
1266 }
1267 #endif
1268 
1269 bool
1270 Debugger::FormatDisassemblerAddress (const FormatEntity::Entry *format,
1271                                      const SymbolContext *sc,
1272                                      const SymbolContext *prev_sc,
1273                                      const ExecutionContext *exe_ctx,
1274                                      const Address *addr,
1275                                      Stream &s)
1276 {
1277     FormatEntity::Entry format_entry;
1278 
1279     if (format == NULL)
1280     {
1281         if (exe_ctx != NULL && exe_ctx->HasTargetScope())
1282             format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1283         if (format == NULL)
1284         {
1285             FormatEntity::Parse("${addr}: ", format_entry);
1286             format = &format_entry;
1287         }
1288     }
1289     bool function_changed = false;
1290     bool initial_function = false;
1291     if (prev_sc && (prev_sc->function || prev_sc->symbol))
1292     {
1293         if (sc && (sc->function || sc->symbol))
1294         {
1295             if (prev_sc->symbol && sc->symbol)
1296             {
1297                 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType()))
1298                 {
1299                     function_changed = true;
1300                 }
1301             }
1302             else if (prev_sc->function && sc->function)
1303             {
1304                 if (prev_sc->function->GetMangled() != sc->function->GetMangled())
1305                 {
1306                     function_changed = true;
1307                 }
1308             }
1309         }
1310     }
1311     // The first context on a list of instructions will have a prev_sc that
1312     // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1313     // would return false.  But we do get a prev_sc pointer.
1314     if ((sc && (sc->function || sc->symbol))
1315         && prev_sc && (prev_sc->function == NULL && prev_sc->symbol == NULL))
1316     {
1317         initial_function = true;
1318     }
1319     return FormatEntity::Format(*format, s, sc, exe_ctx, addr, NULL, function_changed, initial_function);
1320 }
1321 
1322 
1323 void
1324 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
1325 {
1326     // For simplicity's sake, I am not going to deal with how to close down any
1327     // open logging streams, I just redirect everything from here on out to the
1328     // callback.
1329     m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
1330 }
1331 
1332 bool
1333 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
1334 {
1335     StreamSP log_stream_sp;
1336     if (m_log_callback_stream_sp)
1337     {
1338         log_stream_sp = m_log_callback_stream_sp;
1339         // For now when using the callback mode you always get thread & timestamp.
1340         log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1341     }
1342     else if (log_file == NULL || *log_file == '\0')
1343     {
1344         log_stream_sp = GetOutputFile();
1345     }
1346     else
1347     {
1348         LogStreamMap::iterator pos = m_log_streams.find(log_file);
1349         if (pos != m_log_streams.end())
1350             log_stream_sp = pos->second.lock();
1351         if (!log_stream_sp)
1352         {
1353             uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate
1354                                 | File::eOpenOptionCloseOnExec | File::eOpenOptionAppend;
1355             if (! (log_options & LLDB_LOG_OPTION_APPEND))
1356                 options |= File::eOpenOptionTruncate;
1357 
1358             log_stream_sp.reset (new StreamFile (log_file, options));
1359             m_log_streams[log_file] = log_stream_sp;
1360         }
1361     }
1362     assert (log_stream_sp.get());
1363 
1364     if (log_options == 0)
1365         log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1366 
1367     return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, error_stream);
1368 }
1369 
1370 SourceManager &
1371 Debugger::GetSourceManager ()
1372 {
1373     if (m_source_manager_ap.get() == NULL)
1374         m_source_manager_ap.reset (new SourceManager (shared_from_this()));
1375     return *m_source_manager_ap;
1376 }
1377 
1378 
1379 
1380 // This function handles events that were broadcast by the process.
1381 void
1382 Debugger::HandleBreakpointEvent (const EventSP &event_sp)
1383 {
1384     using namespace lldb;
1385     const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
1386 
1387 //    if (event_type & eBreakpointEventTypeAdded
1388 //        || event_type & eBreakpointEventTypeRemoved
1389 //        || event_type & eBreakpointEventTypeEnabled
1390 //        || event_type & eBreakpointEventTypeDisabled
1391 //        || event_type & eBreakpointEventTypeCommandChanged
1392 //        || event_type & eBreakpointEventTypeConditionChanged
1393 //        || event_type & eBreakpointEventTypeIgnoreChanged
1394 //        || event_type & eBreakpointEventTypeLocationsResolved)
1395 //    {
1396 //        // Don't do anything about these events, since the breakpoint commands already echo these actions.
1397 //    }
1398 //
1399     if (event_type & eBreakpointEventTypeLocationsAdded)
1400     {
1401         uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
1402         if (num_new_locations > 0)
1403         {
1404             BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1405             StreamSP output_sp (GetAsyncOutputStream());
1406             if (output_sp)
1407             {
1408                 output_sp->Printf("%d location%s added to breakpoint %d\n",
1409                                   num_new_locations,
1410                                   num_new_locations == 1 ? "" : "s",
1411                                   breakpoint->GetID());
1412                 output_sp->Flush();
1413             }
1414         }
1415     }
1416 //    else if (event_type & eBreakpointEventTypeLocationsRemoved)
1417 //    {
1418 //        // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
1419 //    }
1420 //    else if (event_type & eBreakpointEventTypeLocationsResolved)
1421 //    {
1422 //        // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
1423 //    }
1424 }
1425 
1426 size_t
1427 Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
1428 {
1429     size_t total_bytes = 0;
1430     if (stream == NULL)
1431         stream = GetOutputFile().get();
1432 
1433     if (stream)
1434     {
1435         //  The process has stuff waiting for stdout; get it and write it out to the appropriate place.
1436         if (process == NULL)
1437         {
1438             TargetSP target_sp = GetTargetList().GetSelectedTarget();
1439             if (target_sp)
1440                 process = target_sp->GetProcessSP().get();
1441         }
1442         if (process)
1443         {
1444             Error error;
1445             size_t len;
1446             char stdio_buffer[1024];
1447             while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1448             {
1449                 stream->Write(stdio_buffer, len);
1450                 total_bytes += len;
1451             }
1452         }
1453         stream->Flush();
1454     }
1455     return total_bytes;
1456 }
1457 
1458 size_t
1459 Debugger::GetProcessSTDERR (Process *process, Stream *stream)
1460 {
1461     size_t total_bytes = 0;
1462     if (stream == NULL)
1463         stream = GetOutputFile().get();
1464 
1465     if (stream)
1466     {
1467         //  The process has stuff waiting for stderr; get it and write it out to the appropriate place.
1468         if (process == NULL)
1469         {
1470             TargetSP target_sp = GetTargetList().GetSelectedTarget();
1471             if (target_sp)
1472                 process = target_sp->GetProcessSP().get();
1473         }
1474         if (process)
1475         {
1476             Error error;
1477             size_t len;
1478             char stdio_buffer[1024];
1479             while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1480             {
1481                 stream->Write(stdio_buffer, len);
1482                 total_bytes += len;
1483             }
1484         }
1485         stream->Flush();
1486     }
1487     return total_bytes;
1488 }
1489 
1490 
1491 // This function handles events that were broadcast by the process.
1492 void
1493 Debugger::HandleProcessEvent (const EventSP &event_sp)
1494 {
1495     using namespace lldb;
1496     const uint32_t event_type = event_sp->GetType();
1497     ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1498 
1499     StreamSP output_stream_sp = GetAsyncOutputStream();
1500     StreamSP error_stream_sp = GetAsyncErrorStream();
1501     const bool gui_enabled = IsForwardingEvents();
1502 
1503     if (!gui_enabled)
1504     {
1505         bool pop_process_io_handler = false;
1506         assert (process_sp);
1507 
1508         bool state_is_stopped = false;
1509         const bool got_state_changed = (event_type & Process::eBroadcastBitStateChanged) != 0;
1510         const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1511         const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1512         if (got_state_changed)
1513         {
1514             StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1515             state_is_stopped = StateIsStoppedState(event_state, false);
1516         }
1517 
1518         // Display running state changes first before any STDIO
1519         if (got_state_changed && !state_is_stopped)
1520         {
1521             Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler);
1522         }
1523 
1524         // Now display and STDOUT
1525         if (got_stdout || got_state_changed)
1526         {
1527             GetProcessSTDOUT (process_sp.get(), output_stream_sp.get());
1528         }
1529 
1530         // Now display and STDERR
1531         if (got_stderr || got_state_changed)
1532         {
1533             GetProcessSTDERR (process_sp.get(), error_stream_sp.get());
1534         }
1535 
1536         // Now display any stopped state changes after any STDIO
1537         if (got_state_changed && state_is_stopped)
1538         {
1539             Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler);
1540         }
1541 
1542         output_stream_sp->Flush();
1543         error_stream_sp->Flush();
1544 
1545         if (pop_process_io_handler)
1546             process_sp->PopProcessIOHandler();
1547     }
1548 }
1549 
1550 void
1551 Debugger::HandleThreadEvent (const EventSP &event_sp)
1552 {
1553     // At present the only thread event we handle is the Frame Changed event,
1554     // and all we do for that is just reprint the thread status for that thread.
1555     using namespace lldb;
1556     const uint32_t event_type = event_sp->GetType();
1557     if (event_type == Thread::eBroadcastBitStackChanged   ||
1558         event_type == Thread::eBroadcastBitThreadSelected )
1559     {
1560         ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
1561         if (thread_sp)
1562         {
1563             thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1);
1564         }
1565     }
1566 }
1567 
1568 bool
1569 Debugger::IsForwardingEvents ()
1570 {
1571     return (bool)m_forward_listener_sp;
1572 }
1573 
1574 void
1575 Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
1576 {
1577     m_forward_listener_sp = listener_sp;
1578 }
1579 
1580 void
1581 Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
1582 {
1583     m_forward_listener_sp.reset();
1584 }
1585 
1586 
1587 void
1588 Debugger::DefaultEventHandler()
1589 {
1590     Listener& listener(GetListener());
1591     ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1592     ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1593     ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1594     BroadcastEventSpec target_event_spec (broadcaster_class_target,
1595                                           Target::eBroadcastBitBreakpointChanged);
1596 
1597     BroadcastEventSpec process_event_spec (broadcaster_class_process,
1598                                            Process::eBroadcastBitStateChanged   |
1599                                            Process::eBroadcastBitSTDOUT         |
1600                                            Process::eBroadcastBitSTDERR);
1601 
1602     BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
1603                                           Thread::eBroadcastBitStackChanged     |
1604                                           Thread::eBroadcastBitThreadSelected   );
1605 
1606     listener.StartListeningForEventSpec (*this, target_event_spec);
1607     listener.StartListeningForEventSpec (*this, process_event_spec);
1608     listener.StartListeningForEventSpec (*this, thread_event_spec);
1609     listener.StartListeningForEvents (m_command_interpreter_ap.get(),
1610                                       CommandInterpreter::eBroadcastBitQuitCommandReceived      |
1611                                       CommandInterpreter::eBroadcastBitAsynchronousOutputData   |
1612                                       CommandInterpreter::eBroadcastBitAsynchronousErrorData    );
1613 
1614     // Let the thread that spawned us know that we have started up and
1615     // that we are now listening to all required events so no events get missed
1616     m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1617 
1618     bool done = false;
1619     while (!done)
1620     {
1621         EventSP event_sp;
1622         if (listener.WaitForEvent(NULL, event_sp))
1623         {
1624             if (event_sp)
1625             {
1626                 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1627                 if (broadcaster)
1628                 {
1629                     uint32_t event_type = event_sp->GetType();
1630                     ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
1631                     if (broadcaster_class == broadcaster_class_process)
1632                     {
1633                         HandleProcessEvent (event_sp);
1634                     }
1635                     else if (broadcaster_class == broadcaster_class_target)
1636                     {
1637                         if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
1638                         {
1639                             HandleBreakpointEvent (event_sp);
1640                         }
1641                     }
1642                     else if (broadcaster_class == broadcaster_class_thread)
1643                     {
1644                         HandleThreadEvent (event_sp);
1645                     }
1646                     else if (broadcaster == m_command_interpreter_ap.get())
1647                     {
1648                         if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
1649                         {
1650                             done = true;
1651                         }
1652                         else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
1653                         {
1654                             const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1655                             if (data && data[0])
1656                             {
1657                                 StreamSP error_sp (GetAsyncErrorStream());
1658                                 if (error_sp)
1659                                 {
1660                                     error_sp->PutCString(data);
1661                                     error_sp->Flush();
1662                                 }
1663                             }
1664                         }
1665                         else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
1666                         {
1667                             const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1668                             if (data && data[0])
1669                             {
1670                                 StreamSP output_sp (GetAsyncOutputStream());
1671                                 if (output_sp)
1672                                 {
1673                                     output_sp->PutCString(data);
1674                                     output_sp->Flush();
1675                                 }
1676                             }
1677                         }
1678                     }
1679                 }
1680 
1681                 if (m_forward_listener_sp)
1682                     m_forward_listener_sp->AddEvent(event_sp);
1683             }
1684         }
1685     }
1686 }
1687 
1688 lldb::thread_result_t
1689 Debugger::EventHandlerThread (lldb::thread_arg_t arg)
1690 {
1691     ((Debugger *)arg)->DefaultEventHandler();
1692     return NULL;
1693 }
1694 
1695 bool
1696 Debugger::StartEventHandlerThread()
1697 {
1698     if (!m_event_handler_thread.IsJoinable())
1699     {
1700         // We must synchronize with the DefaultEventHandler() thread to ensure
1701         // it is up and running and listening to events before we return from
1702         // this function. We do this by listening to events for the
1703         // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1704         Listener listener("lldb.debugger.event-handler");
1705         listener.StartListeningForEvents(&m_sync_broadcaster, eBroadcastBitEventThreadIsListening);
1706 
1707         // Use larger 8MB stack for this thread
1708         m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread,
1709                                                               this,
1710                                                               NULL,
1711                                                               g_debugger_event_thread_stack_bytes);
1712 
1713         // Make sure DefaultEventHandler() is running and listening to events before we return
1714         // from this function. We are only listening for events of type
1715         // eBroadcastBitEventThreadIsListening so we don't need to check the event, we just need
1716         // to wait an infinite amount of time for it (NULL timeout as the first parameter)
1717         lldb::EventSP event_sp;
1718         listener.WaitForEvent(NULL, event_sp);
1719     }
1720     return m_event_handler_thread.IsJoinable();
1721 }
1722 
1723 void
1724 Debugger::StopEventHandlerThread()
1725 {
1726     if (m_event_handler_thread.IsJoinable())
1727     {
1728         GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
1729         m_event_handler_thread.Join(nullptr);
1730     }
1731 }
1732 
1733 
1734 lldb::thread_result_t
1735 Debugger::IOHandlerThread (lldb::thread_arg_t arg)
1736 {
1737     Debugger *debugger = (Debugger *)arg;
1738     debugger->ExecuteIOHandlers();
1739     debugger->StopEventHandlerThread();
1740     return NULL;
1741 }
1742 
1743 bool
1744 Debugger::HasIOHandlerThread()
1745 {
1746     return m_io_handler_thread.IsJoinable();
1747 }
1748 
1749 bool
1750 Debugger::StartIOHandlerThread()
1751 {
1752     if (!m_io_handler_thread.IsJoinable())
1753         m_io_handler_thread = ThreadLauncher::LaunchThread ("lldb.debugger.io-handler",
1754                                                             IOHandlerThread,
1755                                                             this,
1756                                                             NULL,
1757                                                             8*1024*1024); // Use larger 8MB stack for this thread
1758     return m_io_handler_thread.IsJoinable();
1759 }
1760 
1761 void
1762 Debugger::StopIOHandlerThread()
1763 {
1764     if (m_io_handler_thread.IsJoinable())
1765     {
1766         if (m_input_file_sp)
1767             m_input_file_sp->GetFile().Close();
1768         m_io_handler_thread.Join(nullptr);
1769     }
1770 }
1771 
1772 void
1773 Debugger::JoinIOHandlerThread()
1774 {
1775     if (HasIOHandlerThread())
1776     {
1777         thread_result_t result;
1778         m_io_handler_thread.Join(&result);
1779         m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1780     }
1781 }
1782 
1783 Target *
1784 Debugger::GetDummyTarget()
1785 {
1786     return m_target_list.GetDummyTarget (*this).get();
1787 }
1788 
1789 Target *
1790 Debugger::GetSelectedOrDummyTarget(bool prefer_dummy)
1791 {
1792     Target *target = nullptr;
1793     if (!prefer_dummy)
1794     {
1795         target = m_target_list.GetSelectedTarget().get();
1796         if (target)
1797             return target;
1798     }
1799 
1800     return GetDummyTarget();
1801 }
1802 
1803 Error
1804 Debugger::RunREPL (LanguageType language, const char *repl_options)
1805 {
1806     Error err;
1807     FileSpec repl_executable;
1808 
1809     if (language == eLanguageTypeUnknown)
1810     {
1811         std::set<LanguageType> repl_languages;
1812 
1813         Language::GetLanguagesSupportingREPLs(repl_languages);
1814 
1815         if (repl_languages.size() == 1)
1816         {
1817             language = *repl_languages.begin();
1818         }
1819         else if (repl_languages.size() == 0)
1820         {
1821             err.SetErrorStringWithFormat("LLDB isn't configured with support support for any REPLs.");
1822             return err;
1823         }
1824         else
1825         {
1826             err.SetErrorStringWithFormat("Multiple possible REPL languages.  Please specify a language.");
1827             return err;
1828         }
1829     }
1830 
1831     Target *const target = nullptr; // passing in an empty target means the REPL must create one
1832 
1833     REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1834 
1835     if (!err.Success())
1836     {
1837         return err;
1838     }
1839 
1840     if (!repl_sp)
1841     {
1842         err.SetErrorStringWithFormat("couldn't find a REPL for %s", Language::GetNameForLanguageType(language));
1843         return err;
1844     }
1845 
1846     repl_sp->SetCompilerOptions(repl_options);
1847     repl_sp->RunLoop();
1848 
1849     return err;
1850 }
1851 
1852