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