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