1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/Debugger.h"
12 #include "lldb/Breakpoint/Breakpoint.h" // for Breakpoint, Brea...
13 #include "lldb/Core/Event.h" // for Event, EventData...
14 #include "lldb/Core/FormatEntity.h"
15 #include "lldb/Core/Listener.h" // for Listener
16 #include "lldb/Core/Mangled.h" // for Mangled
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/State.h"
19 #include "lldb/Core/StreamAsynchronousIO.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/DataFormatters/DataVisualization.h"
22 #include "lldb/Expression/REPL.h"
23 #include "lldb/Host/File.h" // for File, File::kInv...
24 #include "lldb/Host/HostInfo.h"
25 #include "lldb/Host/Terminal.h"
26 #include "lldb/Host/ThreadLauncher.h"
27 #include "lldb/Interpreter/CommandInterpreter.h"
28 #include "lldb/Interpreter/OptionValue.h" // for OptionValue, Opt...
29 #include "lldb/Interpreter/OptionValueProperties.h"
30 #include "lldb/Interpreter/OptionValueSInt64.h"
31 #include "lldb/Interpreter/OptionValueString.h"
32 #include "lldb/Interpreter/Property.h" // for PropertyDefinition
33 #include "lldb/Interpreter/ScriptInterpreter.h" // for ScriptInterpreter
34 #include "lldb/Symbol/Function.h"
35 #include "lldb/Symbol/Symbol.h"
36 #include "lldb/Symbol/SymbolContext.h" // for SymbolContext
37 #include "lldb/Target/Language.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/StructuredDataPlugin.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Target/TargetList.h"
42 #include "lldb/Target/Thread.h"
43 #include "lldb/Target/ThreadList.h" // for ThreadList
44 #include "lldb/Utility/AnsiTerminal.h"
45 #include "lldb/Utility/Log.h" // for LLDB_LOG_OPTION_...
46 #include "lldb/Utility/Stream.h" // for Stream
47 #include "lldb/Utility/StreamCallback.h"
48 #include "lldb/Utility/StreamString.h"
50 #if defined(LLVM_ON_WIN32)
51 #include "lldb/Host/windows/PosixApi.h" // for PATH_MAX
54 #include "llvm/ADT/None.h" // for None
55 #include "llvm/ADT/STLExtras.h" // for make_unique
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/iterator.h" // for iterator_facade_...
58 #include "llvm/Support/DynamicLibrary.h"
59 #include "llvm/Support/FileSystem.h"
60 #include "llvm/Support/Threading.h"
61 #include "llvm/Support/raw_ostream.h" // for raw_fd_ostream
63 #include <list> // for list
64 #include <memory> // for make_shared
66 #include <set> // for set
67 #include <stdio.h> // for size_t, NULL
68 #include <stdlib.h> // for getenv
69 #include <string.h> // for strcmp
70 #include <string> // for string
71 #include <system_error> // for error_code
73 namespace lldb_private {
78 using namespace lldb_private;
80 static lldb::user_id_t g_unique_id = 1;
81 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
83 #pragma mark Static Functions
85 typedef std::vector<DebuggerSP> DebuggerList;
86 static std::recursive_mutex *g_debugger_list_mutex_ptr =
87 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
88 static DebuggerList *g_debugger_list_ptr =
89 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
91 OptionEnumValueElement g_show_disassembly_enum_values[] = {
92 {Debugger::eStopDisassemblyTypeNever, "never",
93 "Never show disassembly when displaying a stop context."},
94 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
95 "Show disassembly when there is no debug information."},
96 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
97 "Show disassembly when there is no source information, or the source file "
98 "is missing when displaying a stop context."},
99 {Debugger::eStopDisassemblyTypeAlways, "always",
100 "Always show disassembly when displaying a stop context."},
101 {0, nullptr, nullptr}};
103 OptionEnumValueElement g_language_enumerators[] = {
104 {eScriptLanguageNone, "none", "Disable scripting languages."},
105 {eScriptLanguagePython, "python",
106 "Select python as the default scripting language."},
107 {eScriptLanguageDefault, "default",
108 "Select the lldb default as the default scripting language."},
109 {0, nullptr, nullptr}};
111 #define MODULE_WITH_FUNC \
113 "${module.file.basename}{`${function.name-with-args}" \
114 "{${frame.no-debug}${function.pc-offset}}}}"
116 #define MODULE_WITH_FUNC_NO_ARGS \
118 "${module.file.basename}{`${function.name-without-args}" \
119 "{${frame.no-debug}${function.pc-offset}}}}"
121 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
122 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
124 #define DEFAULT_THREAD_FORMAT \
125 "thread #${thread.index}: tid = ${thread.id%tid}" \
126 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
127 "{, name = '${thread.name}'}" \
128 "{, queue = '${thread.queue}'}" \
129 "{, activity = '${thread.info.activity.name}'}" \
130 "{, ${thread.info.trace_messages} messages}" \
131 "{, stop reason = ${thread.stop-reason}}" \
132 "{\\nReturn value: ${thread.return-value}}" \
133 "{\\nCompleted expression: ${thread.completed-expression}}" \
136 #define DEFAULT_THREAD_STOP_FORMAT \
137 "thread #${thread.index}{, name = '${thread.name}'}" \
138 "{, queue = '${thread.queue}'}" \
139 "{, activity = '${thread.info.activity.name}'}" \
140 "{, ${thread.info.trace_messages} messages}" \
141 "{, stop reason = ${thread.stop-reason}}" \
142 "{\\nReturn value: ${thread.return-value}}" \
143 "{\\nCompleted expression: ${thread.completed-expression}}" \
146 #define DEFAULT_FRAME_FORMAT \
147 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \
150 #define DEFAULT_FRAME_FORMAT_NO_ARGS \
151 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \
154 // Three parts to this disassembly format specification:
155 // 1. If this is a new function/symbol (no previous symbol/function), print
157 // 2. If this is a symbol context change (different from previous
158 // symbol/function), print
161 // address <+offset>:
162 #define DEFAULT_DISASSEMBLY_FORMAT \
163 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
164 "without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${" \
165 "function.name-without-args}}:\n}{${current-pc-arrow} " \
166 "}${addr-file-or-load}{ " \
167 "<${function.concrete-only-addr-offset-no-padding}>}: "
169 // gdb's disassembly format can be emulated with
170 // ${current-pc-arrow}${addr-file-or-load}{
171 // <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}:
173 // lldb's original format for disassembly would look like this format string -
174 // {${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}
175 // }{${addr-file-or-load}}:
177 #define DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX "${ansi.underline}"
178 #define DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX "${ansi.normal}"
180 static OptionEnumValueElement s_stop_show_column_values[] = {
181 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
182 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
183 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
184 "\"caret-only\" mode was selected."},
185 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
186 "terminal codes when running LLDB with "
187 "color/ANSI enabled."},
188 {eStopShowColumnCaret, "caret",
189 "Highlight the stop column with a caret character (^) underneath the stop "
190 "column. This method introduces a new line in source listings that "
191 "display thread stop locations."},
192 {eStopShowColumnNone, "none", "Do not highlight the stop column."},
193 {0, nullptr, nullptr}};
195 static PropertyDefinition g_properties[] = {
196 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
197 "If true all confirmation prompts will receive their default reply."},
198 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
199 DEFAULT_DISASSEMBLY_FORMAT, nullptr,
200 "The default disassembly format "
201 "string to use when disassembling "
202 "instruction sequences."},
203 {"frame-format", OptionValue::eTypeFormatEntity, true, 0,
204 DEFAULT_FRAME_FORMAT, nullptr,
205 "The default frame format string to use "
206 "when displaying stack frame information "
208 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
209 "Notify the user explicitly if an expression returns void (default: "
211 {"prompt", OptionValue::eTypeString, true,
212 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ",
213 nullptr, "The debugger command line prompt displayed for the user."},
214 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
215 nullptr, g_language_enumerators,
216 "The script language to be used for evaluating user-written scripts."},
217 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr,
219 "The number of disassembly lines to show when displaying a "
221 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
222 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
223 g_show_disassembly_enum_values,
224 "Control when to display disassembly when displaying a stopped context."},
225 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr,
227 "The number of sources lines to display that come after the "
228 "current source line when displaying a stopped context."},
229 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr,
231 "The number of sources lines to display that come before the "
232 "current source line when displaying a stopped context."},
233 {"stop-show-column", OptionValue::eTypeEnum, false,
234 eStopShowColumnAnsiOrCaret, nullptr, s_stop_show_column_values,
235 "If true, LLDB will use the column information from the debug info to "
236 "mark the current position when displaying a stopped context."},
237 {"stop-show-column-ansi-prefix", OptionValue::eTypeFormatEntity, true, 0,
238 DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX, nullptr,
239 "When displaying the column marker in a color-enabled (i.e. ANSI) "
240 "terminal, use the ANSI terminal code specified in this format at the "
241 "immediately before the column to be marked."},
242 {"stop-show-column-ansi-suffix", OptionValue::eTypeFormatEntity, true, 0,
243 DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX, nullptr,
244 "When displaying the column marker in a color-enabled (i.e. ANSI) "
245 "terminal, use the ANSI terminal code specified in this format "
246 "immediately after the column to be marked."},
247 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, nullptr,
248 "The maximum number of columns to use for displaying text."},
249 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
250 DEFAULT_THREAD_FORMAT, nullptr,
251 "The default thread format string to use "
252 "when displaying thread information."},
253 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0,
254 DEFAULT_THREAD_STOP_FORMAT, nullptr,
255 "The default thread format "
256 "string to use when displaying thread "
257 "information as part of the stop display."},
258 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr,
259 nullptr, "Whether to use an external editor or not."},
260 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
261 "Whether to use Ansi color codes or not."},
262 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
264 "If true, LLDB will automatically display small structs in "
265 "one-liner format (default: true)."},
266 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
267 "If true, LLDB will auto indent/outdent code. Currently only supported in "
268 "the REPL (default: true)."},
269 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
270 "If true, LLDB will print the values of variables declared in an "
271 "expression. Currently only supported in the REPL (default: true)."},
272 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, nullptr,
273 "The tab size to use when indenting code in multi-line input mode "
275 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
277 "If true, LLDB will automatically escape non-printable and "
278 "escape characters when formatting strings."},
279 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0,
280 DEFAULT_FRAME_FORMAT_NO_ARGS, nullptr,
281 "The default frame format string to use when displaying stack frame"
282 "information for threads from thread backtrace unique."},
283 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
286 ePropertyAutoConfirm = 0,
287 ePropertyDisassemblyFormat,
288 ePropertyFrameFormat,
291 ePropertyScriptLanguage,
292 ePropertyStopDisassemblyCount,
293 ePropertyStopDisassemblyDisplay,
294 ePropertyStopLineCountAfter,
295 ePropertyStopLineCountBefore,
296 ePropertyStopShowColumn,
297 ePropertyStopShowColumnAnsiPrefix,
298 ePropertyStopShowColumnAnsiSuffix,
299 ePropertyTerminalWidth,
300 ePropertyThreadFormat,
301 ePropertyThreadStopFormat,
302 ePropertyUseExternalEditor,
304 ePropertyAutoOneLineSummaries,
308 ePropertyEscapeNonPrintables,
309 ePropertyFrameFormatUnique,
312 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
314 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
315 VarSetOperationType op,
316 llvm::StringRef property_path,
317 llvm::StringRef value) {
318 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
319 bool is_escape_non_printables = (property_path == "escape-non-printables");
321 LoadScriptFromSymFile load_script_old_value;
322 if (is_load_script && exe_ctx->GetTargetSP()) {
323 target_sp = exe_ctx->GetTargetSP();
324 load_script_old_value =
325 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
327 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
328 if (error.Success()) {
329 // FIXME it would be nice to have "on-change" callbacks for properties
330 if (property_path == g_properties[ePropertyPrompt].name) {
331 llvm::StringRef new_prompt = GetPrompt();
332 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
333 new_prompt, GetUseColor());
336 GetCommandInterpreter().UpdatePrompt(new_prompt);
337 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
338 auto prompt_change_event_sp = std::make_shared<Event>(
339 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
340 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
341 } else if (property_path == g_properties[ePropertyUseColor].name) {
342 // use-color changed. Ping the prompt so it can reset the ansi terminal
344 SetPrompt(GetPrompt());
345 } else if (is_load_script && target_sp &&
346 load_script_old_value == eLoadScriptFromSymFileWarn) {
347 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
348 eLoadScriptFromSymFileTrue) {
349 std::list<Status> errors;
350 StreamString feedback_stream;
351 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
352 StreamFileSP stream_sp(GetErrorFile());
354 for (auto error : errors) {
355 stream_sp->Printf("%s\n", error.AsCString());
357 if (feedback_stream.GetSize())
358 stream_sp->PutCString(feedback_stream.GetString());
362 } else if (is_escape_non_printables) {
363 DataVisualization::ForceUpdate();
369 bool Debugger::GetAutoConfirm() const {
370 const uint32_t idx = ePropertyAutoConfirm;
371 return m_collection_sp->GetPropertyAtIndexAsBoolean(
372 nullptr, idx, g_properties[idx].default_uint_value != 0);
375 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
376 const uint32_t idx = ePropertyDisassemblyFormat;
377 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
380 const FormatEntity::Entry *Debugger::GetFrameFormat() const {
381 const uint32_t idx = ePropertyFrameFormat;
382 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
385 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
386 const uint32_t idx = ePropertyFrameFormatUnique;
387 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
390 bool Debugger::GetNotifyVoid() const {
391 const uint32_t idx = ePropertyNotiftVoid;
392 return m_collection_sp->GetPropertyAtIndexAsBoolean(
393 nullptr, idx, g_properties[idx].default_uint_value != 0);
396 llvm::StringRef Debugger::GetPrompt() const {
397 const uint32_t idx = ePropertyPrompt;
398 return m_collection_sp->GetPropertyAtIndexAsString(
399 nullptr, idx, g_properties[idx].default_cstr_value);
402 void Debugger::SetPrompt(llvm::StringRef p) {
403 const uint32_t idx = ePropertyPrompt;
404 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
405 llvm::StringRef new_prompt = GetPrompt();
407 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
410 GetCommandInterpreter().UpdatePrompt(new_prompt);
413 const FormatEntity::Entry *Debugger::GetThreadFormat() const {
414 const uint32_t idx = ePropertyThreadFormat;
415 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
418 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
419 const uint32_t idx = ePropertyThreadStopFormat;
420 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
423 lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
424 const uint32_t idx = ePropertyScriptLanguage;
425 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
426 nullptr, idx, g_properties[idx].default_uint_value);
429 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
430 const uint32_t idx = ePropertyScriptLanguage;
431 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
435 uint32_t Debugger::GetTerminalWidth() const {
436 const uint32_t idx = ePropertyTerminalWidth;
437 return m_collection_sp->GetPropertyAtIndexAsSInt64(
438 nullptr, idx, g_properties[idx].default_uint_value);
441 bool Debugger::SetTerminalWidth(uint32_t term_width) {
442 const uint32_t idx = ePropertyTerminalWidth;
443 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
446 bool Debugger::GetUseExternalEditor() const {
447 const uint32_t idx = ePropertyUseExternalEditor;
448 return m_collection_sp->GetPropertyAtIndexAsBoolean(
449 nullptr, idx, g_properties[idx].default_uint_value != 0);
452 bool Debugger::SetUseExternalEditor(bool b) {
453 const uint32_t idx = ePropertyUseExternalEditor;
454 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
457 bool Debugger::GetUseColor() const {
458 const uint32_t idx = ePropertyUseColor;
459 return m_collection_sp->GetPropertyAtIndexAsBoolean(
460 nullptr, idx, g_properties[idx].default_uint_value != 0);
463 bool Debugger::SetUseColor(bool b) {
464 const uint32_t idx = ePropertyUseColor;
465 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
466 SetPrompt(GetPrompt());
470 StopShowColumn Debugger::GetStopShowColumn() const {
471 const uint32_t idx = ePropertyStopShowColumn;
472 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
473 nullptr, idx, g_properties[idx].default_uint_value);
476 const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiPrefix() const {
477 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
478 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
481 const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiSuffix() const {
482 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
483 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
486 uint32_t Debugger::GetStopSourceLineCount(bool before) const {
488 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
489 return m_collection_sp->GetPropertyAtIndexAsSInt64(
490 nullptr, idx, g_properties[idx].default_uint_value);
493 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
494 const uint32_t idx = ePropertyStopDisassemblyDisplay;
495 return (Debugger::StopDisassemblyType)
496 m_collection_sp->GetPropertyAtIndexAsEnumeration(
497 nullptr, idx, g_properties[idx].default_uint_value);
500 uint32_t Debugger::GetDisassemblyLineCount() const {
501 const uint32_t idx = ePropertyStopDisassemblyCount;
502 return m_collection_sp->GetPropertyAtIndexAsSInt64(
503 nullptr, idx, g_properties[idx].default_uint_value);
506 bool Debugger::GetAutoOneLineSummaries() const {
507 const uint32_t idx = ePropertyAutoOneLineSummaries;
508 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
511 bool Debugger::GetEscapeNonPrintables() const {
512 const uint32_t idx = ePropertyEscapeNonPrintables;
513 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
516 bool Debugger::GetAutoIndent() const {
517 const uint32_t idx = ePropertyAutoIndent;
518 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
521 bool Debugger::SetAutoIndent(bool b) {
522 const uint32_t idx = ePropertyAutoIndent;
523 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
526 bool Debugger::GetPrintDecls() const {
527 const uint32_t idx = ePropertyPrintDecls;
528 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
531 bool Debugger::SetPrintDecls(bool b) {
532 const uint32_t idx = ePropertyPrintDecls;
533 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
536 uint32_t Debugger::GetTabSize() const {
537 const uint32_t idx = ePropertyTabSize;
538 return m_collection_sp->GetPropertyAtIndexAsUInt64(
539 nullptr, idx, g_properties[idx].default_uint_value);
542 bool Debugger::SetTabSize(uint32_t tab_size) {
543 const uint32_t idx = ePropertyTabSize;
544 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
547 #pragma mark Debugger
549 // const DebuggerPropertiesSP &
550 // Debugger::GetSettings() const
552 // return m_properties_sp;
556 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
557 assert(g_debugger_list_ptr == nullptr &&
558 "Debugger::Initialize called more than once!");
559 g_debugger_list_mutex_ptr = new std::recursive_mutex();
560 g_debugger_list_ptr = new DebuggerList();
561 g_load_plugin_callback = load_plugin_callback;
564 void Debugger::Terminate() {
565 assert(g_debugger_list_ptr &&
566 "Debugger::Terminate called without a matching Debugger::Initialize!");
568 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
569 // Clear our master list of debugger objects
571 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
572 for (const auto &debugger : *g_debugger_list_ptr)
574 g_debugger_list_ptr->clear();
579 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
581 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
583 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
584 if (g_load_plugin_callback) {
585 llvm::sys::DynamicLibrary dynlib =
586 g_load_plugin_callback(shared_from_this(), spec, error);
587 if (dynlib.isValid()) {
588 m_loaded_plugins.push_back(dynlib);
592 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
593 // and if the public API layer isn't available (code is linking against
594 // all of the internal LLDB static libraries), then we can't load plugins
595 error.SetErrorString("Public API layer is not available");
600 static FileSpec::EnumerateDirectoryResult
601 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
602 const FileSpec &file_spec) {
605 static ConstString g_dylibext("dylib");
606 static ConstString g_solibext("so");
609 return FileSpec::eEnumerateDirectoryResultQuit;
611 Debugger *debugger = (Debugger *)baton;
613 namespace fs = llvm::sys::fs;
614 // If we have a regular file, a symbolic link or unknown file type, try
615 // and process the file. We must handle unknown as sometimes the directory
616 // enumeration might be enumerating a file system that doesn't have correct
617 // file type information.
618 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
619 ft == fs::file_type::type_unknown) {
620 FileSpec plugin_file_spec(file_spec);
621 plugin_file_spec.ResolvePath();
623 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
624 plugin_file_spec.GetFileNameExtension() != g_solibext) {
625 return FileSpec::eEnumerateDirectoryResultNext;
628 Status plugin_load_error;
629 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
631 return FileSpec::eEnumerateDirectoryResultNext;
632 } else if (ft == fs::file_type::directory_file ||
633 ft == fs::file_type::symlink_file ||
634 ft == fs::file_type::type_unknown) {
635 // Try and recurse into anything that a directory or symbolic link.
636 // We must also do this for unknown as sometimes the directory enumeration
637 // might be enumerating a file system that doesn't have correct file type
639 return FileSpec::eEnumerateDirectoryResultEnter;
642 return FileSpec::eEnumerateDirectoryResultNext;
645 void Debugger::InstanceInitialize() {
647 const bool find_directories = true;
648 const bool find_files = true;
649 const bool find_other = true;
650 char dir_path[PATH_MAX];
651 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec)) {
652 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
653 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
654 find_other, LoadPluginCallback, this);
658 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec)) {
659 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
660 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
661 find_other, LoadPluginCallback, this);
665 PluginManager::DebuggerInitialize(*this);
668 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
670 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
671 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
672 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
673 g_debugger_list_ptr->push_back(debugger_sp);
675 debugger_sp->InstanceInitialize();
679 void Debugger::Destroy(DebuggerSP &debugger_sp) {
683 debugger_sp->Clear();
685 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
686 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
687 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
688 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
689 if ((*pos).get() == debugger_sp.get()) {
690 g_debugger_list_ptr->erase(pos);
698 Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
699 DebuggerSP debugger_sp;
700 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
701 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
702 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
703 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
704 if ((*pos)->m_instance_name == instance_name) {
713 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
715 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
716 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
717 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
718 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
719 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
727 TargetSP Debugger::FindTargetWithProcess(Process *process) {
729 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
730 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
731 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
732 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
733 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
741 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
742 : UserID(g_unique_id++),
743 Properties(std::make_shared<OptionValueProperties>()),
744 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
745 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
746 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
747 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
748 m_terminal_state(), m_target_list(*this), m_platform_list(),
749 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
750 m_source_manager_ap(), m_source_file_cache(),
751 m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>(
752 *this, eScriptLanguageDefault, false)),
753 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
754 m_event_handler_thread(), m_io_handler_thread(),
755 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
756 m_forward_listener_sp(), m_clear_once() {
757 char instance_cstr[256];
758 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
759 m_instance_name.SetCString(instance_cstr);
761 m_log_callback_stream_sp =
762 std::make_shared<StreamCallback>(log_callback, baton);
763 m_command_interpreter_ap->Initialize();
764 // Always add our default platform to the platform list
765 PlatformSP default_platform_sp(Platform::GetHostPlatform());
766 assert(default_platform_sp);
767 m_platform_list.Append(default_platform_sp, true);
769 m_collection_sp->Initialize(g_properties);
770 m_collection_sp->AppendProperty(
771 ConstString("target"),
772 ConstString("Settings specify to debugging targets."), true,
773 Target::GetGlobalProperties()->GetValueProperties());
774 m_collection_sp->AppendProperty(
775 ConstString("platform"), ConstString("Platform settings."), true,
776 Platform::GetGlobalPlatformProperties()->GetValueProperties());
777 if (m_command_interpreter_ap) {
778 m_collection_sp->AppendProperty(
779 ConstString("interpreter"),
780 ConstString("Settings specify to the debugger's command interpreter."),
781 true, m_command_interpreter_ap->GetValueProperties());
783 OptionValueSInt64 *term_width =
784 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
785 nullptr, ePropertyTerminalWidth);
786 term_width->SetMinimumValue(10);
787 term_width->SetMaximumValue(1024);
789 // Turn off use-color if this is a dumb terminal.
790 const char *term = getenv("TERM");
791 if (term && !strcmp(term, "dumb"))
795 Debugger::~Debugger() { Clear(); }
797 void Debugger::Clear() {
798 //----------------------------------------------------------------------
799 // Make sure we call this function only once. With the C++ global
800 // destructor chain having a list of debuggers and with code that can be
801 // running on other threads, we need to ensure this doesn't happen
804 // The following functions call Debugger::Clear():
805 // Debugger::~Debugger();
806 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
807 // static void Debugger::Terminate();
808 //----------------------------------------------------------------------
809 llvm::call_once(m_clear_once, [this]() {
811 StopIOHandlerThread();
812 StopEventHandlerThread();
813 m_listener_sp->Clear();
814 int num_targets = m_target_list.GetNumTargets();
815 for (int i = 0; i < num_targets; i++) {
816 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
818 ProcessSP process_sp(target_sp->GetProcessSP());
820 process_sp->Finalize();
821 target_sp->Destroy();
824 m_broadcaster_manager_sp->Clear();
826 // Close the input file _before_ we close the input read communications
828 // as it does NOT own the input file, our m_input_file does.
829 m_terminal_state.Clear();
831 m_input_file_sp->GetFile().Close();
833 m_command_interpreter_ap->Clear();
837 bool Debugger::GetCloseInputOnEOF() const {
838 // return m_input_comm.GetCloseOnEOF();
842 void Debugger::SetCloseInputOnEOF(bool b) {
843 // m_input_comm.SetCloseOnEOF(b);
846 bool Debugger::GetAsyncExecution() {
847 return !m_command_interpreter_ap->GetSynchronous();
850 void Debugger::SetAsyncExecution(bool async_execution) {
851 m_command_interpreter_ap->SetSynchronous(!async_execution);
854 void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
856 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
858 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
860 File &in_file = m_input_file_sp->GetFile();
861 if (!in_file.IsValid())
862 in_file.SetStream(stdin, true);
864 // Save away the terminal state if that is relevant, so that we can restore it
865 // in RestoreInputState.
866 SaveInputTerminalState();
869 void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
870 if (m_output_file_sp)
871 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
873 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
875 File &out_file = m_output_file_sp->GetFile();
876 if (!out_file.IsValid())
877 out_file.SetStream(stdout, false);
879 // do not create the ScriptInterpreter just for setting the output file handle
880 // as the constructor will know how to do the right thing on its own
881 const bool can_create = false;
882 ScriptInterpreter *script_interpreter =
883 GetCommandInterpreter().GetScriptInterpreter(can_create);
884 if (script_interpreter)
885 script_interpreter->ResetOutputFileHandle(fh);
888 void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
890 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
892 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
894 File &err_file = m_error_file_sp->GetFile();
895 if (!err_file.IsValid())
896 err_file.SetStream(stderr, false);
899 void Debugger::SaveInputTerminalState() {
900 if (m_input_file_sp) {
901 File &in_file = m_input_file_sp->GetFile();
902 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
903 m_terminal_state.Save(in_file.GetDescriptor(), true);
907 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
909 ExecutionContext Debugger::GetSelectedExecutionContext() {
910 ExecutionContext exe_ctx;
911 TargetSP target_sp(GetSelectedTarget());
912 exe_ctx.SetTargetSP(target_sp);
915 ProcessSP process_sp(target_sp->GetProcessSP());
916 exe_ctx.SetProcessSP(process_sp);
917 if (process_sp && !process_sp->IsRunning()) {
918 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
920 exe_ctx.SetThreadSP(thread_sp);
921 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
922 if (exe_ctx.GetFramePtr() == nullptr)
923 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
930 void Debugger::DispatchInputInterrupt() {
931 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
932 IOHandlerSP reader_sp(m_input_reader_stack.Top());
934 reader_sp->Interrupt();
937 void Debugger::DispatchInputEndOfFile() {
938 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
939 IOHandlerSP reader_sp(m_input_reader_stack.Top());
944 void Debugger::ClearIOHandlers() {
945 // The bottom input reader should be the main debugger input reader. We do
946 // not want to close that one here.
947 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
948 while (m_input_reader_stack.GetSize() > 1) {
949 IOHandlerSP reader_sp(m_input_reader_stack.Top());
951 PopIOHandler(reader_sp);
955 void Debugger::ExecuteIOHandlers() {
957 IOHandlerSP reader_sp(m_input_reader_stack.Top());
963 // Remove all input readers that are done from the top of the stack
965 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
966 if (top_reader_sp && top_reader_sp->GetIsDone())
967 PopIOHandler(top_reader_sp);
975 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
976 return m_input_reader_stack.IsTop(reader_sp);
979 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
980 IOHandler::Type second_top_type) {
981 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
984 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
985 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
986 m_input_reader_stack.PrintAsync(stream.get(), s, len);
989 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
990 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
993 const char *Debugger::GetIOHandlerCommandPrefix() {
994 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
997 const char *Debugger::GetIOHandlerHelpPrologue() {
998 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1001 void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1002 PushIOHandler(reader_sp);
1004 IOHandlerSP top_reader_sp = reader_sp;
1005 while (top_reader_sp) {
1006 top_reader_sp->Run();
1008 if (top_reader_sp.get() == reader_sp.get()) {
1009 if (PopIOHandler(reader_sp))
1014 top_reader_sp = m_input_reader_stack.Top();
1015 if (top_reader_sp && top_reader_sp->GetIsDone())
1016 PopIOHandler(top_reader_sp);
1023 void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1025 StreamFileSP &err) {
1026 // Before an IOHandler runs, it must have in/out/err streams.
1027 // This function is called when one ore more of the streams
1028 // are nullptr. We use the top input reader's in/out/err streams,
1029 // or fall back to the debugger file handles, or we fall back
1030 // onto stdin/stdout/stderr as a last resort.
1032 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1033 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1034 // If no STDIN has been set, then set it appropriately
1037 in = top_reader_sp->GetInputStreamFile();
1039 in = GetInputFile();
1041 // If there is nothing, use stdin
1043 in = std::make_shared<StreamFile>(stdin, false);
1045 // If no STDOUT has been set, then set it appropriately
1048 out = top_reader_sp->GetOutputStreamFile();
1050 out = GetOutputFile();
1052 // If there is nothing, use stdout
1054 out = std::make_shared<StreamFile>(stdout, false);
1056 // If no STDERR has been set, then set it appropriately
1059 err = top_reader_sp->GetErrorStreamFile();
1061 err = GetErrorFile();
1063 // If there is nothing, use stderr
1065 err = std::make_shared<StreamFile>(stdout, false);
1069 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp) {
1073 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1075 // Get the current top input reader...
1076 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1078 // Don't push the same IO handler twice...
1079 if (reader_sp == top_reader_sp)
1082 // Push our new input reader
1083 m_input_reader_stack.Push(reader_sp);
1084 reader_sp->Activate();
1086 // Interrupt the top input reader to it will exit its Run() function
1087 // and let this new input reader take over
1088 if (top_reader_sp) {
1089 top_reader_sp->Deactivate();
1090 top_reader_sp->Cancel();
1094 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1098 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1100 // The reader on the stop of the stack is done, so let the next
1101 // read on the stack refresh its prompt and if there is one...
1102 if (m_input_reader_stack.IsEmpty())
1105 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1107 if (pop_reader_sp != reader_sp)
1110 reader_sp->Deactivate();
1111 reader_sp->Cancel();
1112 m_input_reader_stack.Pop();
1114 reader_sp = m_input_reader_stack.Top();
1116 reader_sp->Activate();
1121 StreamSP Debugger::GetAsyncOutputStream() {
1122 return std::make_shared<StreamAsynchronousIO>(*this, true);
1125 StreamSP Debugger::GetAsyncErrorStream() {
1126 return std::make_shared<StreamAsynchronousIO>(*this, false);
1129 size_t Debugger::GetNumDebuggers() {
1130 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1131 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1132 return g_debugger_list_ptr->size();
1137 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1138 DebuggerSP debugger_sp;
1140 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1141 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1142 if (index < g_debugger_list_ptr->size())
1143 debugger_sp = g_debugger_list_ptr->at(index);
1149 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1150 DebuggerSP debugger_sp;
1152 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1153 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1154 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1155 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1156 if ((*pos)->GetID() == id) {
1165 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1166 const SymbolContext *sc,
1167 const SymbolContext *prev_sc,
1168 const ExecutionContext *exe_ctx,
1169 const Address *addr, Stream &s) {
1170 FormatEntity::Entry format_entry;
1172 if (format == nullptr) {
1173 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1174 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1175 if (format == nullptr) {
1176 FormatEntity::Parse("${addr}: ", format_entry);
1177 format = &format_entry;
1180 bool function_changed = false;
1181 bool initial_function = false;
1182 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1183 if (sc && (sc->function || sc->symbol)) {
1184 if (prev_sc->symbol && sc->symbol) {
1185 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1186 prev_sc->symbol->GetType())) {
1187 function_changed = true;
1189 } else if (prev_sc->function && sc->function) {
1190 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1191 function_changed = true;
1196 // The first context on a list of instructions will have a prev_sc that
1197 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1198 // would return false. But we do get a prev_sc pointer.
1199 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1200 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1201 initial_function = true;
1203 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1204 function_changed, initial_function);
1207 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1209 // For simplicity's sake, I am not going to deal with how to close down any
1210 // open logging streams, I just redirect everything from here on out to the
1212 m_log_callback_stream_sp =
1213 std::make_shared<StreamCallback>(log_callback, baton);
1216 bool Debugger::EnableLog(llvm::StringRef channel,
1217 llvm::ArrayRef<const char *> categories,
1218 llvm::StringRef log_file, uint32_t log_options,
1219 llvm::raw_ostream &error_stream) {
1220 const bool should_close = true;
1221 const bool unbuffered = true;
1223 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
1224 if (m_log_callback_stream_sp) {
1225 log_stream_sp = m_log_callback_stream_sp;
1226 // For now when using the callback mode you always get thread & timestamp.
1228 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1229 } else if (log_file.empty()) {
1230 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1231 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
1233 auto pos = m_log_streams.find(log_file);
1234 if (pos != m_log_streams.end())
1235 log_stream_sp = pos->second.lock();
1236 if (!log_stream_sp) {
1237 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1238 if (log_options & LLDB_LOG_OPTION_APPEND)
1239 flags |= llvm::sys::fs::F_Append;
1241 if (std::error_code ec =
1242 llvm::sys::fs::openFileForWrite(log_file, FD, flags)) {
1243 error_stream << "Unable to open log file: " << ec.message();
1247 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
1248 m_log_streams[log_file] = log_stream_sp;
1251 assert(log_stream_sp);
1253 if (log_options == 0)
1255 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1257 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1261 SourceManager &Debugger::GetSourceManager() {
1262 if (!m_source_manager_ap)
1263 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
1264 return *m_source_manager_ap;
1267 // This function handles events that were broadcast by the process.
1268 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1269 using namespace lldb;
1270 const uint32_t event_type =
1271 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1274 // if (event_type & eBreakpointEventTypeAdded
1275 // || event_type & eBreakpointEventTypeRemoved
1276 // || event_type & eBreakpointEventTypeEnabled
1277 // || event_type & eBreakpointEventTypeDisabled
1278 // || event_type & eBreakpointEventTypeCommandChanged
1279 // || event_type & eBreakpointEventTypeConditionChanged
1280 // || event_type & eBreakpointEventTypeIgnoreChanged
1281 // || event_type & eBreakpointEventTypeLocationsResolved)
1283 // // Don't do anything about these events, since the breakpoint
1284 // commands already echo these actions.
1287 if (event_type & eBreakpointEventTypeLocationsAdded) {
1288 uint32_t num_new_locations =
1289 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1291 if (num_new_locations > 0) {
1292 BreakpointSP breakpoint =
1293 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1294 StreamSP output_sp(GetAsyncOutputStream());
1296 output_sp->Printf("%d location%s added to breakpoint %d\n",
1297 num_new_locations, num_new_locations == 1 ? "" : "s",
1298 breakpoint->GetID());
1303 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1305 // // These locations just get disabled, not sure it is worth spamming
1306 // folks about this on the command line.
1308 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1310 // // This might be an interesting thing to note, but I'm going to
1311 // leave it quiet for now, it just looked noisy.
1315 size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1316 size_t total_bytes = 0;
1317 if (stream == nullptr)
1318 stream = GetOutputFile().get();
1321 // The process has stuff waiting for stdout; get it and write it out to the
1322 // appropriate place.
1323 if (process == nullptr) {
1324 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1326 process = target_sp->GetProcessSP().get();
1331 char stdio_buffer[1024];
1332 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1334 stream->Write(stdio_buffer, len);
1343 size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1344 size_t total_bytes = 0;
1345 if (stream == nullptr)
1346 stream = GetOutputFile().get();
1349 // The process has stuff waiting for stderr; get it and write it out to the
1350 // appropriate place.
1351 if (process == nullptr) {
1352 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1354 process = target_sp->GetProcessSP().get();
1359 char stdio_buffer[1024];
1360 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1362 stream->Write(stdio_buffer, len);
1371 // This function handles events that were broadcast by the process.
1372 void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1373 using namespace lldb;
1374 const uint32_t event_type = event_sp->GetType();
1375 ProcessSP process_sp =
1376 (event_type == Process::eBroadcastBitStructuredData)
1377 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1378 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1380 StreamSP output_stream_sp = GetAsyncOutputStream();
1381 StreamSP error_stream_sp = GetAsyncErrorStream();
1382 const bool gui_enabled = IsForwardingEvents();
1385 bool pop_process_io_handler = false;
1388 bool state_is_stopped = false;
1389 const bool got_state_changed =
1390 (event_type & Process::eBroadcastBitStateChanged) != 0;
1391 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1392 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1393 const bool got_structured_data =
1394 (event_type & Process::eBroadcastBitStructuredData) != 0;
1396 if (got_state_changed) {
1397 StateType event_state =
1398 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1399 state_is_stopped = StateIsStoppedState(event_state, false);
1402 // Display running state changes first before any STDIO
1403 if (got_state_changed && !state_is_stopped) {
1404 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1405 pop_process_io_handler);
1408 // Now display and STDOUT
1409 if (got_stdout || got_state_changed) {
1410 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1413 // Now display and STDERR
1414 if (got_stderr || got_state_changed) {
1415 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1418 // Give structured data events an opportunity to display.
1419 if (got_structured_data) {
1420 StructuredDataPluginSP plugin_sp =
1421 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1423 auto structured_data_sp =
1424 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1425 if (output_stream_sp) {
1426 StreamString content_stream;
1428 plugin_sp->GetDescription(structured_data_sp, content_stream);
1429 if (error.Success()) {
1430 if (!content_stream.GetString().empty()) {
1432 content_stream.PutChar('\n');
1433 content_stream.Flush();
1436 output_stream_sp->PutCString(content_stream.GetString());
1439 error_stream_sp->Printf("Failed to print structured "
1440 "data with plugin %s: %s",
1441 plugin_sp->GetPluginName().AsCString(),
1448 // Now display any stopped state changes after any STDIO
1449 if (got_state_changed && state_is_stopped) {
1450 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1451 pop_process_io_handler);
1454 output_stream_sp->Flush();
1455 error_stream_sp->Flush();
1457 if (pop_process_io_handler)
1458 process_sp->PopProcessIOHandler();
1462 void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1463 // At present the only thread event we handle is the Frame Changed event,
1464 // and all we do for that is just reprint the thread status for that thread.
1465 using namespace lldb;
1466 const uint32_t event_type = event_sp->GetType();
1467 const bool stop_format = true;
1468 if (event_type == Thread::eBroadcastBitStackChanged ||
1469 event_type == Thread::eBroadcastBitThreadSelected) {
1471 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1473 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1478 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1480 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1481 m_forward_listener_sp = listener_sp;
1484 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1485 m_forward_listener_sp.reset();
1488 void Debugger::DefaultEventHandler() {
1489 ListenerSP listener_sp(GetListener());
1490 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1491 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1492 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1493 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1494 Target::eBroadcastBitBreakpointChanged);
1496 BroadcastEventSpec process_event_spec(
1497 broadcaster_class_process,
1498 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1499 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1501 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1502 Thread::eBroadcastBitStackChanged |
1503 Thread::eBroadcastBitThreadSelected);
1505 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1507 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1508 process_event_spec);
1509 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1511 listener_sp->StartListeningForEvents(
1512 m_command_interpreter_ap.get(),
1513 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1514 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1515 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1517 // Let the thread that spawned us know that we have started up and
1518 // that we are now listening to all required events so no events get missed
1519 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1524 if (listener_sp->GetEvent(event_sp, llvm::None)) {
1526 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1528 uint32_t event_type = event_sp->GetType();
1529 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1530 if (broadcaster_class == broadcaster_class_process) {
1531 HandleProcessEvent(event_sp);
1532 } else if (broadcaster_class == broadcaster_class_target) {
1533 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1535 HandleBreakpointEvent(event_sp);
1537 } else if (broadcaster_class == broadcaster_class_thread) {
1538 HandleThreadEvent(event_sp);
1539 } else if (broadcaster == m_command_interpreter_ap.get()) {
1541 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1543 } else if (event_type &
1544 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1545 const char *data = reinterpret_cast<const char *>(
1546 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1547 if (data && data[0]) {
1548 StreamSP error_sp(GetAsyncErrorStream());
1550 error_sp->PutCString(data);
1554 } else if (event_type & CommandInterpreter::
1555 eBroadcastBitAsynchronousOutputData) {
1556 const char *data = reinterpret_cast<const char *>(
1557 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1558 if (data && data[0]) {
1559 StreamSP output_sp(GetAsyncOutputStream());
1561 output_sp->PutCString(data);
1569 if (m_forward_listener_sp)
1570 m_forward_listener_sp->AddEvent(event_sp);
1576 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1577 ((Debugger *)arg)->DefaultEventHandler();
1581 bool Debugger::StartEventHandlerThread() {
1582 if (!m_event_handler_thread.IsJoinable()) {
1583 // We must synchronize with the DefaultEventHandler() thread to ensure
1584 // it is up and running and listening to events before we return from
1585 // this function. We do this by listening to events for the
1586 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1587 ListenerSP listener_sp(
1588 Listener::MakeListener("lldb.debugger.event-handler"));
1589 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1590 eBroadcastBitEventThreadIsListening);
1592 // Use larger 8MB stack for this thread
1593 m_event_handler_thread = ThreadLauncher::LaunchThread(
1594 "lldb.debugger.event-handler", EventHandlerThread, this, nullptr,
1595 g_debugger_event_thread_stack_bytes);
1597 // Make sure DefaultEventHandler() is running and listening to events before
1599 // from this function. We are only listening for events of type
1600 // eBroadcastBitEventThreadIsListening so we don't need to check the event,
1602 // to wait an infinite amount of time for it (nullptr timeout as the first
1604 lldb::EventSP event_sp;
1605 listener_sp->GetEvent(event_sp, llvm::None);
1607 return m_event_handler_thread.IsJoinable();
1610 void Debugger::StopEventHandlerThread() {
1611 if (m_event_handler_thread.IsJoinable()) {
1612 GetCommandInterpreter().BroadcastEvent(
1613 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1614 m_event_handler_thread.Join(nullptr);
1618 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1619 Debugger *debugger = (Debugger *)arg;
1620 debugger->ExecuteIOHandlers();
1621 debugger->StopEventHandlerThread();
1625 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1627 bool Debugger::StartIOHandlerThread() {
1628 if (!m_io_handler_thread.IsJoinable())
1629 m_io_handler_thread = ThreadLauncher::LaunchThread(
1630 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1631 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1632 return m_io_handler_thread.IsJoinable();
1635 void Debugger::StopIOHandlerThread() {
1636 if (m_io_handler_thread.IsJoinable()) {
1637 if (m_input_file_sp)
1638 m_input_file_sp->GetFile().Close();
1639 m_io_handler_thread.Join(nullptr);
1643 void Debugger::JoinIOHandlerThread() {
1644 if (HasIOHandlerThread()) {
1645 thread_result_t result;
1646 m_io_handler_thread.Join(&result);
1647 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1651 Target *Debugger::GetDummyTarget() {
1652 return m_target_list.GetDummyTarget(*this).get();
1655 Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1656 Target *target = nullptr;
1657 if (!prefer_dummy) {
1658 target = m_target_list.GetSelectedTarget().get();
1663 return GetDummyTarget();
1666 Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1668 FileSpec repl_executable;
1670 if (language == eLanguageTypeUnknown) {
1671 std::set<LanguageType> repl_languages;
1673 Language::GetLanguagesSupportingREPLs(repl_languages);
1675 if (repl_languages.size() == 1) {
1676 language = *repl_languages.begin();
1677 } else if (repl_languages.empty()) {
1678 err.SetErrorStringWithFormat(
1679 "LLDB isn't configured with REPL support for any languages.");
1682 err.SetErrorStringWithFormat(
1683 "Multiple possible REPL languages. Please specify a language.");
1688 Target *const target =
1689 nullptr; // passing in an empty target means the REPL must create one
1691 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1693 if (!err.Success()) {
1698 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1699 Language::GetNameForLanguageType(language));
1703 repl_sp->SetCompilerOptions(repl_options);