1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/Debugger.h"
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Core/FormatEntity.h"
13 #include "lldb/Core/Mangled.h"
14 #include "lldb/Core/ModuleList.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/StreamAsynchronousIO.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/DataFormatters/DataVisualization.h"
19 #include "lldb/Expression/REPL.h"
20 #include "lldb/Host/File.h"
21 #include "lldb/Host/FileSystem.h"
22 #include "lldb/Host/HostInfo.h"
23 #include "lldb/Host/Terminal.h"
24 #include "lldb/Host/ThreadLauncher.h"
25 #include "lldb/Interpreter/CommandInterpreter.h"
26 #include "lldb/Interpreter/OptionValue.h"
27 #include "lldb/Interpreter/OptionValueProperties.h"
28 #include "lldb/Interpreter/OptionValueSInt64.h"
29 #include "lldb/Interpreter/OptionValueString.h"
30 #include "lldb/Interpreter/Property.h"
31 #include "lldb/Interpreter/ScriptInterpreter.h"
32 #include "lldb/Symbol/Function.h"
33 #include "lldb/Symbol/Symbol.h"
34 #include "lldb/Symbol/SymbolContext.h"
35 #include "lldb/Target/Language.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/StructuredDataPlugin.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/TargetList.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Target/ThreadList.h"
42 #include "lldb/Utility/AnsiTerminal.h"
43 #include "lldb/Utility/Event.h"
44 #include "lldb/Utility/Listener.h"
45 #include "lldb/Utility/Log.h"
46 #include "lldb/Utility/Reproducer.h"
47 #include "lldb/Utility/State.h"
48 #include "lldb/Utility/Stream.h"
49 #include "lldb/Utility/StreamCallback.h"
50 #include "lldb/Utility/StreamString.h"
53 #include "lldb/Host/windows/PosixApi.h"
54 #include "lldb/Host/windows/windows.h"
57 #include "llvm/ADT/None.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/iterator.h"
61 #include "llvm/Support/DynamicLibrary.h"
62 #include "llvm/Support/FileSystem.h"
63 #include "llvm/Support/Process.h"
64 #include "llvm/Support/Threading.h"
65 #include "llvm/Support/raw_ostream.h"
75 #include <system_error>
77 namespace lldb_private {
82 using namespace lldb_private;
84 static lldb::user_id_t g_unique_id = 1;
85 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
87 #pragma mark Static Functions
89 typedef std::vector<DebuggerSP> DebuggerList;
90 static std::recursive_mutex *g_debugger_list_mutex_ptr =
91 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
92 static DebuggerList *g_debugger_list_ptr =
93 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
95 static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
96 {Debugger::eStopDisassemblyTypeNever, "never",
97 "Never show disassembly when displaying a stop context."},
98 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
99 "Show disassembly when there is no debug information."},
100 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
101 "Show disassembly when there is no source information, or the source file "
102 "is missing when displaying a stop context."},
103 {Debugger::eStopDisassemblyTypeAlways, "always",
104 "Always show disassembly when displaying a stop context."} };
106 static constexpr OptionEnumValueElement g_language_enumerators[] = {
107 {eScriptLanguageNone, "none", "Disable scripting languages."},
108 {eScriptLanguagePython, "python",
109 "Select python as the default scripting language."},
110 {eScriptLanguageDefault, "default",
111 "Select the lldb default as the default scripting language."} };
113 #define MODULE_WITH_FUNC \
115 "${module.file.basename}{`${function.name-with-args}" \
116 "{${frame.no-debug}${function.pc-offset}}}}"
118 #define MODULE_WITH_FUNC_NO_ARGS \
120 "${module.file.basename}{`${function.name-without-args}" \
121 "{${frame.no-debug}${function.pc-offset}}}}"
123 #define FILE_AND_LINE \
124 "{ at ${ansi.fg.cyan}${line.file.basename}${ansi.normal}" \
125 ":${ansi.fg.yellow}${line.number}${ansi.normal}" \
126 "{:${ansi.fg.yellow}${line.column}${ansi.normal}}}"
128 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
130 #define IS_ARTIFICIAL "{${frame.is-artificial} [artificial]}"
132 #define DEFAULT_THREAD_FORMAT \
133 "thread #${thread.index}: tid = ${thread.id%tid}" \
134 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
135 "{, name = ${ansi.fg.green}'${thread.name}'${ansi.normal}}" \
136 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
138 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
139 "{, ${thread.info.trace_messages} messages}" \
140 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
141 "{\\nReturn value: ${thread.return-value}}" \
142 "{\\nCompleted expression: ${thread.completed-expression}}" \
145 #define DEFAULT_THREAD_STOP_FORMAT \
146 "thread #${thread.index}{, name = '${thread.name}'}" \
147 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
149 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
150 "{, ${thread.info.trace_messages} messages}" \
151 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
152 "{\\nReturn value: ${thread.return-value}}" \
153 "{\\nCompleted expression: ${thread.completed-expression}}" \
156 #define DEFAULT_FRAME_FORMAT \
157 "frame #${frame.index}: " \
158 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC FILE_AND_LINE \
159 IS_OPTIMIZED IS_ARTIFICIAL "\\n"
161 #define DEFAULT_FRAME_FORMAT_NO_ARGS \
162 "frame #${frame.index}: " \
163 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC_NO_ARGS \
164 FILE_AND_LINE IS_OPTIMIZED IS_ARTIFICIAL "\\n"
166 // Three parts to this disassembly format specification:
167 // 1. If this is a new function/symbol (no previous symbol/function), print
169 // 2. If this is a symbol context change (different from previous
170 // symbol/function), print
173 // address <+offset>:
174 #define DEFAULT_DISASSEMBLY_FORMAT \
175 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
176 "without-args}}:\\n}{${function.changed}\\n{${module.file.basename}`}{${" \
177 "function.name-without-args}}:\\n}{${current-pc-arrow} " \
178 "}${addr-file-or-load}{ " \
179 "<${function.concrete-only-addr-offset-no-padding}>}: "
181 // gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
182 // file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
183 // offset-no-padding}>}:
185 // lldb's original format for disassembly would look like this format string -
186 // {${function.initial-function}{${module.file.basename}`}{${function.name-
188 // args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
189 // without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
191 static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
192 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
193 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
194 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
195 "\"caret-only\" mode was selected."},
196 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
197 "terminal codes when running LLDB with "
198 "color/ANSI enabled."},
199 {eStopShowColumnCaret, "caret",
200 "Highlight the stop column with a caret character (^) underneath the stop "
201 "column. This method introduces a new line in source listings that "
202 "display thread stop locations."},
203 {eStopShowColumnNone, "none", "Do not highlight the stop column."}};
205 static constexpr PropertyDefinition g_properties[] = {
206 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, {},
207 "If true all confirmation prompts will receive their default reply."},
208 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
209 DEFAULT_DISASSEMBLY_FORMAT, {},
210 "The default disassembly format "
211 "string to use when disassembling "
212 "instruction sequences."},
213 {"frame-format", OptionValue::eTypeFormatEntity, true, 0,
214 DEFAULT_FRAME_FORMAT, {},
215 "The default frame format string to use "
216 "when displaying stack frame information "
218 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, {},
219 "Notify the user explicitly if an expression returns void (default: "
221 {"prompt", OptionValue::eTypeString, true,
222 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", {},
223 "The debugger command line prompt displayed for the user."},
224 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
225 nullptr, OptionEnumValues(g_language_enumerators),
226 "The script language to be used for evaluating user-written scripts."},
227 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr, {},
228 "The number of disassembly lines to show when displaying a "
230 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
231 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
232 OptionEnumValues(g_show_disassembly_enum_values),
233 "Control when to display disassembly when displaying a stopped context."},
234 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr, {},
235 "The number of sources lines to display that come after the "
236 "current source line when displaying a stopped context."},
237 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr, {},
238 "The number of sources lines to display that come before the "
239 "current source line when displaying a stopped context."},
240 {"highlight-source", OptionValue::eTypeBoolean, true, true, nullptr, {},
241 "If true, LLDB will highlight the displayed source code."},
242 {"stop-show-column", OptionValue::eTypeEnum, false,
243 eStopShowColumnAnsiOrCaret, nullptr, OptionEnumValues(s_stop_show_column_values),
244 "If true, LLDB will use the column information from the debug info to "
245 "mark the current position when displaying a stopped context."},
246 {"stop-show-column-ansi-prefix", OptionValue::eTypeString, true, 0,
247 "${ansi.underline}", {},
248 "When displaying the column marker in a color-enabled (i.e. ANSI) "
249 "terminal, use the ANSI terminal code specified in this format at the "
250 "immediately before the column to be marked."},
251 {"stop-show-column-ansi-suffix", OptionValue::eTypeString, true, 0,
252 "${ansi.normal}", {},
253 "When displaying the column marker in a color-enabled (i.e. ANSI) "
254 "terminal, use the ANSI terminal code specified in this format "
255 "immediately after the column to be marked."},
256 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, {},
257 "The maximum number of columns to use for displaying text."},
258 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
259 DEFAULT_THREAD_FORMAT, {},
260 "The default thread format string to use "
261 "when displaying thread information."},
262 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0,
263 DEFAULT_THREAD_STOP_FORMAT, {},
264 "The default thread format "
265 "string to use when displaying thread "
266 "information as part of the stop display."},
267 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr, {},
268 "Whether to use an external editor or not."},
269 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, {},
270 "Whether to use Ansi color codes or not."},
271 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
273 "If true, LLDB will automatically display small structs in "
274 "one-liner format (default: true)."},
275 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, {},
276 "If true, LLDB will auto indent/outdent code. Currently only supported in "
277 "the REPL (default: true)."},
278 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, {},
279 "If true, LLDB will print the values of variables declared in an "
280 "expression. Currently only supported in the REPL (default: true)."},
281 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, {},
282 "The tab size to use when indenting code in multi-line input mode "
284 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
286 "If true, LLDB will automatically escape non-printable and "
287 "escape characters when formatting strings."},
288 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0,
289 DEFAULT_FRAME_FORMAT_NO_ARGS, {},
290 "The default frame format string to use when displaying stack frame"
291 "information for threads from thread backtrace unique."}};
294 ePropertyAutoConfirm = 0,
295 ePropertyDisassemblyFormat,
296 ePropertyFrameFormat,
299 ePropertyScriptLanguage,
300 ePropertyStopDisassemblyCount,
301 ePropertyStopDisassemblyDisplay,
302 ePropertyStopLineCountAfter,
303 ePropertyStopLineCountBefore,
304 ePropertyHighlightSource,
305 ePropertyStopShowColumn,
306 ePropertyStopShowColumnAnsiPrefix,
307 ePropertyStopShowColumnAnsiSuffix,
308 ePropertyTerminalWidth,
309 ePropertyThreadFormat,
310 ePropertyThreadStopFormat,
311 ePropertyUseExternalEditor,
313 ePropertyAutoOneLineSummaries,
317 ePropertyEscapeNonPrintables,
318 ePropertyFrameFormatUnique,
321 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
323 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
324 VarSetOperationType op,
325 llvm::StringRef property_path,
326 llvm::StringRef value) {
327 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
328 bool is_escape_non_printables = (property_path == "escape-non-printables");
330 LoadScriptFromSymFile load_script_old_value;
331 if (is_load_script && exe_ctx->GetTargetSP()) {
332 target_sp = exe_ctx->GetTargetSP();
333 load_script_old_value =
334 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
336 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
337 if (error.Success()) {
338 // FIXME it would be nice to have "on-change" callbacks for properties
339 if (property_path == g_properties[ePropertyPrompt].name) {
340 llvm::StringRef new_prompt = GetPrompt();
341 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
342 new_prompt, GetUseColor());
345 GetCommandInterpreter().UpdatePrompt(new_prompt);
346 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
347 auto prompt_change_event_sp = std::make_shared<Event>(
348 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
349 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
350 } else if (property_path == g_properties[ePropertyUseColor].name) {
351 // use-color changed. Ping the prompt so it can reset the ansi terminal
353 SetPrompt(GetPrompt());
354 } else if (is_load_script && target_sp &&
355 load_script_old_value == eLoadScriptFromSymFileWarn) {
356 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
357 eLoadScriptFromSymFileTrue) {
358 std::list<Status> errors;
359 StreamString feedback_stream;
360 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
361 StreamFileSP stream_sp(GetErrorFile());
363 for (auto error : errors) {
364 stream_sp->Printf("%s\n", error.AsCString());
366 if (feedback_stream.GetSize())
367 stream_sp->PutCString(feedback_stream.GetString());
371 } else if (is_escape_non_printables) {
372 DataVisualization::ForceUpdate();
378 bool Debugger::GetAutoConfirm() const {
379 const uint32_t idx = ePropertyAutoConfirm;
380 return m_collection_sp->GetPropertyAtIndexAsBoolean(
381 nullptr, idx, g_properties[idx].default_uint_value != 0);
384 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
385 const uint32_t idx = ePropertyDisassemblyFormat;
386 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
389 const FormatEntity::Entry *Debugger::GetFrameFormat() const {
390 const uint32_t idx = ePropertyFrameFormat;
391 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
394 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
395 const uint32_t idx = ePropertyFrameFormatUnique;
396 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
399 bool Debugger::GetNotifyVoid() const {
400 const uint32_t idx = ePropertyNotiftVoid;
401 return m_collection_sp->GetPropertyAtIndexAsBoolean(
402 nullptr, idx, g_properties[idx].default_uint_value != 0);
405 llvm::StringRef Debugger::GetPrompt() const {
406 const uint32_t idx = ePropertyPrompt;
407 return m_collection_sp->GetPropertyAtIndexAsString(
408 nullptr, idx, g_properties[idx].default_cstr_value);
411 void Debugger::SetPrompt(llvm::StringRef p) {
412 const uint32_t idx = ePropertyPrompt;
413 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
414 llvm::StringRef new_prompt = GetPrompt();
416 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
419 GetCommandInterpreter().UpdatePrompt(new_prompt);
422 llvm::StringRef Debugger::GetReproducerPath() const {
423 auto &r = repro::Reproducer::Instance();
424 return r.GetReproducerPath().GetCString();
427 const FormatEntity::Entry *Debugger::GetThreadFormat() const {
428 const uint32_t idx = ePropertyThreadFormat;
429 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
432 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
433 const uint32_t idx = ePropertyThreadStopFormat;
434 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
437 lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
438 const uint32_t idx = ePropertyScriptLanguage;
439 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
440 nullptr, idx, g_properties[idx].default_uint_value);
443 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
444 const uint32_t idx = ePropertyScriptLanguage;
445 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
449 uint32_t Debugger::GetTerminalWidth() const {
450 const uint32_t idx = ePropertyTerminalWidth;
451 return m_collection_sp->GetPropertyAtIndexAsSInt64(
452 nullptr, idx, g_properties[idx].default_uint_value);
455 bool Debugger::SetTerminalWidth(uint32_t term_width) {
456 const uint32_t idx = ePropertyTerminalWidth;
457 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
460 bool Debugger::GetUseExternalEditor() const {
461 const uint32_t idx = ePropertyUseExternalEditor;
462 return m_collection_sp->GetPropertyAtIndexAsBoolean(
463 nullptr, idx, g_properties[idx].default_uint_value != 0);
466 bool Debugger::SetUseExternalEditor(bool b) {
467 const uint32_t idx = ePropertyUseExternalEditor;
468 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
471 bool Debugger::GetUseColor() const {
472 const uint32_t idx = ePropertyUseColor;
473 return m_collection_sp->GetPropertyAtIndexAsBoolean(
474 nullptr, idx, g_properties[idx].default_uint_value != 0);
477 bool Debugger::SetUseColor(bool b) {
478 const uint32_t idx = ePropertyUseColor;
479 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
480 SetPrompt(GetPrompt());
484 bool Debugger::GetHighlightSource() const {
485 const uint32_t idx = ePropertyHighlightSource;
486 return m_collection_sp->GetPropertyAtIndexAsBoolean(
487 nullptr, idx, g_properties[idx].default_uint_value);
490 StopShowColumn Debugger::GetStopShowColumn() const {
491 const uint32_t idx = ePropertyStopShowColumn;
492 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
493 nullptr, idx, g_properties[idx].default_uint_value);
496 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
497 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
498 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
501 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
502 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
503 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
506 uint32_t Debugger::GetStopSourceLineCount(bool before) const {
508 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
509 return m_collection_sp->GetPropertyAtIndexAsSInt64(
510 nullptr, idx, g_properties[idx].default_uint_value);
513 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
514 const uint32_t idx = ePropertyStopDisassemblyDisplay;
515 return (Debugger::StopDisassemblyType)
516 m_collection_sp->GetPropertyAtIndexAsEnumeration(
517 nullptr, idx, g_properties[idx].default_uint_value);
520 uint32_t Debugger::GetDisassemblyLineCount() const {
521 const uint32_t idx = ePropertyStopDisassemblyCount;
522 return m_collection_sp->GetPropertyAtIndexAsSInt64(
523 nullptr, idx, g_properties[idx].default_uint_value);
526 bool Debugger::GetAutoOneLineSummaries() const {
527 const uint32_t idx = ePropertyAutoOneLineSummaries;
528 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
531 bool Debugger::GetEscapeNonPrintables() const {
532 const uint32_t idx = ePropertyEscapeNonPrintables;
533 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
536 bool Debugger::GetAutoIndent() const {
537 const uint32_t idx = ePropertyAutoIndent;
538 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
541 bool Debugger::SetAutoIndent(bool b) {
542 const uint32_t idx = ePropertyAutoIndent;
543 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
546 bool Debugger::GetPrintDecls() const {
547 const uint32_t idx = ePropertyPrintDecls;
548 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
551 bool Debugger::SetPrintDecls(bool b) {
552 const uint32_t idx = ePropertyPrintDecls;
553 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
556 uint32_t Debugger::GetTabSize() const {
557 const uint32_t idx = ePropertyTabSize;
558 return m_collection_sp->GetPropertyAtIndexAsUInt64(
559 nullptr, idx, g_properties[idx].default_uint_value);
562 bool Debugger::SetTabSize(uint32_t tab_size) {
563 const uint32_t idx = ePropertyTabSize;
564 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
567 #pragma mark Debugger
569 // const DebuggerPropertiesSP &
570 // Debugger::GetSettings() const
572 // return m_properties_sp;
576 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
577 assert(g_debugger_list_ptr == nullptr &&
578 "Debugger::Initialize called more than once!");
579 g_debugger_list_mutex_ptr = new std::recursive_mutex();
580 g_debugger_list_ptr = new DebuggerList();
581 g_load_plugin_callback = load_plugin_callback;
584 void Debugger::Terminate() {
585 assert(g_debugger_list_ptr &&
586 "Debugger::Terminate called without a matching Debugger::Initialize!");
588 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
589 // Clear our master list of debugger objects
591 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
592 for (const auto &debugger : *g_debugger_list_ptr)
594 g_debugger_list_ptr->clear();
599 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
601 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
603 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
604 if (g_load_plugin_callback) {
605 llvm::sys::DynamicLibrary dynlib =
606 g_load_plugin_callback(shared_from_this(), spec, error);
607 if (dynlib.isValid()) {
608 m_loaded_plugins.push_back(dynlib);
612 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
613 // if the public API layer isn't available (code is linking against all of
614 // the internal LLDB static libraries), then we can't load plugins
615 error.SetErrorString("Public API layer is not available");
620 static FileSystem::EnumerateDirectoryResult
621 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
622 llvm::StringRef path) {
625 static ConstString g_dylibext(".dylib");
626 static ConstString g_solibext(".so");
629 return FileSystem::eEnumerateDirectoryResultQuit;
631 Debugger *debugger = (Debugger *)baton;
633 namespace fs = llvm::sys::fs;
634 // If we have a regular file, a symbolic link or unknown file type, try and
635 // process the file. We must handle unknown as sometimes the directory
636 // enumeration might be enumerating a file system that doesn't have correct
637 // file type information.
638 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
639 ft == fs::file_type::type_unknown) {
640 FileSpec plugin_file_spec(path);
641 FileSystem::Instance().Resolve(plugin_file_spec);
643 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
644 plugin_file_spec.GetFileNameExtension() != g_solibext) {
645 return FileSystem::eEnumerateDirectoryResultNext;
648 Status plugin_load_error;
649 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
651 return FileSystem::eEnumerateDirectoryResultNext;
652 } else if (ft == fs::file_type::directory_file ||
653 ft == fs::file_type::symlink_file ||
654 ft == fs::file_type::type_unknown) {
655 // Try and recurse into anything that a directory or symbolic link. We must
656 // also do this for unknown as sometimes the directory enumeration might be
657 // enumerating a file system that doesn't have correct file type
659 return FileSystem::eEnumerateDirectoryResultEnter;
662 return FileSystem::eEnumerateDirectoryResultNext;
665 void Debugger::InstanceInitialize() {
666 const bool find_directories = true;
667 const bool find_files = true;
668 const bool find_other = true;
669 char dir_path[PATH_MAX];
670 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
671 if (FileSystem::Instance().Exists(dir_spec) &&
672 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
673 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
674 find_files, find_other,
675 LoadPluginCallback, this);
679 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
680 if (FileSystem::Instance().Exists(dir_spec) &&
681 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
682 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
683 find_files, find_other,
684 LoadPluginCallback, this);
688 PluginManager::DebuggerInitialize(*this);
691 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
693 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
694 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
695 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
696 g_debugger_list_ptr->push_back(debugger_sp);
698 debugger_sp->InstanceInitialize();
702 void Debugger::Destroy(DebuggerSP &debugger_sp) {
706 debugger_sp->Clear();
708 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
709 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
710 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
711 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
712 if ((*pos).get() == debugger_sp.get()) {
713 g_debugger_list_ptr->erase(pos);
721 Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
722 DebuggerSP debugger_sp;
723 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
724 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
725 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
726 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
727 if ((*pos)->m_instance_name == instance_name) {
736 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
738 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
739 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
740 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
741 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
742 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
750 TargetSP Debugger::FindTargetWithProcess(Process *process) {
752 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
753 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
754 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
755 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
756 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
764 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
765 : UserID(g_unique_id++),
766 Properties(std::make_shared<OptionValueProperties>()),
767 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
768 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
769 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
770 m_input_recorder(nullptr),
771 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
772 m_terminal_state(), m_target_list(*this), m_platform_list(),
773 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
774 m_source_manager_up(), m_source_file_cache(),
775 m_command_interpreter_up(
776 llvm::make_unique<CommandInterpreter>(*this, false)),
777 m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(),
778 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
779 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
780 m_forward_listener_sp(), m_clear_once() {
781 char instance_cstr[256];
782 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
783 m_instance_name.SetCString(instance_cstr);
785 m_log_callback_stream_sp =
786 std::make_shared<StreamCallback>(log_callback, baton);
787 m_command_interpreter_up->Initialize();
788 // Always add our default platform to the platform list
789 PlatformSP default_platform_sp(Platform::GetHostPlatform());
790 assert(default_platform_sp);
791 m_platform_list.Append(default_platform_sp, true);
793 m_collection_sp->Initialize(g_properties);
794 m_collection_sp->AppendProperty(
795 ConstString("target"),
796 ConstString("Settings specify to debugging targets."), true,
797 Target::GetGlobalProperties()->GetValueProperties());
798 m_collection_sp->AppendProperty(
799 ConstString("platform"), ConstString("Platform settings."), true,
800 Platform::GetGlobalPlatformProperties()->GetValueProperties());
801 m_collection_sp->AppendProperty(
802 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
803 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
804 if (m_command_interpreter_up) {
805 m_collection_sp->AppendProperty(
806 ConstString("interpreter"),
807 ConstString("Settings specify to the debugger's command interpreter."),
808 true, m_command_interpreter_up->GetValueProperties());
810 OptionValueSInt64 *term_width =
811 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
812 nullptr, ePropertyTerminalWidth);
813 term_width->SetMinimumValue(10);
814 term_width->SetMaximumValue(1024);
816 // Turn off use-color if this is a dumb terminal.
817 const char *term = getenv("TERM");
818 if (term && !strcmp(term, "dumb"))
820 // Turn off use-color if we don't write to a terminal with color support.
821 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
824 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
825 // Enabling use of ANSI color codes because LLDB is using them to highlight
827 llvm::sys::Process::UseANSIEscapeCodes(true);
831 Debugger::~Debugger() { Clear(); }
833 void Debugger::Clear() {
834 // Make sure we call this function only once. With the C++ global destructor
835 // chain having a list of debuggers and with code that can be running on
836 // other threads, we need to ensure this doesn't happen multiple times.
838 // The following functions call Debugger::Clear():
839 // Debugger::~Debugger();
840 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
841 // static void Debugger::Terminate();
842 llvm::call_once(m_clear_once, [this]() {
844 StopIOHandlerThread();
845 StopEventHandlerThread();
846 m_listener_sp->Clear();
847 int num_targets = m_target_list.GetNumTargets();
848 for (int i = 0; i < num_targets; i++) {
849 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
851 ProcessSP process_sp(target_sp->GetProcessSP());
853 process_sp->Finalize();
854 target_sp->Destroy();
857 m_broadcaster_manager_sp->Clear();
859 // Close the input file _before_ we close the input read communications
860 // class as it does NOT own the input file, our m_input_file does.
861 m_terminal_state.Clear();
863 m_input_file_sp->GetFile().Close();
865 m_command_interpreter_up->Clear();
869 bool Debugger::GetCloseInputOnEOF() const {
870 // return m_input_comm.GetCloseOnEOF();
874 void Debugger::SetCloseInputOnEOF(bool b) {
875 // m_input_comm.SetCloseOnEOF(b);
878 bool Debugger::GetAsyncExecution() {
879 return !m_command_interpreter_up->GetSynchronous();
882 void Debugger::SetAsyncExecution(bool async_execution) {
883 m_command_interpreter_up->SetSynchronous(!async_execution);
886 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
888 void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership,
889 repro::DataRecorder *recorder) {
890 m_input_recorder = recorder;
892 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
894 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
896 File &in_file = m_input_file_sp->GetFile();
897 if (!in_file.IsValid())
898 in_file.SetStream(stdin, true);
900 // Save away the terminal state if that is relevant, so that we can restore
901 // it in RestoreInputState.
902 SaveInputTerminalState();
905 void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
906 if (m_output_file_sp)
907 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
909 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
911 File &out_file = m_output_file_sp->GetFile();
912 if (!out_file.IsValid())
913 out_file.SetStream(stdout, false);
915 // Do not create the ScriptInterpreter just for setting the output file
916 // handle as the constructor will know how to do the right thing on its own.
917 if (ScriptInterpreter *script_interpreter =
918 GetScriptInterpreter(/*can_create=*/false))
919 script_interpreter->ResetOutputFileHandle(fh);
922 void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
924 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
926 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
928 File &err_file = m_error_file_sp->GetFile();
929 if (!err_file.IsValid())
930 err_file.SetStream(stderr, false);
933 void Debugger::SaveInputTerminalState() {
934 if (m_input_file_sp) {
935 File &in_file = m_input_file_sp->GetFile();
936 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
937 m_terminal_state.Save(in_file.GetDescriptor(), true);
941 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
943 ExecutionContext Debugger::GetSelectedExecutionContext() {
944 ExecutionContext exe_ctx;
945 TargetSP target_sp(GetSelectedTarget());
946 exe_ctx.SetTargetSP(target_sp);
949 ProcessSP process_sp(target_sp->GetProcessSP());
950 exe_ctx.SetProcessSP(process_sp);
951 if (process_sp && !process_sp->IsRunning()) {
952 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
954 exe_ctx.SetThreadSP(thread_sp);
955 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
956 if (exe_ctx.GetFramePtr() == nullptr)
957 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
964 void Debugger::DispatchInputInterrupt() {
965 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
966 IOHandlerSP reader_sp(m_input_reader_stack.Top());
968 reader_sp->Interrupt();
971 void Debugger::DispatchInputEndOfFile() {
972 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
973 IOHandlerSP reader_sp(m_input_reader_stack.Top());
978 void Debugger::ClearIOHandlers() {
979 // The bottom input reader should be the main debugger input reader. We do
980 // not want to close that one here.
981 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
982 while (m_input_reader_stack.GetSize() > 1) {
983 IOHandlerSP reader_sp(m_input_reader_stack.Top());
985 PopIOHandler(reader_sp);
989 void Debugger::ExecuteIOHandlers() {
991 IOHandlerSP reader_sp(m_input_reader_stack.Top());
997 // Remove all input readers that are done from the top of the stack
999 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
1000 if (top_reader_sp && top_reader_sp->GetIsDone())
1001 PopIOHandler(top_reader_sp);
1009 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
1010 return m_input_reader_stack.IsTop(reader_sp);
1013 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
1014 IOHandler::Type second_top_type) {
1015 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1018 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1019 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
1020 m_input_reader_stack.PrintAsync(stream.get(), s, len);
1023 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1024 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
1027 const char *Debugger::GetIOHandlerCommandPrefix() {
1028 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
1031 const char *Debugger::GetIOHandlerHelpPrologue() {
1032 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1035 void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1036 PushIOHandler(reader_sp);
1038 IOHandlerSP top_reader_sp = reader_sp;
1039 while (top_reader_sp) {
1040 top_reader_sp->Run();
1042 if (top_reader_sp.get() == reader_sp.get()) {
1043 if (PopIOHandler(reader_sp))
1048 top_reader_sp = m_input_reader_stack.Top();
1049 if (top_reader_sp && top_reader_sp->GetIsDone())
1050 PopIOHandler(top_reader_sp);
1057 void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1059 StreamFileSP &err) {
1060 // Before an IOHandler runs, it must have in/out/err streams. This function
1061 // is called when one ore more of the streams are nullptr. We use the top
1062 // input reader's in/out/err streams, or fall back to the debugger file
1063 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1065 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1066 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1067 // If no STDIN has been set, then set it appropriately
1070 in = top_reader_sp->GetInputStreamFile();
1072 in = GetInputFile();
1074 // If there is nothing, use stdin
1076 in = std::make_shared<StreamFile>(stdin, false);
1078 // If no STDOUT has been set, then set it appropriately
1081 out = top_reader_sp->GetOutputStreamFile();
1083 out = GetOutputFile();
1085 // If there is nothing, use stdout
1087 out = std::make_shared<StreamFile>(stdout, false);
1089 // If no STDERR has been set, then set it appropriately
1092 err = top_reader_sp->GetErrorStreamFile();
1094 err = GetErrorFile();
1096 // If there is nothing, use stderr
1098 err = std::make_shared<StreamFile>(stdout, false);
1102 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1103 bool cancel_top_handler) {
1107 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1109 // Get the current top input reader...
1110 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1112 // Don't push the same IO handler twice...
1113 if (reader_sp == top_reader_sp)
1116 // Push our new input reader
1117 m_input_reader_stack.Push(reader_sp);
1118 reader_sp->Activate();
1120 // Interrupt the top input reader to it will exit its Run() function and let
1121 // this new input reader take over
1122 if (top_reader_sp) {
1123 top_reader_sp->Deactivate();
1124 if (cancel_top_handler)
1125 top_reader_sp->Cancel();
1129 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1133 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1135 // The reader on the stop of the stack is done, so let the next read on the
1136 // stack refresh its prompt and if there is one...
1137 if (m_input_reader_stack.IsEmpty())
1140 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1142 if (pop_reader_sp != reader_sp)
1145 reader_sp->Deactivate();
1146 reader_sp->Cancel();
1147 m_input_reader_stack.Pop();
1149 reader_sp = m_input_reader_stack.Top();
1151 reader_sp->Activate();
1156 StreamSP Debugger::GetAsyncOutputStream() {
1157 return std::make_shared<StreamAsynchronousIO>(*this, true);
1160 StreamSP Debugger::GetAsyncErrorStream() {
1161 return std::make_shared<StreamAsynchronousIO>(*this, false);
1164 size_t Debugger::GetNumDebuggers() {
1165 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1166 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1167 return g_debugger_list_ptr->size();
1172 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1173 DebuggerSP debugger_sp;
1175 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1176 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1177 if (index < g_debugger_list_ptr->size())
1178 debugger_sp = g_debugger_list_ptr->at(index);
1184 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1185 DebuggerSP debugger_sp;
1187 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1188 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1189 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1190 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1191 if ((*pos)->GetID() == id) {
1200 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1201 const SymbolContext *sc,
1202 const SymbolContext *prev_sc,
1203 const ExecutionContext *exe_ctx,
1204 const Address *addr, Stream &s) {
1205 FormatEntity::Entry format_entry;
1207 if (format == nullptr) {
1208 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1209 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1210 if (format == nullptr) {
1211 FormatEntity::Parse("${addr}: ", format_entry);
1212 format = &format_entry;
1215 bool function_changed = false;
1216 bool initial_function = false;
1217 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1218 if (sc && (sc->function || sc->symbol)) {
1219 if (prev_sc->symbol && sc->symbol) {
1220 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1221 prev_sc->symbol->GetType())) {
1222 function_changed = true;
1224 } else if (prev_sc->function && sc->function) {
1225 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1226 function_changed = true;
1231 // The first context on a list of instructions will have a prev_sc that has
1232 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1233 // would return false. But we do get a prev_sc pointer.
1234 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1235 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1236 initial_function = true;
1238 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1239 function_changed, initial_function);
1242 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1244 // For simplicity's sake, I am not going to deal with how to close down any
1245 // open logging streams, I just redirect everything from here on out to the
1247 m_log_callback_stream_sp =
1248 std::make_shared<StreamCallback>(log_callback, baton);
1251 bool Debugger::EnableLog(llvm::StringRef channel,
1252 llvm::ArrayRef<const char *> categories,
1253 llvm::StringRef log_file, uint32_t log_options,
1254 llvm::raw_ostream &error_stream) {
1255 const bool should_close = true;
1256 const bool unbuffered = true;
1258 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
1259 if (m_log_callback_stream_sp) {
1260 log_stream_sp = m_log_callback_stream_sp;
1261 // For now when using the callback mode you always get thread & timestamp.
1263 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1264 } else if (log_file.empty()) {
1265 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1266 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
1268 auto pos = m_log_streams.find(log_file);
1269 if (pos != m_log_streams.end())
1270 log_stream_sp = pos->second.lock();
1271 if (!log_stream_sp) {
1272 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1273 if (log_options & LLDB_LOG_OPTION_APPEND)
1274 flags |= llvm::sys::fs::F_Append;
1276 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1277 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
1278 error_stream << "Unable to open log file: " << ec.message();
1282 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
1283 m_log_streams[log_file] = log_stream_sp;
1286 assert(log_stream_sp);
1288 if (log_options == 0)
1290 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1292 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1296 ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) {
1297 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1299 if (!m_script_interpreter_sp) {
1302 m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(
1303 GetScriptLanguage(), *this);
1306 return m_script_interpreter_sp.get();
1309 SourceManager &Debugger::GetSourceManager() {
1310 if (!m_source_manager_up)
1311 m_source_manager_up = llvm::make_unique<SourceManager>(shared_from_this());
1312 return *m_source_manager_up;
1315 // This function handles events that were broadcast by the process.
1316 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1317 using namespace lldb;
1318 const uint32_t event_type =
1319 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1322 // if (event_type & eBreakpointEventTypeAdded
1323 // || event_type & eBreakpointEventTypeRemoved
1324 // || event_type & eBreakpointEventTypeEnabled
1325 // || event_type & eBreakpointEventTypeDisabled
1326 // || event_type & eBreakpointEventTypeCommandChanged
1327 // || event_type & eBreakpointEventTypeConditionChanged
1328 // || event_type & eBreakpointEventTypeIgnoreChanged
1329 // || event_type & eBreakpointEventTypeLocationsResolved)
1331 // // Don't do anything about these events, since the breakpoint
1332 // commands already echo these actions.
1335 if (event_type & eBreakpointEventTypeLocationsAdded) {
1336 uint32_t num_new_locations =
1337 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1339 if (num_new_locations > 0) {
1340 BreakpointSP breakpoint =
1341 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1342 StreamSP output_sp(GetAsyncOutputStream());
1344 output_sp->Printf("%d location%s added to breakpoint %d\n",
1345 num_new_locations, num_new_locations == 1 ? "" : "s",
1346 breakpoint->GetID());
1351 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1353 // // These locations just get disabled, not sure it is worth spamming
1354 // folks about this on the command line.
1356 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1358 // // This might be an interesting thing to note, but I'm going to
1359 // leave it quiet for now, it just looked noisy.
1363 size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1364 size_t total_bytes = 0;
1365 if (stream == nullptr)
1366 stream = GetOutputFile().get();
1369 // The process has stuff waiting for stdout; get it and write it out to the
1370 // appropriate place.
1371 if (process == nullptr) {
1372 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1374 process = target_sp->GetProcessSP().get();
1379 char stdio_buffer[1024];
1380 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1382 stream->Write(stdio_buffer, len);
1391 size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1392 size_t total_bytes = 0;
1393 if (stream == nullptr)
1394 stream = GetOutputFile().get();
1397 // The process has stuff waiting for stderr; get it and write it out to the
1398 // appropriate place.
1399 if (process == nullptr) {
1400 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1402 process = target_sp->GetProcessSP().get();
1407 char stdio_buffer[1024];
1408 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1410 stream->Write(stdio_buffer, len);
1419 // This function handles events that were broadcast by the process.
1420 void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1421 using namespace lldb;
1422 const uint32_t event_type = event_sp->GetType();
1423 ProcessSP process_sp =
1424 (event_type == Process::eBroadcastBitStructuredData)
1425 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1426 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1428 StreamSP output_stream_sp = GetAsyncOutputStream();
1429 StreamSP error_stream_sp = GetAsyncErrorStream();
1430 const bool gui_enabled = IsForwardingEvents();
1433 bool pop_process_io_handler = false;
1436 bool state_is_stopped = false;
1437 const bool got_state_changed =
1438 (event_type & Process::eBroadcastBitStateChanged) != 0;
1439 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1440 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1441 const bool got_structured_data =
1442 (event_type & Process::eBroadcastBitStructuredData) != 0;
1444 if (got_state_changed) {
1445 StateType event_state =
1446 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1447 state_is_stopped = StateIsStoppedState(event_state, false);
1450 // Display running state changes first before any STDIO
1451 if (got_state_changed && !state_is_stopped) {
1452 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1453 pop_process_io_handler);
1456 // Now display and STDOUT
1457 if (got_stdout || got_state_changed) {
1458 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1461 // Now display and STDERR
1462 if (got_stderr || got_state_changed) {
1463 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1466 // Give structured data events an opportunity to display.
1467 if (got_structured_data) {
1468 StructuredDataPluginSP plugin_sp =
1469 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1471 auto structured_data_sp =
1472 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1473 if (output_stream_sp) {
1474 StreamString content_stream;
1476 plugin_sp->GetDescription(structured_data_sp, content_stream);
1477 if (error.Success()) {
1478 if (!content_stream.GetString().empty()) {
1480 content_stream.PutChar('\n');
1481 content_stream.Flush();
1484 output_stream_sp->PutCString(content_stream.GetString());
1487 error_stream_sp->Printf("Failed to print structured "
1488 "data with plugin %s: %s",
1489 plugin_sp->GetPluginName().AsCString(),
1496 // Now display any stopped state changes after any STDIO
1497 if (got_state_changed && state_is_stopped) {
1498 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1499 pop_process_io_handler);
1502 output_stream_sp->Flush();
1503 error_stream_sp->Flush();
1505 if (pop_process_io_handler)
1506 process_sp->PopProcessIOHandler();
1510 void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1511 // At present the only thread event we handle is the Frame Changed event, and
1512 // all we do for that is just reprint the thread status for that thread.
1513 using namespace lldb;
1514 const uint32_t event_type = event_sp->GetType();
1515 const bool stop_format = true;
1516 if (event_type == Thread::eBroadcastBitStackChanged ||
1517 event_type == Thread::eBroadcastBitThreadSelected) {
1519 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1521 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1526 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1528 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1529 m_forward_listener_sp = listener_sp;
1532 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1533 m_forward_listener_sp.reset();
1536 void Debugger::DefaultEventHandler() {
1537 ListenerSP listener_sp(GetListener());
1538 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1539 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1540 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1541 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1542 Target::eBroadcastBitBreakpointChanged);
1544 BroadcastEventSpec process_event_spec(
1545 broadcaster_class_process,
1546 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1547 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1549 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1550 Thread::eBroadcastBitStackChanged |
1551 Thread::eBroadcastBitThreadSelected);
1553 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1555 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1556 process_event_spec);
1557 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1559 listener_sp->StartListeningForEvents(
1560 m_command_interpreter_up.get(),
1561 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1562 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1563 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1565 // Let the thread that spawned us know that we have started up and that we
1566 // are now listening to all required events so no events get missed
1567 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1572 if (listener_sp->GetEvent(event_sp, llvm::None)) {
1574 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1576 uint32_t event_type = event_sp->GetType();
1577 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1578 if (broadcaster_class == broadcaster_class_process) {
1579 HandleProcessEvent(event_sp);
1580 } else if (broadcaster_class == broadcaster_class_target) {
1581 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1583 HandleBreakpointEvent(event_sp);
1585 } else if (broadcaster_class == broadcaster_class_thread) {
1586 HandleThreadEvent(event_sp);
1587 } else if (broadcaster == m_command_interpreter_up.get()) {
1589 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1591 } else if (event_type &
1592 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1593 const char *data = reinterpret_cast<const char *>(
1594 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1595 if (data && data[0]) {
1596 StreamSP error_sp(GetAsyncErrorStream());
1598 error_sp->PutCString(data);
1602 } else if (event_type & CommandInterpreter::
1603 eBroadcastBitAsynchronousOutputData) {
1604 const char *data = reinterpret_cast<const char *>(
1605 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1606 if (data && data[0]) {
1607 StreamSP output_sp(GetAsyncOutputStream());
1609 output_sp->PutCString(data);
1617 if (m_forward_listener_sp)
1618 m_forward_listener_sp->AddEvent(event_sp);
1624 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1625 ((Debugger *)arg)->DefaultEventHandler();
1629 bool Debugger::StartEventHandlerThread() {
1630 if (!m_event_handler_thread.IsJoinable()) {
1631 // We must synchronize with the DefaultEventHandler() thread to ensure it
1632 // is up and running and listening to events before we return from this
1633 // function. We do this by listening to events for the
1634 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1635 ConstString full_name("lldb.debugger.event-handler");
1636 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
1637 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1638 eBroadcastBitEventThreadIsListening);
1641 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1642 full_name.AsCString() : "dbg.evt-handler";
1644 // Use larger 8MB stack for this thread
1645 llvm::Expected<HostThread> event_handler_thread =
1646 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1647 g_debugger_event_thread_stack_bytes);
1649 if (event_handler_thread) {
1650 m_event_handler_thread = *event_handler_thread;
1652 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1653 "failed to launch host thread: {}",
1654 llvm::toString(event_handler_thread.takeError()));
1657 // Make sure DefaultEventHandler() is running and listening to events
1658 // before we return from this function. We are only listening for events of
1659 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1660 // event, we just need to wait an infinite amount of time for it (nullptr
1661 // timeout as the first parameter)
1662 lldb::EventSP event_sp;
1663 listener_sp->GetEvent(event_sp, llvm::None);
1665 return m_event_handler_thread.IsJoinable();
1668 void Debugger::StopEventHandlerThread() {
1669 if (m_event_handler_thread.IsJoinable()) {
1670 GetCommandInterpreter().BroadcastEvent(
1671 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1672 m_event_handler_thread.Join(nullptr);
1676 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1677 Debugger *debugger = (Debugger *)arg;
1678 debugger->ExecuteIOHandlers();
1679 debugger->StopEventHandlerThread();
1683 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1685 bool Debugger::StartIOHandlerThread() {
1686 if (!m_io_handler_thread.IsJoinable()) {
1687 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1688 "lldb.debugger.io-handler", IOHandlerThread, this,
1689 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1690 if (io_handler_thread) {
1691 m_io_handler_thread = *io_handler_thread;
1693 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1694 "failed to launch host thread: {}",
1695 llvm::toString(io_handler_thread.takeError()));
1698 return m_io_handler_thread.IsJoinable();
1701 void Debugger::StopIOHandlerThread() {
1702 if (m_io_handler_thread.IsJoinable()) {
1703 if (m_input_file_sp)
1704 m_input_file_sp->GetFile().Close();
1705 m_io_handler_thread.Join(nullptr);
1709 void Debugger::JoinIOHandlerThread() {
1710 if (HasIOHandlerThread()) {
1711 thread_result_t result;
1712 m_io_handler_thread.Join(&result);
1713 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1717 Target *Debugger::GetDummyTarget() {
1718 return m_target_list.GetDummyTarget(*this).get();
1721 Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1722 Target *target = nullptr;
1723 if (!prefer_dummy) {
1724 target = m_target_list.GetSelectedTarget().get();
1729 return GetDummyTarget();
1732 Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1734 FileSpec repl_executable;
1736 if (language == eLanguageTypeUnknown) {
1737 std::set<LanguageType> repl_languages;
1739 Language::GetLanguagesSupportingREPLs(repl_languages);
1741 if (repl_languages.size() == 1) {
1742 language = *repl_languages.begin();
1743 } else if (repl_languages.empty()) {
1744 err.SetErrorStringWithFormat(
1745 "LLDB isn't configured with REPL support for any languages.");
1748 err.SetErrorStringWithFormat(
1749 "Multiple possible REPL languages. Please specify a language.");
1754 Target *const target =
1755 nullptr; // passing in an empty target means the REPL must create one
1757 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1759 if (!err.Success()) {
1764 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1765 Language::GetNameForLanguageType(language));
1769 repl_sp->SetCompilerOptions(repl_options);