1 //===-- Debugger.cpp ------------------------------------------------------===//
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/DebuggerEvents.h"
13 #include "lldb/Core/FormatEntity.h"
14 #include "lldb/Core/Mangled.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Progress.h"
19 #include "lldb/Core/StreamAsynchronousIO.h"
20 #include "lldb/DataFormatters/DataVisualization.h"
21 #include "lldb/Expression/REPL.h"
22 #include "lldb/Host/File.h"
23 #include "lldb/Host/FileSystem.h"
24 #include "lldb/Host/HostInfo.h"
25 #include "lldb/Host/StreamFile.h"
26 #include "lldb/Host/Terminal.h"
27 #include "lldb/Host/ThreadLauncher.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Interpreter/CommandReturnObject.h"
30 #include "lldb/Interpreter/OptionValue.h"
31 #include "lldb/Interpreter/OptionValueLanguage.h"
32 #include "lldb/Interpreter/OptionValueProperties.h"
33 #include "lldb/Interpreter/OptionValueSInt64.h"
34 #include "lldb/Interpreter/OptionValueString.h"
35 #include "lldb/Interpreter/Property.h"
36 #include "lldb/Interpreter/ScriptInterpreter.h"
37 #include "lldb/Symbol/Function.h"
38 #include "lldb/Symbol/Symbol.h"
39 #include "lldb/Symbol/SymbolContext.h"
40 #include "lldb/Target/Language.h"
41 #include "lldb/Target/Process.h"
42 #include "lldb/Target/StructuredDataPlugin.h"
43 #include "lldb/Target/Target.h"
44 #include "lldb/Target/TargetList.h"
45 #include "lldb/Target/Thread.h"
46 #include "lldb/Target/ThreadList.h"
47 #include "lldb/Utility/AnsiTerminal.h"
48 #include "lldb/Utility/Event.h"
49 #include "lldb/Utility/LLDBLog.h"
50 #include "lldb/Utility/Listener.h"
51 #include "lldb/Utility/Log.h"
52 #include "lldb/Utility/State.h"
53 #include "lldb/Utility/Stream.h"
54 #include "lldb/Utility/StreamString.h"
55 #include "lldb/lldb-enumerations.h"
58 #include "lldb/Host/windows/PosixApi.h"
59 #include "lldb/Host/windows/windows.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/ADT/StringRef.h"
64 #include "llvm/ADT/iterator.h"
65 #include "llvm/Support/DynamicLibrary.h"
66 #include "llvm/Support/FileSystem.h"
67 #include "llvm/Support/Process.h"
68 #include "llvm/Support/ThreadPool.h"
69 #include "llvm/Support/Threading.h"
70 #include "llvm/Support/raw_ostream.h"
81 #include <system_error>
83 // Includes for pipe()
91 namespace lldb_private
{
96 using namespace lldb_private
;
98 static lldb::user_id_t g_unique_id
= 1;
99 static size_t g_debugger_event_thread_stack_bytes
= 8 * 1024 * 1024;
101 #pragma mark Static Functions
103 static std::recursive_mutex
*g_debugger_list_mutex_ptr
=
104 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
105 static Debugger::DebuggerList
*g_debugger_list_ptr
=
106 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
107 static llvm::DefaultThreadPool
*g_thread_pool
= nullptr;
109 static constexpr OptionEnumValueElement g_show_disassembly_enum_values
[] = {
111 Debugger::eStopDisassemblyTypeNever
,
113 "Never show disassembly when displaying a stop context.",
116 Debugger::eStopDisassemblyTypeNoDebugInfo
,
118 "Show disassembly when there is no debug information.",
121 Debugger::eStopDisassemblyTypeNoSource
,
123 "Show disassembly when there is no source information, or the source "
125 "is missing when displaying a stop context.",
128 Debugger::eStopDisassemblyTypeAlways
,
130 "Always show disassembly when displaying a stop context.",
134 static constexpr OptionEnumValueElement g_language_enumerators
[] = {
138 "Disable scripting languages.",
141 eScriptLanguagePython
,
143 "Select python as the default scripting language.",
146 eScriptLanguageDefault
,
148 "Select the lldb default as the default scripting language.",
152 static constexpr OptionEnumValueElement g_dwim_print_verbosities
[] = {
153 {eDWIMPrintVerbosityNone
, "none",
154 "Use no verbosity when running dwim-print."},
155 {eDWIMPrintVerbosityExpression
, "expression",
156 "Use partial verbosity when running dwim-print - display a message when "
157 "`expression` evaluation is used."},
158 {eDWIMPrintVerbosityFull
, "full",
159 "Use full verbosity when running dwim-print."},
162 static constexpr OptionEnumValueElement s_stop_show_column_values
[] = {
164 eStopShowColumnAnsiOrCaret
,
166 "Highlight the stop column with ANSI terminal codes when color/ANSI "
167 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
168 "as if \"caret-only\" mode was selected.",
173 "Highlight the stop column with ANSI terminal codes when running LLDB "
174 "with color/ANSI enabled.",
177 eStopShowColumnCaret
,
179 "Highlight the stop column with a caret character (^) underneath the "
180 "stop column. This method introduces a new line in source listings "
181 "that display thread stop locations.",
186 "Do not highlight the stop column.",
190 #define LLDB_PROPERTIES_debugger
191 #include "CoreProperties.inc"
194 #define LLDB_PROPERTIES_debugger
195 #include "CorePropertiesEnum.inc"
198 LoadPluginCallbackType
Debugger::g_load_plugin_callback
= nullptr;
200 Status
Debugger::SetPropertyValue(const ExecutionContext
*exe_ctx
,
201 VarSetOperationType op
,
202 llvm::StringRef property_path
,
203 llvm::StringRef value
) {
204 bool is_load_script
=
205 (property_path
== "target.load-script-from-symbol-file");
206 // These properties might change how we visualize data.
207 bool invalidate_data_vis
= (property_path
== "escape-non-printables");
208 invalidate_data_vis
|=
209 (property_path
== "target.max-zero-padding-in-float-format");
210 if (invalidate_data_vis
) {
211 DataVisualization::ForceUpdate();
215 LoadScriptFromSymFile load_script_old_value
= eLoadScriptFromSymFileFalse
;
216 if (is_load_script
&& exe_ctx
&& exe_ctx
->GetTargetSP()) {
217 target_sp
= exe_ctx
->GetTargetSP();
218 load_script_old_value
=
219 target_sp
->TargetProperties::GetLoadScriptFromSymbolFile();
221 Status
error(Properties::SetPropertyValue(exe_ctx
, op
, property_path
, value
));
222 if (error
.Success()) {
223 // FIXME it would be nice to have "on-change" callbacks for properties
224 if (property_path
== g_debugger_properties
[ePropertyPrompt
].name
) {
225 llvm::StringRef new_prompt
= GetPrompt();
226 std::string str
= lldb_private::ansi::FormatAnsiTerminalCodes(
227 new_prompt
, GetUseColor());
230 GetCommandInterpreter().UpdatePrompt(new_prompt
);
231 auto bytes
= std::make_unique
<EventDataBytes
>(new_prompt
);
232 auto prompt_change_event_sp
= std::make_shared
<Event
>(
233 CommandInterpreter::eBroadcastBitResetPrompt
, bytes
.release());
234 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp
);
235 } else if (property_path
== g_debugger_properties
[ePropertyUseColor
].name
) {
236 // use-color changed. Ping the prompt so it can reset the ansi terminal
238 SetPrompt(GetPrompt());
239 } else if (property_path
==
240 g_debugger_properties
[ePropertyPromptAnsiPrefix
].name
||
242 g_debugger_properties
[ePropertyPromptAnsiSuffix
].name
) {
243 // Prompt colors changed. Ping the prompt so it can reset the ansi
245 SetPrompt(GetPrompt());
246 } else if (property_path
==
247 g_debugger_properties
[ePropertyUseSourceCache
].name
) {
248 // use-source-cache changed. Wipe out the cache contents if it was
250 if (!GetUseSourceCache()) {
251 m_source_file_cache
.Clear();
253 } else if (is_load_script
&& target_sp
&&
254 load_script_old_value
== eLoadScriptFromSymFileWarn
) {
255 if (target_sp
->TargetProperties::GetLoadScriptFromSymbolFile() ==
256 eLoadScriptFromSymFileTrue
) {
257 std::list
<Status
> errors
;
258 StreamString feedback_stream
;
259 if (!target_sp
->LoadScriptingResources(errors
, feedback_stream
)) {
260 Stream
&s
= GetErrorStream();
261 for (auto &error
: errors
) {
262 s
.Printf("%s\n", error
.AsCString());
264 if (feedback_stream
.GetSize())
265 s
.PutCString(feedback_stream
.GetString());
273 bool Debugger::GetAutoConfirm() const {
274 constexpr uint32_t idx
= ePropertyAutoConfirm
;
275 return GetPropertyAtIndexAs
<bool>(
276 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
279 const FormatEntity::Entry
*Debugger::GetDisassemblyFormat() const {
280 constexpr uint32_t idx
= ePropertyDisassemblyFormat
;
281 return GetPropertyAtIndexAs
<const FormatEntity::Entry
*>(idx
);
284 const FormatEntity::Entry
*Debugger::GetFrameFormat() const {
285 constexpr uint32_t idx
= ePropertyFrameFormat
;
286 return GetPropertyAtIndexAs
<const FormatEntity::Entry
*>(idx
);
289 const FormatEntity::Entry
*Debugger::GetFrameFormatUnique() const {
290 constexpr uint32_t idx
= ePropertyFrameFormatUnique
;
291 return GetPropertyAtIndexAs
<const FormatEntity::Entry
*>(idx
);
294 uint64_t Debugger::GetStopDisassemblyMaxSize() const {
295 constexpr uint32_t idx
= ePropertyStopDisassemblyMaxSize
;
296 return GetPropertyAtIndexAs
<uint64_t>(
297 idx
, g_debugger_properties
[idx
].default_uint_value
);
300 bool Debugger::GetNotifyVoid() const {
301 constexpr uint32_t idx
= ePropertyNotiftVoid
;
302 return GetPropertyAtIndexAs
<uint64_t>(
303 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
306 llvm::StringRef
Debugger::GetPrompt() const {
307 constexpr uint32_t idx
= ePropertyPrompt
;
308 return GetPropertyAtIndexAs
<llvm::StringRef
>(
309 idx
, g_debugger_properties
[idx
].default_cstr_value
);
312 llvm::StringRef
Debugger::GetPromptAnsiPrefix() const {
313 const uint32_t idx
= ePropertyPromptAnsiPrefix
;
314 return GetPropertyAtIndexAs
<llvm::StringRef
>(
315 idx
, g_debugger_properties
[idx
].default_cstr_value
);
318 llvm::StringRef
Debugger::GetPromptAnsiSuffix() const {
319 const uint32_t idx
= ePropertyPromptAnsiSuffix
;
320 return GetPropertyAtIndexAs
<llvm::StringRef
>(
321 idx
, g_debugger_properties
[idx
].default_cstr_value
);
324 void Debugger::SetPrompt(llvm::StringRef p
) {
325 constexpr uint32_t idx
= ePropertyPrompt
;
326 SetPropertyAtIndex(idx
, p
);
327 llvm::StringRef new_prompt
= GetPrompt();
329 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt
, GetUseColor());
332 GetCommandInterpreter().UpdatePrompt(new_prompt
);
335 const FormatEntity::Entry
*Debugger::GetThreadFormat() const {
336 constexpr uint32_t idx
= ePropertyThreadFormat
;
337 return GetPropertyAtIndexAs
<const FormatEntity::Entry
*>(idx
);
340 const FormatEntity::Entry
*Debugger::GetThreadStopFormat() const {
341 constexpr uint32_t idx
= ePropertyThreadStopFormat
;
342 return GetPropertyAtIndexAs
<const FormatEntity::Entry
*>(idx
);
345 lldb::ScriptLanguage
Debugger::GetScriptLanguage() const {
346 const uint32_t idx
= ePropertyScriptLanguage
;
347 return GetPropertyAtIndexAs
<lldb::ScriptLanguage
>(
348 idx
, static_cast<lldb::ScriptLanguage
>(
349 g_debugger_properties
[idx
].default_uint_value
));
352 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang
) {
353 const uint32_t idx
= ePropertyScriptLanguage
;
354 return SetPropertyAtIndex(idx
, script_lang
);
357 lldb::LanguageType
Debugger::GetREPLLanguage() const {
358 const uint32_t idx
= ePropertyREPLLanguage
;
359 return GetPropertyAtIndexAs
<LanguageType
>(idx
, {});
362 bool Debugger::SetREPLLanguage(lldb::LanguageType repl_lang
) {
363 const uint32_t idx
= ePropertyREPLLanguage
;
364 return SetPropertyAtIndex(idx
, repl_lang
);
367 uint64_t Debugger::GetTerminalWidth() const {
368 const uint32_t idx
= ePropertyTerminalWidth
;
369 return GetPropertyAtIndexAs
<uint64_t>(
370 idx
, g_debugger_properties
[idx
].default_uint_value
);
373 bool Debugger::SetTerminalWidth(uint64_t term_width
) {
374 const uint32_t idx
= ePropertyTerminalWidth
;
375 const bool success
= SetPropertyAtIndex(idx
, term_width
);
377 if (auto handler_sp
= m_io_handler_stack
.Top())
378 handler_sp
->TerminalSizeChanged();
383 uint64_t Debugger::GetTerminalHeight() const {
384 const uint32_t idx
= ePropertyTerminalHeight
;
385 return GetPropertyAtIndexAs
<uint64_t>(
386 idx
, g_debugger_properties
[idx
].default_uint_value
);
389 bool Debugger::SetTerminalHeight(uint64_t term_height
) {
390 const uint32_t idx
= ePropertyTerminalHeight
;
391 const bool success
= SetPropertyAtIndex(idx
, term_height
);
393 if (auto handler_sp
= m_io_handler_stack
.Top())
394 handler_sp
->TerminalSizeChanged();
399 bool Debugger::GetUseExternalEditor() const {
400 const uint32_t idx
= ePropertyUseExternalEditor
;
401 return GetPropertyAtIndexAs
<bool>(
402 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
405 bool Debugger::SetUseExternalEditor(bool b
) {
406 const uint32_t idx
= ePropertyUseExternalEditor
;
407 return SetPropertyAtIndex(idx
, b
);
410 llvm::StringRef
Debugger::GetExternalEditor() const {
411 const uint32_t idx
= ePropertyExternalEditor
;
412 return GetPropertyAtIndexAs
<llvm::StringRef
>(
413 idx
, g_debugger_properties
[idx
].default_cstr_value
);
416 bool Debugger::SetExternalEditor(llvm::StringRef editor
) {
417 const uint32_t idx
= ePropertyExternalEditor
;
418 return SetPropertyAtIndex(idx
, editor
);
421 bool Debugger::GetUseColor() const {
422 const uint32_t idx
= ePropertyUseColor
;
423 return GetPropertyAtIndexAs
<bool>(
424 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
427 bool Debugger::SetUseColor(bool b
) {
428 const uint32_t idx
= ePropertyUseColor
;
429 bool ret
= SetPropertyAtIndex(idx
, b
);
430 SetPrompt(GetPrompt());
434 bool Debugger::GetShowProgress() const {
435 const uint32_t idx
= ePropertyShowProgress
;
436 return GetPropertyAtIndexAs
<bool>(
437 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
440 bool Debugger::SetShowProgress(bool show_progress
) {
441 const uint32_t idx
= ePropertyShowProgress
;
442 return SetPropertyAtIndex(idx
, show_progress
);
445 llvm::StringRef
Debugger::GetShowProgressAnsiPrefix() const {
446 const uint32_t idx
= ePropertyShowProgressAnsiPrefix
;
447 return GetPropertyAtIndexAs
<llvm::StringRef
>(
448 idx
, g_debugger_properties
[idx
].default_cstr_value
);
451 llvm::StringRef
Debugger::GetShowProgressAnsiSuffix() const {
452 const uint32_t idx
= ePropertyShowProgressAnsiSuffix
;
453 return GetPropertyAtIndexAs
<llvm::StringRef
>(
454 idx
, g_debugger_properties
[idx
].default_cstr_value
);
457 bool Debugger::GetUseAutosuggestion() const {
458 const uint32_t idx
= ePropertyShowAutosuggestion
;
459 return GetPropertyAtIndexAs
<bool>(
460 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
463 llvm::StringRef
Debugger::GetAutosuggestionAnsiPrefix() const {
464 const uint32_t idx
= ePropertyShowAutosuggestionAnsiPrefix
;
465 return GetPropertyAtIndexAs
<llvm::StringRef
>(
466 idx
, g_debugger_properties
[idx
].default_cstr_value
);
469 llvm::StringRef
Debugger::GetAutosuggestionAnsiSuffix() const {
470 const uint32_t idx
= ePropertyShowAutosuggestionAnsiSuffix
;
471 return GetPropertyAtIndexAs
<llvm::StringRef
>(
472 idx
, g_debugger_properties
[idx
].default_cstr_value
);
475 llvm::StringRef
Debugger::GetRegexMatchAnsiPrefix() const {
476 const uint32_t idx
= ePropertyShowRegexMatchAnsiPrefix
;
477 return GetPropertyAtIndexAs
<llvm::StringRef
>(
478 idx
, g_debugger_properties
[idx
].default_cstr_value
);
481 llvm::StringRef
Debugger::GetRegexMatchAnsiSuffix() const {
482 const uint32_t idx
= ePropertyShowRegexMatchAnsiSuffix
;
483 return GetPropertyAtIndexAs
<llvm::StringRef
>(
484 idx
, g_debugger_properties
[idx
].default_cstr_value
);
487 bool Debugger::GetShowDontUsePoHint() const {
488 const uint32_t idx
= ePropertyShowDontUsePoHint
;
489 return GetPropertyAtIndexAs
<bool>(
490 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
493 bool Debugger::GetUseSourceCache() const {
494 const uint32_t idx
= ePropertyUseSourceCache
;
495 return GetPropertyAtIndexAs
<bool>(
496 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
499 bool Debugger::SetUseSourceCache(bool b
) {
500 const uint32_t idx
= ePropertyUseSourceCache
;
501 bool ret
= SetPropertyAtIndex(idx
, b
);
503 m_source_file_cache
.Clear();
507 bool Debugger::GetHighlightSource() const {
508 const uint32_t idx
= ePropertyHighlightSource
;
509 return GetPropertyAtIndexAs
<bool>(
510 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
513 StopShowColumn
Debugger::GetStopShowColumn() const {
514 const uint32_t idx
= ePropertyStopShowColumn
;
515 return GetPropertyAtIndexAs
<lldb::StopShowColumn
>(
516 idx
, static_cast<lldb::StopShowColumn
>(
517 g_debugger_properties
[idx
].default_uint_value
));
520 llvm::StringRef
Debugger::GetStopShowColumnAnsiPrefix() const {
521 const uint32_t idx
= ePropertyStopShowColumnAnsiPrefix
;
522 return GetPropertyAtIndexAs
<llvm::StringRef
>(
523 idx
, g_debugger_properties
[idx
].default_cstr_value
);
526 llvm::StringRef
Debugger::GetStopShowColumnAnsiSuffix() const {
527 const uint32_t idx
= ePropertyStopShowColumnAnsiSuffix
;
528 return GetPropertyAtIndexAs
<llvm::StringRef
>(
529 idx
, g_debugger_properties
[idx
].default_cstr_value
);
532 llvm::StringRef
Debugger::GetStopShowLineMarkerAnsiPrefix() const {
533 const uint32_t idx
= ePropertyStopShowLineMarkerAnsiPrefix
;
534 return GetPropertyAtIndexAs
<llvm::StringRef
>(
535 idx
, g_debugger_properties
[idx
].default_cstr_value
);
538 llvm::StringRef
Debugger::GetStopShowLineMarkerAnsiSuffix() const {
539 const uint32_t idx
= ePropertyStopShowLineMarkerAnsiSuffix
;
540 return GetPropertyAtIndexAs
<llvm::StringRef
>(
541 idx
, g_debugger_properties
[idx
].default_cstr_value
);
544 uint64_t Debugger::GetStopSourceLineCount(bool before
) const {
546 before
? ePropertyStopLineCountBefore
: ePropertyStopLineCountAfter
;
547 return GetPropertyAtIndexAs
<uint64_t>(
548 idx
, g_debugger_properties
[idx
].default_uint_value
);
551 Debugger::StopDisassemblyType
Debugger::GetStopDisassemblyDisplay() const {
552 const uint32_t idx
= ePropertyStopDisassemblyDisplay
;
553 return GetPropertyAtIndexAs
<Debugger::StopDisassemblyType
>(
554 idx
, static_cast<Debugger::StopDisassemblyType
>(
555 g_debugger_properties
[idx
].default_uint_value
));
558 uint64_t Debugger::GetDisassemblyLineCount() const {
559 const uint32_t idx
= ePropertyStopDisassemblyCount
;
560 return GetPropertyAtIndexAs
<uint64_t>(
561 idx
, g_debugger_properties
[idx
].default_uint_value
);
564 bool Debugger::GetAutoOneLineSummaries() const {
565 const uint32_t idx
= ePropertyAutoOneLineSummaries
;
566 return GetPropertyAtIndexAs
<bool>(
567 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
570 bool Debugger::GetEscapeNonPrintables() const {
571 const uint32_t idx
= ePropertyEscapeNonPrintables
;
572 return GetPropertyAtIndexAs
<bool>(
573 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
576 bool Debugger::GetAutoIndent() const {
577 const uint32_t idx
= ePropertyAutoIndent
;
578 return GetPropertyAtIndexAs
<bool>(
579 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
582 bool Debugger::SetAutoIndent(bool b
) {
583 const uint32_t idx
= ePropertyAutoIndent
;
584 return SetPropertyAtIndex(idx
, b
);
587 bool Debugger::GetPrintDecls() const {
588 const uint32_t idx
= ePropertyPrintDecls
;
589 return GetPropertyAtIndexAs
<bool>(
590 idx
, g_debugger_properties
[idx
].default_uint_value
!= 0);
593 bool Debugger::SetPrintDecls(bool b
) {
594 const uint32_t idx
= ePropertyPrintDecls
;
595 return SetPropertyAtIndex(idx
, b
);
598 uint64_t Debugger::GetTabSize() const {
599 const uint32_t idx
= ePropertyTabSize
;
600 return GetPropertyAtIndexAs
<uint64_t>(
601 idx
, g_debugger_properties
[idx
].default_uint_value
);
604 bool Debugger::SetTabSize(uint64_t tab_size
) {
605 const uint32_t idx
= ePropertyTabSize
;
606 return SetPropertyAtIndex(idx
, tab_size
);
609 lldb::DWIMPrintVerbosity
Debugger::GetDWIMPrintVerbosity() const {
610 const uint32_t idx
= ePropertyDWIMPrintVerbosity
;
611 return GetPropertyAtIndexAs
<lldb::DWIMPrintVerbosity
>(
612 idx
, static_cast<lldb::DWIMPrintVerbosity
>(
613 g_debugger_properties
[idx
].default_uint_value
!= 0));
616 bool Debugger::GetShowInlineDiagnostics() const {
617 const uint32_t idx
= ePropertyShowInlineDiagnostics
;
618 return GetPropertyAtIndexAs
<bool>(
619 idx
, g_debugger_properties
[idx
].default_uint_value
);
622 bool Debugger::SetShowInlineDiagnostics(bool b
) {
623 const uint32_t idx
= ePropertyShowInlineDiagnostics
;
624 return SetPropertyAtIndex(idx
, b
);
627 #pragma mark Debugger
629 // const DebuggerPropertiesSP &
630 // Debugger::GetSettings() const
632 // return m_properties_sp;
636 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback
) {
637 assert(g_debugger_list_ptr
== nullptr &&
638 "Debugger::Initialize called more than once!");
639 g_debugger_list_mutex_ptr
= new std::recursive_mutex();
640 g_debugger_list_ptr
= new DebuggerList();
641 g_thread_pool
= new llvm::DefaultThreadPool(llvm::optimal_concurrency());
642 g_load_plugin_callback
= load_plugin_callback
;
645 void Debugger::Terminate() {
646 assert(g_debugger_list_ptr
&&
647 "Debugger::Terminate called without a matching Debugger::Initialize!");
649 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
650 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
651 for (const auto &debugger
: *g_debugger_list_ptr
)
652 debugger
->HandleDestroyCallback();
656 // The destructor will wait for all the threads to complete.
657 delete g_thread_pool
;
660 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
661 // Clear our global list of debugger objects
663 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
664 for (const auto &debugger
: *g_debugger_list_ptr
)
666 g_debugger_list_ptr
->clear();
671 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
673 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
675 bool Debugger::LoadPlugin(const FileSpec
&spec
, Status
&error
) {
676 if (g_load_plugin_callback
) {
677 llvm::sys::DynamicLibrary dynlib
=
678 g_load_plugin_callback(shared_from_this(), spec
, error
);
679 if (dynlib
.isValid()) {
680 m_loaded_plugins
.push_back(dynlib
);
684 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
685 // if the public API layer isn't available (code is linking against all of
686 // the internal LLDB static libraries), then we can't load plugins
687 error
= Status::FromErrorString("Public API layer is not available");
692 static FileSystem::EnumerateDirectoryResult
693 LoadPluginCallback(void *baton
, llvm::sys::fs::file_type ft
,
694 llvm::StringRef path
) {
697 static constexpr llvm::StringLiteral
g_dylibext(".dylib");
698 static constexpr llvm::StringLiteral
g_solibext(".so");
701 return FileSystem::eEnumerateDirectoryResultQuit
;
703 Debugger
*debugger
= (Debugger
*)baton
;
705 namespace fs
= llvm::sys::fs
;
706 // If we have a regular file, a symbolic link or unknown file type, try and
707 // process the file. We must handle unknown as sometimes the directory
708 // enumeration might be enumerating a file system that doesn't have correct
709 // file type information.
710 if (ft
== fs::file_type::regular_file
|| ft
== fs::file_type::symlink_file
||
711 ft
== fs::file_type::type_unknown
) {
712 FileSpec
plugin_file_spec(path
);
713 FileSystem::Instance().Resolve(plugin_file_spec
);
715 if (plugin_file_spec
.GetFileNameExtension() != g_dylibext
&&
716 plugin_file_spec
.GetFileNameExtension() != g_solibext
) {
717 return FileSystem::eEnumerateDirectoryResultNext
;
720 Status plugin_load_error
;
721 debugger
->LoadPlugin(plugin_file_spec
, plugin_load_error
);
723 return FileSystem::eEnumerateDirectoryResultNext
;
724 } else if (ft
== fs::file_type::directory_file
||
725 ft
== fs::file_type::symlink_file
||
726 ft
== fs::file_type::type_unknown
) {
727 // Try and recurse into anything that a directory or symbolic link. We must
728 // also do this for unknown as sometimes the directory enumeration might be
729 // enumerating a file system that doesn't have correct file type
731 return FileSystem::eEnumerateDirectoryResultEnter
;
734 return FileSystem::eEnumerateDirectoryResultNext
;
737 void Debugger::InstanceInitialize() {
738 const bool find_directories
= true;
739 const bool find_files
= true;
740 const bool find_other
= true;
741 char dir_path
[PATH_MAX
];
742 if (FileSpec dir_spec
= HostInfo::GetSystemPluginDir()) {
743 if (FileSystem::Instance().Exists(dir_spec
) &&
744 dir_spec
.GetPath(dir_path
, sizeof(dir_path
))) {
745 FileSystem::Instance().EnumerateDirectory(dir_path
, find_directories
,
746 find_files
, find_other
,
747 LoadPluginCallback
, this);
751 if (FileSpec dir_spec
= HostInfo::GetUserPluginDir()) {
752 if (FileSystem::Instance().Exists(dir_spec
) &&
753 dir_spec
.GetPath(dir_path
, sizeof(dir_path
))) {
754 FileSystem::Instance().EnumerateDirectory(dir_path
, find_directories
,
755 find_files
, find_other
,
756 LoadPluginCallback
, this);
760 PluginManager::DebuggerInitialize(*this);
763 DebuggerSP
Debugger::CreateInstance(lldb::LogOutputCallback log_callback
,
765 DebuggerSP
debugger_sp(new Debugger(log_callback
, baton
));
766 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
767 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
768 g_debugger_list_ptr
->push_back(debugger_sp
);
770 debugger_sp
->InstanceInitialize();
774 void Debugger::HandleDestroyCallback() {
775 const lldb::user_id_t user_id
= GetID();
776 // Invoke and remove all the callbacks in an FIFO order. Callbacks which are
777 // added during this loop will be appended, invoked and then removed last.
778 // Callbacks which are removed during this loop will not be invoked.
780 DestroyCallbackInfo callback_info
;
782 std::lock_guard
<std::mutex
> guard(m_destroy_callback_mutex
);
783 if (m_destroy_callbacks
.empty())
785 // Pop the first item in the list
786 callback_info
= m_destroy_callbacks
.front();
787 m_destroy_callbacks
.erase(m_destroy_callbacks
.begin());
789 // Call the destroy callback with user id and baton
790 callback_info
.callback(user_id
, callback_info
.baton
);
794 void Debugger::Destroy(DebuggerSP
&debugger_sp
) {
798 debugger_sp
->HandleDestroyCallback();
799 CommandInterpreter
&cmd_interpreter
= debugger_sp
->GetCommandInterpreter();
801 if (cmd_interpreter
.GetSaveSessionOnQuit()) {
802 CommandReturnObject
result(debugger_sp
->GetUseColor());
803 cmd_interpreter
.SaveTranscript(result
);
804 if (result
.Succeeded())
805 (*debugger_sp
->GetAsyncOutputStream())
806 << result
.GetOutputString() << '\n';
808 (*debugger_sp
->GetAsyncErrorStream()) << result
.GetErrorString() << '\n';
811 debugger_sp
->Clear();
813 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
814 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
815 DebuggerList::iterator pos
, end
= g_debugger_list_ptr
->end();
816 for (pos
= g_debugger_list_ptr
->begin(); pos
!= end
; ++pos
) {
817 if ((*pos
).get() == debugger_sp
.get()) {
818 g_debugger_list_ptr
->erase(pos
);
826 Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name
) {
827 if (!g_debugger_list_ptr
|| !g_debugger_list_mutex_ptr
)
830 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
831 for (const DebuggerSP
&debugger_sp
: *g_debugger_list_ptr
) {
835 if (llvm::StringRef(debugger_sp
->GetInstanceName()) == instance_name
)
841 TargetSP
Debugger::FindTargetWithProcessID(lldb::pid_t pid
) {
843 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
844 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
845 DebuggerList::iterator pos
, end
= g_debugger_list_ptr
->end();
846 for (pos
= g_debugger_list_ptr
->begin(); pos
!= end
; ++pos
) {
847 target_sp
= (*pos
)->GetTargetList().FindTargetWithProcessID(pid
);
855 TargetSP
Debugger::FindTargetWithProcess(Process
*process
) {
857 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
858 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
859 DebuggerList::iterator pos
, end
= g_debugger_list_ptr
->end();
860 for (pos
= g_debugger_list_ptr
->begin(); pos
!= end
; ++pos
) {
861 target_sp
= (*pos
)->GetTargetList().FindTargetWithProcess(process
);
869 llvm::StringRef
Debugger::GetStaticBroadcasterClass() {
870 static constexpr llvm::StringLiteral
class_name("lldb.debugger");
874 Debugger::Debugger(lldb::LogOutputCallback log_callback
, void *baton
)
875 : UserID(g_unique_id
++),
876 Properties(std::make_shared
<OptionValueProperties
>()),
877 m_input_file_sp(std::make_shared
<NativeFile
>(stdin
, false)),
878 m_output_stream_sp(std::make_shared
<StreamFile
>(stdout
, false)),
879 m_error_stream_sp(std::make_shared
<StreamFile
>(stderr
, false)),
880 m_input_recorder(nullptr),
881 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
882 m_terminal_state(), m_target_list(*this), m_platform_list(),
883 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
884 m_source_manager_up(), m_source_file_cache(),
885 m_command_interpreter_up(
886 std::make_unique
<CommandInterpreter
>(*this, false)),
887 m_io_handler_stack(),
888 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()),
889 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
890 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
891 m_broadcaster(m_broadcaster_manager_sp
,
892 GetStaticBroadcasterClass().str()),
893 m_forward_listener_sp(), m_clear_once() {
894 // Initialize the debugger properties as early as possible as other parts of
895 // LLDB will start querying them during construction.
896 m_collection_sp
->Initialize(g_debugger_properties
);
897 m_collection_sp
->AppendProperty(
898 "target", "Settings specify to debugging targets.", true,
899 Target::GetGlobalProperties().GetValueProperties());
900 m_collection_sp
->AppendProperty(
901 "platform", "Platform settings.", true,
902 Platform::GetGlobalPlatformProperties().GetValueProperties());
903 m_collection_sp
->AppendProperty(
904 "symbols", "Symbol lookup and cache settings.", true,
905 ModuleList::GetGlobalModuleListProperties().GetValueProperties());
906 m_collection_sp
->AppendProperty(
907 LanguageProperties::GetSettingName(), "Language settings.", true,
908 Language::GetGlobalLanguageProperties().GetValueProperties());
909 if (m_command_interpreter_up
) {
910 m_collection_sp
->AppendProperty(
912 "Settings specify to the debugger's command interpreter.", true,
913 m_command_interpreter_up
->GetValueProperties());
916 m_callback_handler_sp
=
917 std::make_shared
<CallbackLogHandler
>(log_callback
, baton
);
918 m_command_interpreter_up
->Initialize();
919 // Always add our default platform to the platform list
920 PlatformSP
default_platform_sp(Platform::GetHostPlatform());
921 assert(default_platform_sp
);
922 m_platform_list
.Append(default_platform_sp
, true);
924 // Create the dummy target.
926 ArchSpec
arch(Target::GetDefaultArchitecture());
928 arch
= HostInfo::GetArchitecture();
929 assert(arch
.IsValid() && "No valid default or host archspec");
930 const bool is_dummy_target
= true;
931 m_dummy_target_sp
.reset(
932 new Target(*this, arch
, default_platform_sp
, is_dummy_target
));
934 assert(m_dummy_target_sp
.get() && "Couldn't construct dummy target?");
936 OptionValueUInt64
*term_width
=
937 m_collection_sp
->GetPropertyAtIndexAsOptionValueUInt64(
938 ePropertyTerminalWidth
);
939 term_width
->SetMinimumValue(10);
941 OptionValueUInt64
*term_height
=
942 m_collection_sp
->GetPropertyAtIndexAsOptionValueUInt64(
943 ePropertyTerminalHeight
);
944 term_height
->SetMinimumValue(10);
946 // Turn off use-color if this is a dumb terminal.
947 const char *term
= getenv("TERM");
948 if (term
&& !strcmp(term
, "dumb"))
950 // Turn off use-color if we don't write to a terminal with color support.
951 if (!GetOutputFile().GetIsTerminalWithColors())
954 if (Diagnostics::Enabled()) {
955 m_diagnostics_callback_id
= Diagnostics::Instance().AddCallback(
956 [this](const FileSpec
&dir
) -> llvm::Error
{
957 for (auto &entry
: m_stream_handlers
) {
958 llvm::StringRef log_path
= entry
.first();
959 llvm::StringRef file_name
= llvm::sys::path::filename(log_path
);
960 FileSpec destination
= dir
.CopyByAppendingPathComponent(file_name
);
962 llvm::sys::fs::copy_file(log_path
, destination
.GetPath());
964 return llvm::errorCodeToError(ec
);
966 return llvm::Error::success();
970 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
971 // Enabling use of ANSI color codes because LLDB is using them to highlight
973 llvm::sys::Process::UseANSIEscapeCodes(true);
977 Debugger::~Debugger() { Clear(); }
979 void Debugger::Clear() {
980 // Make sure we call this function only once. With the C++ global destructor
981 // chain having a list of debuggers and with code that can be running on
982 // other threads, we need to ensure this doesn't happen multiple times.
984 // The following functions call Debugger::Clear():
985 // Debugger::~Debugger();
986 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
987 // static void Debugger::Terminate();
988 llvm::call_once(m_clear_once
, [this]() {
990 StopIOHandlerThread();
991 StopEventHandlerThread();
992 m_listener_sp
->Clear();
993 for (TargetSP target_sp
: m_target_list
.Targets()) {
995 if (ProcessSP process_sp
= target_sp
->GetProcessSP())
996 process_sp
->Finalize(false /* not destructing */);
997 target_sp
->Destroy();
1000 m_broadcaster_manager_sp
->Clear();
1002 // Close the input file _before_ we close the input read communications
1003 // class as it does NOT own the input file, our m_input_file does.
1004 m_terminal_state
.Clear();
1005 GetInputFile().Close();
1007 m_command_interpreter_up
->Clear();
1009 if (Diagnostics::Enabled())
1010 Diagnostics::Instance().RemoveCallback(m_diagnostics_callback_id
);
1014 bool Debugger::GetAsyncExecution() {
1015 return !m_command_interpreter_up
->GetSynchronous();
1018 void Debugger::SetAsyncExecution(bool async_execution
) {
1019 m_command_interpreter_up
->SetSynchronous(!async_execution
);
1022 repro::DataRecorder
*Debugger::GetInputRecorder() { return m_input_recorder
; }
1024 static inline int OpenPipe(int fds
[2], std::size_t size
) {
1026 return _pipe(fds
, size
, O_BINARY
);
1033 Status
Debugger::SetInputString(const char *data
) {
1035 enum PIPES
{ READ
, WRITE
}; // Indexes for the read and write fds
1036 int fds
[2] = {-1, -1};
1038 if (data
== nullptr) {
1039 result
= Status::FromErrorString("String data is null");
1043 size_t size
= strlen(data
);
1045 result
= Status::FromErrorString("String data is empty");
1049 if (OpenPipe(fds
, size
) != 0) {
1050 result
= Status::FromErrorString(
1051 "can't create pipe file descriptors for LLDB commands");
1055 int r
= write(fds
[WRITE
], data
, size
);
1057 // Close the write end of the pipe, so that the command interpreter will exit
1058 // when it consumes all the data.
1059 llvm::sys::Process::SafelyCloseFileDescriptor(fds
[WRITE
]);
1061 // Open the read file descriptor as a FILE * that we can return as an input
1063 FILE *commands_file
= fdopen(fds
[READ
], "rb");
1064 if (commands_file
== nullptr) {
1065 result
= Status::FromErrorStringWithFormat(
1066 "fdopen(%i, \"rb\") failed (errno = %i) "
1067 "when trying to open LLDB commands pipe",
1069 llvm::sys::Process::SafelyCloseFileDescriptor(fds
[READ
]);
1073 SetInputFile((FileSP
)std::make_shared
<NativeFile
>(commands_file
, true));
1077 void Debugger::SetInputFile(FileSP file_sp
) {
1078 assert(file_sp
&& file_sp
->IsValid());
1079 m_input_file_sp
= std::move(file_sp
);
1080 // Save away the terminal state if that is relevant, so that we can restore
1081 // it in RestoreInputState.
1082 SaveInputTerminalState();
1085 void Debugger::SetOutputFile(FileSP file_sp
) {
1086 assert(file_sp
&& file_sp
->IsValid());
1087 m_output_stream_sp
= std::make_shared
<StreamFile
>(file_sp
);
1090 void Debugger::SetErrorFile(FileSP file_sp
) {
1091 assert(file_sp
&& file_sp
->IsValid());
1092 m_error_stream_sp
= std::make_shared
<StreamFile
>(file_sp
);
1095 void Debugger::SaveInputTerminalState() {
1096 int fd
= GetInputFile().GetDescriptor();
1097 if (fd
!= File::kInvalidDescriptor
)
1098 m_terminal_state
.Save(fd
, true);
1101 void Debugger::RestoreInputTerminalState() { m_terminal_state
.Restore(); }
1103 ExecutionContext
Debugger::GetSelectedExecutionContext() {
1104 bool adopt_selected
= true;
1105 ExecutionContextRef
exe_ctx_ref(GetSelectedTarget().get(), adopt_selected
);
1106 return ExecutionContext(exe_ctx_ref
);
1109 void Debugger::DispatchInputInterrupt() {
1110 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_stack
.GetMutex());
1111 IOHandlerSP
reader_sp(m_io_handler_stack
.Top());
1113 reader_sp
->Interrupt();
1116 void Debugger::DispatchInputEndOfFile() {
1117 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_stack
.GetMutex());
1118 IOHandlerSP
reader_sp(m_io_handler_stack
.Top());
1120 reader_sp
->GotEOF();
1123 void Debugger::ClearIOHandlers() {
1124 // The bottom input reader should be the main debugger input reader. We do
1125 // not want to close that one here.
1126 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_stack
.GetMutex());
1127 while (m_io_handler_stack
.GetSize() > 1) {
1128 IOHandlerSP
reader_sp(m_io_handler_stack
.Top());
1130 PopIOHandler(reader_sp
);
1134 void Debugger::RunIOHandlers() {
1135 IOHandlerSP reader_sp
= m_io_handler_stack
.Top();
1142 std::lock_guard
<std::recursive_mutex
> guard(
1143 m_io_handler_synchronous_mutex
);
1145 // Remove all input readers that are done from the top of the stack
1147 IOHandlerSP top_reader_sp
= m_io_handler_stack
.Top();
1148 if (top_reader_sp
&& top_reader_sp
->GetIsDone())
1149 PopIOHandler(top_reader_sp
);
1153 reader_sp
= m_io_handler_stack
.Top();
1159 void Debugger::RunIOHandlerSync(const IOHandlerSP
&reader_sp
) {
1160 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_synchronous_mutex
);
1162 PushIOHandler(reader_sp
);
1163 IOHandlerSP top_reader_sp
= reader_sp
;
1165 while (top_reader_sp
) {
1166 top_reader_sp
->Run();
1168 // Don't unwind past the starting point.
1169 if (top_reader_sp
.get() == reader_sp
.get()) {
1170 if (PopIOHandler(reader_sp
))
1174 // If we pushed new IO handlers, pop them if they're done or restart the
1175 // loop to run them if they're not.
1177 top_reader_sp
= m_io_handler_stack
.Top();
1178 if (top_reader_sp
&& top_reader_sp
->GetIsDone()) {
1179 PopIOHandler(top_reader_sp
);
1180 // Don't unwind past the starting point.
1181 if (top_reader_sp
.get() == reader_sp
.get())
1190 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP
&reader_sp
) {
1191 return m_io_handler_stack
.IsTop(reader_sp
);
1194 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type
,
1195 IOHandler::Type second_top_type
) {
1196 return m_io_handler_stack
.CheckTopIOHandlerTypes(top_type
, second_top_type
);
1199 void Debugger::PrintAsync(const char *s
, size_t len
, bool is_stdout
) {
1200 bool printed
= m_io_handler_stack
.PrintAsync(s
, len
, is_stdout
);
1202 lldb::StreamFileSP stream
=
1203 is_stdout
? m_output_stream_sp
: m_error_stream_sp
;
1204 stream
->Write(s
, len
);
1208 llvm::StringRef
Debugger::GetTopIOHandlerControlSequence(char ch
) {
1209 return m_io_handler_stack
.GetTopIOHandlerControlSequence(ch
);
1212 const char *Debugger::GetIOHandlerCommandPrefix() {
1213 return m_io_handler_stack
.GetTopIOHandlerCommandPrefix();
1216 const char *Debugger::GetIOHandlerHelpPrologue() {
1217 return m_io_handler_stack
.GetTopIOHandlerHelpPrologue();
1220 bool Debugger::RemoveIOHandler(const IOHandlerSP
&reader_sp
) {
1221 return PopIOHandler(reader_sp
);
1224 void Debugger::RunIOHandlerAsync(const IOHandlerSP
&reader_sp
,
1225 bool cancel_top_handler
) {
1226 PushIOHandler(reader_sp
, cancel_top_handler
);
1229 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP
&in
, StreamFileSP
&out
,
1230 StreamFileSP
&err
) {
1231 // Before an IOHandler runs, it must have in/out/err streams. This function
1232 // is called when one ore more of the streams are nullptr. We use the top
1233 // input reader's in/out/err streams, or fall back to the debugger file
1234 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1236 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_stack
.GetMutex());
1237 IOHandlerSP
top_reader_sp(m_io_handler_stack
.Top());
1238 // If no STDIN has been set, then set it appropriately
1239 if (!in
|| !in
->IsValid()) {
1241 in
= top_reader_sp
->GetInputFileSP();
1243 in
= GetInputFileSP();
1244 // If there is nothing, use stdin
1246 in
= std::make_shared
<NativeFile
>(stdin
, false);
1248 // If no STDOUT has been set, then set it appropriately
1249 if (!out
|| !out
->GetFile().IsValid()) {
1251 out
= top_reader_sp
->GetOutputStreamFileSP();
1253 out
= GetOutputStreamSP();
1254 // If there is nothing, use stdout
1256 out
= std::make_shared
<StreamFile
>(stdout
, false);
1258 // If no STDERR has been set, then set it appropriately
1259 if (!err
|| !err
->GetFile().IsValid()) {
1261 err
= top_reader_sp
->GetErrorStreamFileSP();
1263 err
= GetErrorStreamSP();
1264 // If there is nothing, use stderr
1266 err
= std::make_shared
<StreamFile
>(stderr
, false);
1270 void Debugger::PushIOHandler(const IOHandlerSP
&reader_sp
,
1271 bool cancel_top_handler
) {
1275 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_stack
.GetMutex());
1277 // Get the current top input reader...
1278 IOHandlerSP
top_reader_sp(m_io_handler_stack
.Top());
1280 // Don't push the same IO handler twice...
1281 if (reader_sp
== top_reader_sp
)
1284 // Push our new input reader
1285 m_io_handler_stack
.Push(reader_sp
);
1286 reader_sp
->Activate();
1288 // Interrupt the top input reader to it will exit its Run() function and let
1289 // this new input reader take over
1290 if (top_reader_sp
) {
1291 top_reader_sp
->Deactivate();
1292 if (cancel_top_handler
)
1293 top_reader_sp
->Cancel();
1297 bool Debugger::PopIOHandler(const IOHandlerSP
&pop_reader_sp
) {
1301 std::lock_guard
<std::recursive_mutex
> guard(m_io_handler_stack
.GetMutex());
1303 // The reader on the stop of the stack is done, so let the next read on the
1304 // stack refresh its prompt and if there is one...
1305 if (m_io_handler_stack
.IsEmpty())
1308 IOHandlerSP
reader_sp(m_io_handler_stack
.Top());
1310 if (pop_reader_sp
!= reader_sp
)
1313 reader_sp
->Deactivate();
1314 reader_sp
->Cancel();
1315 m_io_handler_stack
.Pop();
1317 reader_sp
= m_io_handler_stack
.Top();
1319 reader_sp
->Activate();
1324 StreamSP
Debugger::GetAsyncOutputStream() {
1325 return std::make_shared
<StreamAsynchronousIO
>(*this, true, GetUseColor());
1328 StreamSP
Debugger::GetAsyncErrorStream() {
1329 return std::make_shared
<StreamAsynchronousIO
>(*this, false, GetUseColor());
1332 void Debugger::RequestInterrupt() {
1333 std::lock_guard
<std::mutex
> guard(m_interrupt_mutex
);
1334 m_interrupt_requested
++;
1337 void Debugger::CancelInterruptRequest() {
1338 std::lock_guard
<std::mutex
> guard(m_interrupt_mutex
);
1339 if (m_interrupt_requested
> 0)
1340 m_interrupt_requested
--;
1343 bool Debugger::InterruptRequested() {
1344 // This is the one we should call internally. This will return true either
1345 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1346 // or if we are on the IOHandler thread and there's a CommandInterpreter
1348 if (!IsIOHandlerThreadCurrentThread()) {
1349 std::lock_guard
<std::mutex
> guard(m_interrupt_mutex
);
1350 return m_interrupt_requested
!= 0;
1352 return GetCommandInterpreter().WasInterrupted();
1355 Debugger::InterruptionReport::InterruptionReport(
1356 std::string function_name
, const llvm::formatv_object_base
&payload
)
1357 : m_function_name(std::move(function_name
)),
1358 m_interrupt_time(std::chrono::system_clock::now()),
1359 m_thread_id(llvm::get_threadid()) {
1360 llvm::raw_string_ostream
desc(m_description
);
1361 desc
<< payload
<< "\n";
1364 void Debugger::ReportInterruption(const InterruptionReport
&report
) {
1365 // For now, just log the description:
1366 Log
*log
= GetLog(LLDBLog::Host
);
1367 LLDB_LOG(log
, "Interruption: {0}", report
.m_description
);
1370 Debugger::DebuggerList
Debugger::DebuggersRequestingInterruption() {
1371 DebuggerList result
;
1372 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1373 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1374 for (auto debugger_sp
: *g_debugger_list_ptr
) {
1375 if (debugger_sp
->InterruptRequested())
1376 result
.push_back(debugger_sp
);
1382 size_t Debugger::GetNumDebuggers() {
1383 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1384 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1385 return g_debugger_list_ptr
->size();
1390 lldb::DebuggerSP
Debugger::GetDebuggerAtIndex(size_t index
) {
1391 DebuggerSP debugger_sp
;
1393 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1394 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1395 if (index
< g_debugger_list_ptr
->size())
1396 debugger_sp
= g_debugger_list_ptr
->at(index
);
1402 DebuggerSP
Debugger::FindDebuggerWithID(lldb::user_id_t id
) {
1403 DebuggerSP debugger_sp
;
1405 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1406 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1407 DebuggerList::iterator pos
, end
= g_debugger_list_ptr
->end();
1408 for (pos
= g_debugger_list_ptr
->begin(); pos
!= end
; ++pos
) {
1409 if ((*pos
)->GetID() == id
) {
1418 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry
*format
,
1419 const SymbolContext
*sc
,
1420 const SymbolContext
*prev_sc
,
1421 const ExecutionContext
*exe_ctx
,
1422 const Address
*addr
, Stream
&s
) {
1423 FormatEntity::Entry format_entry
;
1425 if (format
== nullptr) {
1426 if (exe_ctx
!= nullptr && exe_ctx
->HasTargetScope())
1427 format
= exe_ctx
->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1428 if (format
== nullptr) {
1429 FormatEntity::Parse("${addr}: ", format_entry
);
1430 format
= &format_entry
;
1433 bool function_changed
= false;
1434 bool initial_function
= false;
1435 if (prev_sc
&& (prev_sc
->function
|| prev_sc
->symbol
)) {
1436 if (sc
&& (sc
->function
|| sc
->symbol
)) {
1437 if (prev_sc
->symbol
&& sc
->symbol
) {
1438 if (!sc
->symbol
->Compare(prev_sc
->symbol
->GetName(),
1439 prev_sc
->symbol
->GetType())) {
1440 function_changed
= true;
1442 } else if (prev_sc
->function
&& sc
->function
) {
1443 if (prev_sc
->function
->GetMangled() != sc
->function
->GetMangled()) {
1444 function_changed
= true;
1449 // The first context on a list of instructions will have a prev_sc that has
1450 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1451 // would return false. But we do get a prev_sc pointer.
1452 if ((sc
&& (sc
->function
|| sc
->symbol
)) && prev_sc
&&
1453 (prev_sc
->function
== nullptr && prev_sc
->symbol
== nullptr)) {
1454 initial_function
= true;
1456 return FormatEntity::Format(*format
, s
, sc
, exe_ctx
, addr
, nullptr,
1457 function_changed
, initial_function
);
1460 void Debugger::AssertCallback(llvm::StringRef message
,
1461 llvm::StringRef backtrace
,
1462 llvm::StringRef prompt
) {
1463 Debugger::ReportError(
1464 llvm::formatv("{0}\n{1}{2}", message
, backtrace
, prompt
).str());
1467 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback
,
1469 // For simplicity's sake, I am not going to deal with how to close down any
1470 // open logging streams, I just redirect everything from here on out to the
1472 m_callback_handler_sp
=
1473 std::make_shared
<CallbackLogHandler
>(log_callback
, baton
);
1476 void Debugger::SetDestroyCallback(
1477 lldb_private::DebuggerDestroyCallback destroy_callback
, void *baton
) {
1478 std::lock_guard
<std::mutex
> guard(m_destroy_callback_mutex
);
1479 m_destroy_callbacks
.clear();
1480 const lldb::callback_token_t token
= m_destroy_callback_next_token
++;
1481 m_destroy_callbacks
.emplace_back(token
, destroy_callback
, baton
);
1484 lldb::callback_token_t
Debugger::AddDestroyCallback(
1485 lldb_private::DebuggerDestroyCallback destroy_callback
, void *baton
) {
1486 std::lock_guard
<std::mutex
> guard(m_destroy_callback_mutex
);
1487 const lldb::callback_token_t token
= m_destroy_callback_next_token
++;
1488 m_destroy_callbacks
.emplace_back(token
, destroy_callback
, baton
);
1492 bool Debugger::RemoveDestroyCallback(lldb::callback_token_t token
) {
1493 std::lock_guard
<std::mutex
> guard(m_destroy_callback_mutex
);
1494 for (auto it
= m_destroy_callbacks
.begin(); it
!= m_destroy_callbacks
.end();
1496 if (it
->token
== token
) {
1497 m_destroy_callbacks
.erase(it
);
1504 static void PrivateReportProgress(Debugger
&debugger
, uint64_t progress_id
,
1505 std::string title
, std::string details
,
1506 uint64_t completed
, uint64_t total
,
1507 bool is_debugger_specific
,
1508 uint32_t progress_broadcast_bit
) {
1509 // Only deliver progress events if we have any progress listeners.
1510 if (!debugger
.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit
))
1513 EventSP
event_sp(new Event(
1514 progress_broadcast_bit
,
1515 new ProgressEventData(progress_id
, std::move(title
), std::move(details
),
1516 completed
, total
, is_debugger_specific
)));
1517 debugger
.GetBroadcaster().BroadcastEvent(event_sp
);
1520 void Debugger::ReportProgress(uint64_t progress_id
, std::string title
,
1521 std::string details
, uint64_t completed
,
1523 std::optional
<lldb::user_id_t
> debugger_id
,
1524 uint32_t progress_category_bit
) {
1525 // Check if this progress is for a specific debugger.
1527 // It is debugger specific, grab it and deliver the event if the debugger
1529 DebuggerSP debugger_sp
= FindDebuggerWithID(*debugger_id
);
1531 PrivateReportProgress(*debugger_sp
, progress_id
, std::move(title
),
1532 std::move(details
), completed
, total
,
1533 /*is_debugger_specific*/ true,
1534 progress_category_bit
);
1537 // The progress event is not debugger specific, iterate over all debuggers
1538 // and deliver a progress event to each one.
1539 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1540 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1541 DebuggerList::iterator pos
, end
= g_debugger_list_ptr
->end();
1542 for (pos
= g_debugger_list_ptr
->begin(); pos
!= end
; ++pos
)
1543 PrivateReportProgress(*(*pos
), progress_id
, title
, details
, completed
,
1544 total
, /*is_debugger_specific*/ false,
1545 progress_category_bit
);
1549 static void PrivateReportDiagnostic(Debugger
&debugger
, Severity severity
,
1550 std::string message
,
1551 bool debugger_specific
) {
1552 uint32_t event_type
= 0;
1555 assert(false && "eSeverityInfo should not be broadcast");
1557 case eSeverityWarning
:
1558 event_type
= lldb::eBroadcastBitWarning
;
1560 case eSeverityError
:
1561 event_type
= lldb::eBroadcastBitError
;
1565 Broadcaster
&broadcaster
= debugger
.GetBroadcaster();
1566 if (!broadcaster
.EventTypeHasListeners(event_type
)) {
1567 // Diagnostics are too important to drop. If nobody is listening, print the
1568 // diagnostic directly to the debugger's error stream.
1569 DiagnosticEventData
event_data(severity
, std::move(message
),
1571 StreamSP stream
= debugger
.GetAsyncErrorStream();
1572 event_data
.Dump(stream
.get());
1575 EventSP event_sp
= std::make_shared
<Event
>(
1577 new DiagnosticEventData(severity
, std::move(message
), debugger_specific
));
1578 broadcaster
.BroadcastEvent(event_sp
);
1581 void Debugger::ReportDiagnosticImpl(Severity severity
, std::string message
,
1582 std::optional
<lldb::user_id_t
> debugger_id
,
1583 std::once_flag
*once
) {
1584 auto ReportDiagnosticLambda
= [&]() {
1585 // Always log diagnostics to the system log.
1586 Host::SystemLog(severity
, message
);
1588 // The diagnostic subsystem is optional but we still want to broadcast
1589 // events when it's disabled.
1590 if (Diagnostics::Enabled())
1591 Diagnostics::Instance().Report(message
);
1593 // We don't broadcast info events.
1594 if (severity
== lldb::eSeverityInfo
)
1597 // Check if this diagnostic is for a specific debugger.
1599 // It is debugger specific, grab it and deliver the event if the debugger
1601 DebuggerSP debugger_sp
= FindDebuggerWithID(*debugger_id
);
1603 PrivateReportDiagnostic(*debugger_sp
, severity
, std::move(message
),
1607 // The diagnostic event is not debugger specific, iterate over all debuggers
1608 // and deliver a diagnostic event to each one.
1609 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1610 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1611 for (const auto &debugger
: *g_debugger_list_ptr
)
1612 PrivateReportDiagnostic(*debugger
, severity
, message
, false);
1617 std::call_once(*once
, ReportDiagnosticLambda
);
1619 ReportDiagnosticLambda();
1622 void Debugger::ReportWarning(std::string message
,
1623 std::optional
<lldb::user_id_t
> debugger_id
,
1624 std::once_flag
*once
) {
1625 ReportDiagnosticImpl(eSeverityWarning
, std::move(message
), debugger_id
, once
);
1628 void Debugger::ReportError(std::string message
,
1629 std::optional
<lldb::user_id_t
> debugger_id
,
1630 std::once_flag
*once
) {
1631 ReportDiagnosticImpl(eSeverityError
, std::move(message
), debugger_id
, once
);
1634 void Debugger::ReportInfo(std::string message
,
1635 std::optional
<lldb::user_id_t
> debugger_id
,
1636 std::once_flag
*once
) {
1637 ReportDiagnosticImpl(eSeverityInfo
, std::move(message
), debugger_id
, once
);
1640 void Debugger::ReportSymbolChange(const ModuleSpec
&module_spec
) {
1641 if (g_debugger_list_ptr
&& g_debugger_list_mutex_ptr
) {
1642 std::lock_guard
<std::recursive_mutex
> guard(*g_debugger_list_mutex_ptr
);
1643 for (DebuggerSP debugger_sp
: *g_debugger_list_ptr
) {
1644 EventSP event_sp
= std::make_shared
<Event
>(
1645 lldb::eBroadcastSymbolChange
,
1646 new SymbolChangeEventData(debugger_sp
, module_spec
));
1647 debugger_sp
->GetBroadcaster().BroadcastEvent(event_sp
);
1652 static std::shared_ptr
<LogHandler
>
1653 CreateLogHandler(LogHandlerKind log_handler_kind
, int fd
, bool should_close
,
1654 size_t buffer_size
) {
1655 switch (log_handler_kind
) {
1656 case eLogHandlerStream
:
1657 return std::make_shared
<StreamLogHandler
>(fd
, should_close
, buffer_size
);
1658 case eLogHandlerCircular
:
1659 return std::make_shared
<RotatingLogHandler
>(buffer_size
);
1660 case eLogHandlerSystem
:
1661 return std::make_shared
<SystemLogHandler
>();
1662 case eLogHandlerCallback
:
1668 bool Debugger::EnableLog(llvm::StringRef channel
,
1669 llvm::ArrayRef
<const char *> categories
,
1670 llvm::StringRef log_file
, uint32_t log_options
,
1671 size_t buffer_size
, LogHandlerKind log_handler_kind
,
1672 llvm::raw_ostream
&error_stream
) {
1674 std::shared_ptr
<LogHandler
> log_handler_sp
;
1675 if (m_callback_handler_sp
) {
1676 log_handler_sp
= m_callback_handler_sp
;
1677 // For now when using the callback mode you always get thread & timestamp.
1679 LLDB_LOG_OPTION_PREPEND_TIMESTAMP
| LLDB_LOG_OPTION_PREPEND_THREAD_NAME
;
1680 } else if (log_file
.empty()) {
1682 CreateLogHandler(log_handler_kind
, GetOutputFile().GetDescriptor(),
1683 /*should_close=*/false, buffer_size
);
1685 auto pos
= m_stream_handlers
.find(log_file
);
1686 if (pos
!= m_stream_handlers
.end())
1687 log_handler_sp
= pos
->second
.lock();
1688 if (!log_handler_sp
) {
1689 File::OpenOptions flags
=
1690 File::eOpenOptionWriteOnly
| File::eOpenOptionCanCreate
;
1691 if (log_options
& LLDB_LOG_OPTION_APPEND
)
1692 flags
|= File::eOpenOptionAppend
;
1694 flags
|= File::eOpenOptionTruncate
;
1695 llvm::Expected
<FileUP
> file
= FileSystem::Instance().Open(
1696 FileSpec(log_file
), flags
, lldb::eFilePermissionsFileDefault
, false);
1698 error_stream
<< "Unable to open log file '" << log_file
1699 << "': " << llvm::toString(file
.takeError()) << "\n";
1704 CreateLogHandler(log_handler_kind
, (*file
)->GetDescriptor(),
1705 /*should_close=*/true, buffer_size
);
1706 m_stream_handlers
[log_file
] = log_handler_sp
;
1709 assert(log_handler_sp
);
1711 if (log_options
== 0)
1712 log_options
= LLDB_LOG_OPTION_PREPEND_THREAD_NAME
;
1714 return Log::EnableLogChannel(log_handler_sp
, log_options
, channel
, categories
,
1719 Debugger::GetScriptInterpreter(bool can_create
,
1720 std::optional
<lldb::ScriptLanguage
> language
) {
1721 std::lock_guard
<std::recursive_mutex
> locker(m_script_interpreter_mutex
);
1722 lldb::ScriptLanguage script_language
=
1723 language
? *language
: GetScriptLanguage();
1725 if (!m_script_interpreters
[script_language
]) {
1728 m_script_interpreters
[script_language
] =
1729 PluginManager::GetScriptInterpreterForLanguage(script_language
, *this);
1732 return m_script_interpreters
[script_language
].get();
1735 SourceManager
&Debugger::GetSourceManager() {
1736 if (!m_source_manager_up
)
1737 m_source_manager_up
= std::make_unique
<SourceManager
>(shared_from_this());
1738 return *m_source_manager_up
;
1741 // This function handles events that were broadcast by the process.
1742 void Debugger::HandleBreakpointEvent(const EventSP
&event_sp
) {
1743 using namespace lldb
;
1744 const uint32_t event_type
=
1745 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1748 // if (event_type & eBreakpointEventTypeAdded
1749 // || event_type & eBreakpointEventTypeRemoved
1750 // || event_type & eBreakpointEventTypeEnabled
1751 // || event_type & eBreakpointEventTypeDisabled
1752 // || event_type & eBreakpointEventTypeCommandChanged
1753 // || event_type & eBreakpointEventTypeConditionChanged
1754 // || event_type & eBreakpointEventTypeIgnoreChanged
1755 // || event_type & eBreakpointEventTypeLocationsResolved)
1757 // // Don't do anything about these events, since the breakpoint
1758 // commands already echo these actions.
1761 if (event_type
& eBreakpointEventTypeLocationsAdded
) {
1762 uint32_t num_new_locations
=
1763 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1765 if (num_new_locations
> 0) {
1766 BreakpointSP breakpoint
=
1767 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp
);
1768 StreamSP
output_sp(GetAsyncOutputStream());
1770 output_sp
->Printf("%d location%s added to breakpoint %d\n",
1771 num_new_locations
, num_new_locations
== 1 ? "" : "s",
1772 breakpoint
->GetID());
1777 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1779 // // These locations just get disabled, not sure it is worth spamming
1780 // folks about this on the command line.
1782 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1784 // // This might be an interesting thing to note, but I'm going to
1785 // leave it quiet for now, it just looked noisy.
1789 void Debugger::FlushProcessOutput(Process
&process
, bool flush_stdout
,
1790 bool flush_stderr
) {
1791 const auto &flush
= [&](Stream
&stream
,
1792 size_t (Process::*get
)(char *, size_t, Status
&)) {
1796 while ((len
= (process
.*get
)(buffer
, sizeof(buffer
), error
)) > 0)
1797 stream
.Write(buffer
, len
);
1801 std::lock_guard
<std::mutex
> guard(m_output_flush_mutex
);
1803 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT
);
1805 flush(*GetAsyncErrorStream(), &Process::GetSTDERR
);
1808 // This function handles events that were broadcast by the process.
1809 void Debugger::HandleProcessEvent(const EventSP
&event_sp
) {
1810 using namespace lldb
;
1811 const uint32_t event_type
= event_sp
->GetType();
1812 ProcessSP process_sp
=
1813 (event_type
== Process::eBroadcastBitStructuredData
)
1814 ? EventDataStructuredData::GetProcessFromEvent(event_sp
.get())
1815 : Process::ProcessEventData::GetProcessFromEvent(event_sp
.get());
1817 StreamSP output_stream_sp
= GetAsyncOutputStream();
1818 StreamSP error_stream_sp
= GetAsyncErrorStream();
1819 const bool gui_enabled
= IsForwardingEvents();
1822 bool pop_process_io_handler
= false;
1825 bool state_is_stopped
= false;
1826 const bool got_state_changed
=
1827 (event_type
& Process::eBroadcastBitStateChanged
) != 0;
1828 const bool got_stdout
= (event_type
& Process::eBroadcastBitSTDOUT
) != 0;
1829 const bool got_stderr
= (event_type
& Process::eBroadcastBitSTDERR
) != 0;
1830 const bool got_structured_data
=
1831 (event_type
& Process::eBroadcastBitStructuredData
) != 0;
1833 if (got_state_changed
) {
1834 StateType event_state
=
1835 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
1836 state_is_stopped
= StateIsStoppedState(event_state
, false);
1839 // Display running state changes first before any STDIO
1840 if (got_state_changed
&& !state_is_stopped
) {
1841 // This is a public stop which we are going to announce to the user, so
1842 // we should force the most relevant frame selection here.
1843 Process::HandleProcessStateChangedEvent(event_sp
, output_stream_sp
.get(),
1844 SelectMostRelevantFrame
,
1845 pop_process_io_handler
);
1848 // Now display STDOUT and STDERR
1849 FlushProcessOutput(*process_sp
, got_stdout
|| got_state_changed
,
1850 got_stderr
|| got_state_changed
);
1852 // Give structured data events an opportunity to display.
1853 if (got_structured_data
) {
1854 StructuredDataPluginSP plugin_sp
=
1855 EventDataStructuredData::GetPluginFromEvent(event_sp
.get());
1857 auto structured_data_sp
=
1858 EventDataStructuredData::GetObjectFromEvent(event_sp
.get());
1859 if (output_stream_sp
) {
1860 StreamString content_stream
;
1862 plugin_sp
->GetDescription(structured_data_sp
, content_stream
);
1863 if (error
.Success()) {
1864 if (!content_stream
.GetString().empty()) {
1866 content_stream
.PutChar('\n');
1867 content_stream
.Flush();
1870 output_stream_sp
->PutCString(content_stream
.GetString());
1873 error_stream_sp
->Format("Failed to print structured "
1874 "data with plugin {0}: {1}",
1875 plugin_sp
->GetPluginName(), error
);
1881 // Now display any stopped state changes after any STDIO
1882 if (got_state_changed
&& state_is_stopped
) {
1883 Process::HandleProcessStateChangedEvent(event_sp
, output_stream_sp
.get(),
1884 SelectMostRelevantFrame
,
1885 pop_process_io_handler
);
1888 output_stream_sp
->Flush();
1889 error_stream_sp
->Flush();
1891 if (pop_process_io_handler
)
1892 process_sp
->PopProcessIOHandler();
1896 void Debugger::HandleThreadEvent(const EventSP
&event_sp
) {
1897 // At present the only thread event we handle is the Frame Changed event, and
1898 // all we do for that is just reprint the thread status for that thread.
1899 using namespace lldb
;
1900 const uint32_t event_type
= event_sp
->GetType();
1901 const bool stop_format
= true;
1902 if (event_type
== Thread::eBroadcastBitStackChanged
||
1903 event_type
== Thread::eBroadcastBitThreadSelected
) {
1905 Thread::ThreadEventData::GetThreadFromEvent(event_sp
.get()));
1907 thread_sp
->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format
,
1908 /*show_hidden*/ true);
1913 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp
; }
1915 void Debugger::EnableForwardEvents(const ListenerSP
&listener_sp
) {
1916 m_forward_listener_sp
= listener_sp
;
1919 void Debugger::CancelForwardEvents(const ListenerSP
&listener_sp
) {
1920 m_forward_listener_sp
.reset();
1923 lldb::thread_result_t
Debugger::DefaultEventHandler() {
1924 ListenerSP
listener_sp(GetListener());
1925 ConstString
broadcaster_class_target(Target::GetStaticBroadcasterClass());
1926 ConstString
broadcaster_class_process(Process::GetStaticBroadcasterClass());
1927 ConstString
broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1928 BroadcastEventSpec
target_event_spec(broadcaster_class_target
,
1929 Target::eBroadcastBitBreakpointChanged
);
1931 BroadcastEventSpec
process_event_spec(
1932 broadcaster_class_process
,
1933 Process::eBroadcastBitStateChanged
| Process::eBroadcastBitSTDOUT
|
1934 Process::eBroadcastBitSTDERR
| Process::eBroadcastBitStructuredData
);
1936 BroadcastEventSpec
thread_event_spec(broadcaster_class_thread
,
1937 Thread::eBroadcastBitStackChanged
|
1938 Thread::eBroadcastBitThreadSelected
);
1940 listener_sp
->StartListeningForEventSpec(m_broadcaster_manager_sp
,
1942 listener_sp
->StartListeningForEventSpec(m_broadcaster_manager_sp
,
1943 process_event_spec
);
1944 listener_sp
->StartListeningForEventSpec(m_broadcaster_manager_sp
,
1946 listener_sp
->StartListeningForEvents(
1947 m_command_interpreter_up
.get(),
1948 CommandInterpreter::eBroadcastBitQuitCommandReceived
|
1949 CommandInterpreter::eBroadcastBitAsynchronousOutputData
|
1950 CommandInterpreter::eBroadcastBitAsynchronousErrorData
);
1952 listener_sp
->StartListeningForEvents(
1953 &m_broadcaster
, lldb::eBroadcastBitProgress
| lldb::eBroadcastBitWarning
|
1954 lldb::eBroadcastBitError
|
1955 lldb::eBroadcastSymbolChange
);
1957 // Let the thread that spawned us know that we have started up and that we
1958 // are now listening to all required events so no events get missed
1959 m_sync_broadcaster
.BroadcastEvent(eBroadcastBitEventThreadIsListening
);
1964 if (listener_sp
->GetEvent(event_sp
, std::nullopt
)) {
1966 Broadcaster
*broadcaster
= event_sp
->GetBroadcaster();
1968 uint32_t event_type
= event_sp
->GetType();
1969 ConstString
broadcaster_class(broadcaster
->GetBroadcasterClass());
1970 if (broadcaster_class
== broadcaster_class_process
) {
1971 HandleProcessEvent(event_sp
);
1972 } else if (broadcaster_class
== broadcaster_class_target
) {
1973 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1975 HandleBreakpointEvent(event_sp
);
1977 } else if (broadcaster_class
== broadcaster_class_thread
) {
1978 HandleThreadEvent(event_sp
);
1979 } else if (broadcaster
== m_command_interpreter_up
.get()) {
1981 CommandInterpreter::eBroadcastBitQuitCommandReceived
) {
1983 } else if (event_type
&
1984 CommandInterpreter::eBroadcastBitAsynchronousErrorData
) {
1985 const char *data
= static_cast<const char *>(
1986 EventDataBytes::GetBytesFromEvent(event_sp
.get()));
1987 if (data
&& data
[0]) {
1988 StreamSP
error_sp(GetAsyncErrorStream());
1990 error_sp
->PutCString(data
);
1994 } else if (event_type
& CommandInterpreter::
1995 eBroadcastBitAsynchronousOutputData
) {
1996 const char *data
= static_cast<const char *>(
1997 EventDataBytes::GetBytesFromEvent(event_sp
.get()));
1998 if (data
&& data
[0]) {
1999 StreamSP
output_sp(GetAsyncOutputStream());
2001 output_sp
->PutCString(data
);
2006 } else if (broadcaster
== &m_broadcaster
) {
2007 if (event_type
& lldb::eBroadcastBitProgress
)
2008 HandleProgressEvent(event_sp
);
2009 else if (event_type
& lldb::eBroadcastBitWarning
)
2010 HandleDiagnosticEvent(event_sp
);
2011 else if (event_type
& lldb::eBroadcastBitError
)
2012 HandleDiagnosticEvent(event_sp
);
2016 if (m_forward_listener_sp
)
2017 m_forward_listener_sp
->AddEvent(event_sp
);
2024 bool Debugger::StartEventHandlerThread() {
2025 if (!m_event_handler_thread
.IsJoinable()) {
2026 // We must synchronize with the DefaultEventHandler() thread to ensure it
2027 // is up and running and listening to events before we return from this
2028 // function. We do this by listening to events for the
2029 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2030 ConstString
full_name("lldb.debugger.event-handler");
2031 ListenerSP
listener_sp(Listener::MakeListener(full_name
.AsCString()));
2032 listener_sp
->StartListeningForEvents(&m_sync_broadcaster
,
2033 eBroadcastBitEventThreadIsListening
);
2035 llvm::StringRef thread_name
=
2036 full_name
.GetLength() < llvm::get_max_thread_name_length()
2037 ? full_name
.GetStringRef()
2038 : "dbg.evt-handler";
2040 // Use larger 8MB stack for this thread
2041 llvm::Expected
<HostThread
> event_handler_thread
=
2042 ThreadLauncher::LaunchThread(
2043 thread_name
, [this] { return DefaultEventHandler(); },
2044 g_debugger_event_thread_stack_bytes
);
2046 if (event_handler_thread
) {
2047 m_event_handler_thread
= *event_handler_thread
;
2049 LLDB_LOG_ERROR(GetLog(LLDBLog::Host
), event_handler_thread
.takeError(),
2050 "failed to launch host thread: {0}");
2053 // Make sure DefaultEventHandler() is running and listening to events
2054 // before we return from this function. We are only listening for events of
2055 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2056 // event, we just need to wait an infinite amount of time for it (nullptr
2057 // timeout as the first parameter)
2058 lldb::EventSP event_sp
;
2059 listener_sp
->GetEvent(event_sp
, std::nullopt
);
2061 return m_event_handler_thread
.IsJoinable();
2064 void Debugger::StopEventHandlerThread() {
2065 if (m_event_handler_thread
.IsJoinable()) {
2066 GetCommandInterpreter().BroadcastEvent(
2067 CommandInterpreter::eBroadcastBitQuitCommandReceived
);
2068 m_event_handler_thread
.Join(nullptr);
2072 lldb::thread_result_t
Debugger::IOHandlerThread() {
2074 StopEventHandlerThread();
2078 void Debugger::HandleProgressEvent(const lldb::EventSP
&event_sp
) {
2079 auto *data
= ProgressEventData::GetEventDataFromEvent(event_sp
.get());
2083 // Do some bookkeeping for the current event, regardless of whether we're
2084 // going to show the progress.
2085 const uint64_t id
= data
->GetID();
2086 if (m_current_event_id
) {
2087 Log
*log
= GetLog(LLDBLog::Events
);
2088 if (log
&& log
->GetVerbose()) {
2089 StreamString log_stream
;
2090 log_stream
.AsRawOstream()
2091 << static_cast<void *>(this) << " Debugger(" << GetID()
2092 << ")::HandleProgressEvent( m_current_event_id = "
2093 << *m_current_event_id
<< ", data = { ";
2094 data
->Dump(&log_stream
);
2095 log_stream
<< " } )";
2096 log
->PutString(log_stream
.GetString());
2098 if (id
!= *m_current_event_id
)
2100 if (data
->GetCompleted() == data
->GetTotal())
2101 m_current_event_id
.reset();
2103 m_current_event_id
= id
;
2106 // Decide whether we actually are going to show the progress. This decision
2107 // can change between iterations so check it inside the loop.
2108 if (!GetShowProgress())
2111 // Determine whether the current output file is an interactive terminal with
2112 // color support. We assume that if we support ANSI escape codes we support
2113 // vt100 escape codes.
2114 File
&file
= GetOutputFile();
2115 if (!file
.GetIsInteractive() || !file
.GetIsTerminalWithColors())
2118 StreamSP output
= GetAsyncOutputStream();
2120 // Print over previous line, if any.
2121 output
->Printf("\r");
2123 if (data
->GetCompleted() == data
->GetTotal()) {
2124 // Clear the current line.
2125 output
->Printf("\x1B[2K");
2130 // Trim the progress message if it exceeds the window's width and print it.
2131 std::string message
= data
->GetMessage();
2132 if (data
->IsFinite())
2133 message
= llvm::formatv("[{0}/{1}] {2}", data
->GetCompleted(),
2134 data
->GetTotal(), message
)
2137 // Trim the progress message if it exceeds the window's width and print it.
2138 const uint32_t term_width
= GetTerminalWidth();
2139 const uint32_t ellipsis
= 3;
2140 if (message
.size() + ellipsis
>= term_width
)
2141 message
.resize(term_width
- ellipsis
);
2143 const bool use_color
= GetUseColor();
2144 llvm::StringRef ansi_prefix
= GetShowProgressAnsiPrefix();
2145 if (!ansi_prefix
.empty())
2147 "%s", ansi::FormatAnsiTerminalCodes(ansi_prefix
, use_color
).c_str());
2149 output
->Printf("%s...", message
.c_str());
2151 llvm::StringRef ansi_suffix
= GetShowProgressAnsiSuffix();
2152 if (!ansi_suffix
.empty())
2154 "%s", ansi::FormatAnsiTerminalCodes(ansi_suffix
, use_color
).c_str());
2156 // Clear until the end of the line.
2157 output
->Printf("\x1B[K\r");
2159 // Flush the output.
2163 void Debugger::HandleDiagnosticEvent(const lldb::EventSP
&event_sp
) {
2164 auto *data
= DiagnosticEventData::GetEventDataFromEvent(event_sp
.get());
2168 StreamSP stream
= GetAsyncErrorStream();
2169 data
->Dump(stream
.get());
2172 bool Debugger::HasIOHandlerThread() const {
2173 return m_io_handler_thread
.IsJoinable();
2176 HostThread
Debugger::SetIOHandlerThread(HostThread
&new_thread
) {
2177 HostThread old_host
= m_io_handler_thread
;
2178 m_io_handler_thread
= new_thread
;
2182 bool Debugger::StartIOHandlerThread() {
2183 if (!m_io_handler_thread
.IsJoinable()) {
2184 llvm::Expected
<HostThread
> io_handler_thread
= ThreadLauncher::LaunchThread(
2185 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2186 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2187 if (io_handler_thread
) {
2188 m_io_handler_thread
= *io_handler_thread
;
2190 LLDB_LOG_ERROR(GetLog(LLDBLog::Host
), io_handler_thread
.takeError(),
2191 "failed to launch host thread: {0}");
2194 return m_io_handler_thread
.IsJoinable();
2197 void Debugger::StopIOHandlerThread() {
2198 if (m_io_handler_thread
.IsJoinable()) {
2199 GetInputFile().Close();
2200 m_io_handler_thread
.Join(nullptr);
2204 void Debugger::JoinIOHandlerThread() {
2205 if (HasIOHandlerThread()) {
2206 thread_result_t result
;
2207 m_io_handler_thread
.Join(&result
);
2208 m_io_handler_thread
= LLDB_INVALID_HOST_THREAD
;
2212 bool Debugger::IsIOHandlerThreadCurrentThread() const {
2213 if (!HasIOHandlerThread())
2215 return m_io_handler_thread
.EqualsThread(Host::GetCurrentThread());
2218 Target
&Debugger::GetSelectedOrDummyTarget(bool prefer_dummy
) {
2219 if (!prefer_dummy
) {
2220 if (TargetSP target
= m_target_list
.GetSelectedTarget())
2223 return GetDummyTarget();
2226 Status
Debugger::RunREPL(LanguageType language
, const char *repl_options
) {
2228 FileSpec repl_executable
;
2230 if (language
== eLanguageTypeUnknown
)
2231 language
= GetREPLLanguage();
2233 if (language
== eLanguageTypeUnknown
) {
2234 LanguageSet repl_languages
= Language::GetLanguagesSupportingREPLs();
2236 if (auto single_lang
= repl_languages
.GetSingularLanguage()) {
2237 language
= *single_lang
;
2238 } else if (repl_languages
.Empty()) {
2239 err
= Status::FromErrorString(
2240 "LLDB isn't configured with REPL support for any languages.");
2243 err
= Status::FromErrorString(
2244 "Multiple possible REPL languages. Please specify a language.");
2249 Target
*const target
=
2250 nullptr; // passing in an empty target means the REPL must create one
2252 REPLSP
repl_sp(REPL::Create(err
, language
, this, target
, repl_options
));
2254 if (!err
.Success()) {
2259 err
= Status::FromErrorStringWithFormat(
2260 "couldn't find a REPL for %s",
2261 Language::GetNameForLanguageType(language
));
2265 repl_sp
->SetCompilerOptions(repl_options
);
2271 llvm::ThreadPoolInterface
&Debugger::GetThreadPool() {
2272 assert(g_thread_pool
&&
2273 "Debugger::GetThreadPool called before Debugger::Initialize");
2274 return *g_thread_pool
;