LLDB mainline
Debugger.cpp
Go to the documentation of this file.
1//===-- Debugger.cpp ------------------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
10
15#include "lldb/Core/Mangled.h"
19#include "lldb/Core/Progress.h"
22#include "lldb/Core/Telemetry.h"
25#include "lldb/Host/Config.h"
26#include "lldb/Host/File.h"
28#include "lldb/Host/HostInfo.h"
30#include "lldb/Host/Terminal.h"
32#include "lldb/Host/XML.h"
44#include "lldb/Symbol/Symbol.h"
47#include "lldb/Target/Process.h"
49#include "lldb/Target/Target.h"
51#include "lldb/Target/Thread.h"
54#include "lldb/Utility/Event.h"
57#include "lldb/Utility/Log.h"
58#include "lldb/Utility/State.h"
59#include "lldb/Utility/Stream.h"
63
64#if defined(_WIN32)
67#endif
68
69#include "llvm/ADT/STLExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/ADT/iterator.h"
72#include "llvm/Config/llvm-config.h"
73#include "llvm/Support/DynamicLibrary.h"
74#include "llvm/Support/FileSystem.h"
75#include "llvm/Support/FormatAdapters.h"
76#include "llvm/Support/Process.h"
77#include "llvm/Support/ThreadPool.h"
78#include "llvm/Support/Threading.h"
79#include "llvm/Support/raw_ostream.h"
80
81#include <chrono>
82#include <cstdio>
83#include <cstdlib>
84#include <cstring>
85#include <list>
86#include <memory>
87#include <mutex>
88#include <optional>
89#include <set>
90#include <string>
91#include <system_error>
92
93// Includes for pipe()
94#if defined(_WIN32)
95#include <fcntl.h>
96#include <io.h>
97#else
98#include <unistd.h>
99#endif
100
101namespace lldb_private {
102class Address;
103}
104
105using namespace lldb;
106using namespace lldb_private;
107
109static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
110
111static std::mutex &GetDebuggerListMutex() {
112 static std::mutex g_mutex;
113 return g_mutex;
114}
115
117static llvm::DefaultThreadPool *g_thread_pool = nullptr;
118
120 {
122 "never",
123 "Never show disassembly when displaying a stop context.",
124 },
125 {
127 "no-debuginfo",
128 "Show disassembly when there is no debug information.",
129 },
130 {
132 "no-source",
133 "Show disassembly when there is no source information, or the source "
134 "file "
135 "is missing when displaying a stop context.",
136 },
137 {
139 "always",
140 "Always show disassembly when displaying a stop context.",
141 },
142};
143
145 {
147 "none",
148 "Disable scripting languages.",
149 },
150 {
152 "python",
153 "Select python as the default scripting language.",
154 },
155 {
157 "default",
158 "Select the lldb default as the default scripting language.",
159 },
160};
161
164 "Use no verbosity when running dwim-print."},
165 {eDWIMPrintVerbosityExpression, "expression",
166 "Use partial verbosity when running dwim-print - display a message when "
167 "`expression` evaluation is used."},
169 "Use full verbosity when running dwim-print."},
170};
171
173 {
175 "ansi-or-caret",
176 "Highlight the stop column with ANSI terminal codes when color/ANSI "
177 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
178 "as if \"caret-only\" mode was selected.",
179 },
180 {
182 "ansi",
183 "Highlight the stop column with ANSI terminal codes when running LLDB "
184 "with color/ANSI enabled.",
185 },
186 {
188 "caret",
189 "Highlight the stop column with a caret character (^) underneath the "
190 "stop column. This method introduces a new line in source listings "
191 "that display thread stop locations.",
192 },
193 {
195 "none",
196 "Do not highlight the stop column.",
197 },
198};
199
201 {
203 "false",
204 "Do not show any autosuggestion.",
205 },
206 {
208 "true",
209 "Show a suggestion sourced from previously entered commands.",
210 },
211 {
213 "tab-mode",
214 "Show the prefix that tab completion would insert for the current "
215 "line.",
216 },
217};
218
219#define LLDB_PROPERTIES_debugger
220#include "CoreProperties.inc"
221
222enum {
223#define LLDB_PROPERTIES_debugger
224#include "CorePropertiesEnum.inc"
225};
226
227#ifndef NDEBUG
228#define LLDB_PROPERTIES_testing
229#include "CoreProperties.inc"
230
231enum {
232#define LLDB_PROPERTIES_testing
233#include "CorePropertiesEnum.inc"
234};
235#endif
236
238 static const FileSpecList sSafePaths = [] {
239 // FIXME: in c++20 this could be a std::array (with CTAD deduced size)
240 // and we could statically assert that all members are non-empty.
241 const llvm::SmallVector<llvm::StringRef> kVendorSafePaths = {
242#include "SafeAutoloadPaths.inc"
243 };
244 FileSpecList fspecs;
245 for (auto path : kVendorSafePaths) {
246 assert(!path.empty());
247 LLDB_LOG(GetLog(SystemLog::System), "Safe auto-load path configured: {0}",
248 path);
249 fspecs.EmplaceBack(path);
250 }
251
252 return fspecs;
253 }();
254
255 return sSafePaths;
256}
257
258#ifndef NDEBUG
260 m_collection_sp = std::make_shared<OptionValueProperties>("testing");
261 m_collection_sp->Initialize(g_testing_properties_def);
262}
263
265 const uint32_t idx = ePropertyInjectVarLocListError;
267 idx, g_testing_properties[idx].default_uint_value != 0);
268}
269
271 static TestingProperties g_testing_properties;
272 return g_testing_properties;
273}
274
276 const uint32_t idx = ePropertySafeAutoloadPaths;
277 OptionValueFileSpecList *option_value =
278 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
279 assert(option_value);
280 option_value->SetCurrentValue(std::move(paths));
281}
282
284 const uint32_t idx = ePropertySafeAutoloadPaths;
285 OptionValueFileSpecList *option_value =
286 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
287 assert(option_value);
288 option_value->AppendCurrentValue(path);
289}
290
292 const uint32_t idx = ePropertySafeAutoloadPaths;
294}
295#endif
296
298
301 llvm::StringRef property_path,
302 llvm::StringRef value) {
303 bool is_load_script =
304 (property_path == "target.load-script-from-symbol-file");
305 // These properties might change how we visualize data.
306 bool invalidate_data_vis = (property_path == "escape-non-printables");
307 invalidate_data_vis |=
308 (property_path == "target.max-zero-padding-in-float-format");
309 if (invalidate_data_vis) {
311 }
312
313 TargetSP target_sp;
315 if (is_load_script && exe_ctx && exe_ctx->GetTargetSP()) {
316 target_sp = exe_ctx->GetTargetSP();
317 load_script_old_value =
318 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
319 }
320 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
321 if (error.Success()) {
322 // FIXME it would be nice to have "on-change" callbacks for properties
323 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
324 llvm::StringRef new_prompt = GetPrompt();
326 new_prompt, GetUseColor());
327 if (str.length())
328 new_prompt = str;
330 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
331 auto prompt_change_event_sp = std::make_shared<Event>(
333 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
334 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
335 // use-color changed. set use-color, this also pings the prompt so it can
336 // reset the ansi terminal codes.
338 } else if (property_path ==
339 g_debugger_properties[ePropertyPromptAnsiPrefix].name ||
340 property_path ==
341 g_debugger_properties[ePropertyPromptAnsiSuffix].name) {
342 // Prompt color changed. set use-color, this also pings the prompt so it
343 // can reset the ansi terminal codes.
345 } else if (property_path ==
346 g_debugger_properties[ePropertyShowStatusline].name) {
347 // Statusline setting changed. If we have a statusline instance, update it
348 // now. Otherwise it will get created in the default event handler.
349 std::lock_guard<std::mutex> guard(m_statusline_mutex);
350 if (StatuslineSupported()) {
351 m_statusline.emplace(*this);
352 m_statusline->Enable(
353 GetSelectedExecutionContextRef(/*adopt_dummy_target=*/true));
354 } else {
355 m_statusline.reset();
356 }
357 } else if (property_path ==
358 g_debugger_properties[ePropertyStatuslineFormat].name ||
359 property_path ==
360 g_debugger_properties[ePropertySeparator].name) {
361 // Statusline format changed. Redraw the statusline.
362 RedrawStatusline(std::nullopt);
363 } else if (property_path ==
364 g_debugger_properties[ePropertyUseSourceCache].name) {
365 // use-source-cache changed. Wipe out the cache contents if it was
366 // disabled.
367 if (!GetUseSourceCache()) {
368 m_source_file_cache.Clear();
369 }
370 } else if (is_load_script && target_sp &&
371 load_script_old_value == eLoadScriptFromSymFileWarn) {
372 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
374 std::list<Status> errors;
375 if (!target_sp->LoadScriptingResources(errors)) {
377 for (auto &error : errors)
378 s->Printf("%s\n", error.AsCString());
379 }
380 }
381 }
382 }
383 return error;
384}
385
387 constexpr uint32_t idx = ePropertyAutoConfirm;
389 idx, g_debugger_properties[idx].default_uint_value != 0);
390}
391
393 constexpr uint32_t idx = ePropertyDisassemblyFormat;
395}
396
398 constexpr uint32_t idx = ePropertyFrameFormat;
400}
401
403 constexpr uint32_t idx = ePropertyFrameFormatUnique;
405}
406
408 constexpr uint32_t idx = ePropertyStopDisassemblyMaxSize;
410 idx, g_debugger_properties[idx].default_uint_value);
411}
412
414 constexpr uint32_t idx = ePropertyNotiftVoid;
416 idx, g_debugger_properties[idx].default_uint_value != 0);
417}
418
419llvm::StringRef Debugger::GetPrompt() const {
420 constexpr uint32_t idx = ePropertyPrompt;
422 idx, g_debugger_properties[idx].default_cstr_value);
423}
424
425llvm::StringRef Debugger::GetPromptAnsiPrefix() const {
426 const uint32_t idx = ePropertyPromptAnsiPrefix;
428 idx, g_debugger_properties[idx].default_cstr_value);
429}
430
431llvm::StringRef Debugger::GetPromptAnsiSuffix() const {
432 const uint32_t idx = ePropertyPromptAnsiSuffix;
434 idx, g_debugger_properties[idx].default_cstr_value);
435}
436
437void Debugger::SetPrompt(llvm::StringRef p) {
438 constexpr uint32_t idx = ePropertyPrompt;
439 SetPropertyAtIndex(idx, p);
440 llvm::StringRef new_prompt = GetPrompt();
441 std::string str =
443 if (str.length())
444 new_prompt = str;
446}
447
449 constexpr uint32_t idx = ePropertyThreadFormat;
451}
452
454 constexpr uint32_t idx = ePropertyThreadStopFormat;
456}
457
459 const uint32_t idx = ePropertyScriptLanguage;
461 idx, static_cast<lldb::ScriptLanguage>(
462 g_debugger_properties[idx].default_uint_value));
463}
464
466 const uint32_t idx = ePropertyScriptLanguage;
467 return SetPropertyAtIndex(idx, script_lang);
468}
469
471 const uint32_t idx = ePropertyREPLLanguage;
473}
474
476 const uint32_t idx = ePropertyREPLLanguage;
477 return SetPropertyAtIndex(idx, repl_lang);
478}
479
481 const uint32_t idx = ePropertyTerminalWidth;
483 idx, g_debugger_properties[idx].default_uint_value);
484}
485
486bool Debugger::SetTerminalWidth(uint64_t term_width) {
487 return SetTerminalDimensions(term_width, GetTerminalHeight());
488}
489
491 const uint32_t idx = ePropertyTerminalHeight;
493 idx, g_debugger_properties[idx].default_uint_value);
494}
495
496bool Debugger::SetTerminalHeight(uint64_t term_height) {
497 return SetTerminalDimensions(GetTerminalWidth(), term_height);
498}
499
500bool Debugger::SetTerminalDimensions(uint64_t term_width,
501 uint64_t term_height) {
502 // Set both properties before notifying, so observers never recompute from a
503 // mix of fresh and stale dimensions.
504 const bool width_success =
505 SetPropertyAtIndex(ePropertyTerminalWidth, term_width);
506 const bool height_success =
507 SetPropertyAtIndex(ePropertyTerminalHeight, term_height);
508
509 if (auto handler_sp = m_io_handler_stack.Top())
510 handler_sp->TerminalSizeChanged();
511
512 {
513 std::lock_guard<std::mutex> guard(m_statusline_mutex);
514 if (m_statusline)
515 m_statusline->TerminalSizeChanged();
516 }
517
518 return width_success && height_success;
519}
520
522 const uint32_t idx = ePropertyUseExternalEditor;
524 idx, g_debugger_properties[idx].default_uint_value != 0);
525}
526
528 const uint32_t idx = ePropertyUseExternalEditor;
529 return SetPropertyAtIndex(idx, b);
530}
531
532llvm::StringRef Debugger::GetExternalEditor() const {
533 const uint32_t idx = ePropertyExternalEditor;
535 idx, g_debugger_properties[idx].default_cstr_value);
536}
537
538bool Debugger::SetExternalEditor(llvm::StringRef editor) {
539 const uint32_t idx = ePropertyExternalEditor;
540 return SetPropertyAtIndex(idx, editor);
541}
542
544 const uint32_t idx = ePropertyUseColor;
546 idx, g_debugger_properties[idx].default_uint_value != 0);
547}
548
550 const uint32_t idx = ePropertyUseColor;
551 bool ret = SetPropertyAtIndex(idx, b);
552
555 return ret;
556}
557
559 const uint32_t idx = ePropertyShowProgress;
561 idx, g_debugger_properties[idx].default_uint_value != 0);
562}
563
564bool Debugger::SetShowProgress(bool show_progress) {
565 const uint32_t idx = ePropertyShowProgress;
566 return SetPropertyAtIndex(idx, show_progress);
567}
568
569llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const {
570 const uint32_t idx = ePropertyShowProgressAnsiPrefix;
572 idx, g_debugger_properties[idx].default_cstr_value);
573}
574
575llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const {
576 const uint32_t idx = ePropertyShowProgressAnsiSuffix;
578 idx, g_debugger_properties[idx].default_cstr_value);
579}
580
581llvm::StringRef Debugger::GetLabelAnsiPrefix() const {
582 const uint32_t idx = ePropertyLabelAnsiPrefix;
584 idx, g_debugger_properties[idx].default_cstr_value);
585}
586
587llvm::StringRef Debugger::GetLabelAnsiSuffix() const {
588 const uint32_t idx = ePropertyLabelAnsiSuffix;
590 idx, g_debugger_properties[idx].default_cstr_value);
591}
592
593llvm::StringRef Debugger::GetTitleAnsiPrefix() const {
594 const uint32_t idx = ePropertyTitleAnsiPrefix;
596 idx, g_debugger_properties[idx].default_cstr_value);
597}
598
599llvm::StringRef Debugger::GetTitleAnsiSuffix() const {
600 const uint32_t idx = ePropertyTitleAnsiSuffix;
602 idx, g_debugger_properties[idx].default_cstr_value);
603}
604
605llvm::StringRef Debugger::GetDividerAnsiPrefix() const {
606 const uint32_t idx = ePropertyDividerAnsiPrefix;
608 idx, g_debugger_properties[idx].default_cstr_value);
609}
610
611llvm::StringRef Debugger::GetDividerAnsiSuffix() const {
612 const uint32_t idx = ePropertyDividerAnsiSuffix;
614 idx, g_debugger_properties[idx].default_cstr_value);
615}
616
618 const uint32_t idx = ePropertyShowStatusline;
620 idx, g_debugger_properties[idx].default_uint_value != 0);
621}
622
624 constexpr uint32_t idx = ePropertyStatuslineFormat;
626}
627
629 constexpr uint32_t idx = ePropertyStatuslineFormat;
630 bool ret = SetPropertyAtIndex(idx, format);
631 RedrawStatusline(std::nullopt);
632 return ret;
633}
634
635llvm::StringRef Debugger::GetSeparator() const {
636 constexpr uint32_t idx = ePropertySeparator;
638 idx, g_debugger_properties[idx].default_cstr_value);
639}
640
641llvm::StringRef Debugger::GetDisabledAnsiPrefix() const {
642 const uint32_t idx = ePropertyShowDisabledAnsiPrefix;
644 idx, g_debugger_properties[idx].default_cstr_value);
645}
646
647llvm::StringRef Debugger::GetDisabledAnsiSuffix() const {
648 const uint32_t idx = ePropertyShowDisabledAnsiSuffix;
650 idx, g_debugger_properties[idx].default_cstr_value);
651}
652
653bool Debugger::SetSeparator(llvm::StringRef s) {
654 constexpr uint32_t idx = ePropertySeparator;
655 bool ret = SetPropertyAtIndex(idx, s);
656 RedrawStatusline(std::nullopt);
657 return ret;
658}
659
661 const uint32_t idx = ePropertyShowAutosuggestion;
663 idx, static_cast<AutosuggestionMode>(
664 g_debugger_properties[idx].default_uint_value));
665}
666
668 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix;
670 idx, g_debugger_properties[idx].default_cstr_value);
671}
672
674 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix;
676 idx, g_debugger_properties[idx].default_cstr_value);
677}
678
679llvm::StringRef Debugger::GetRegexMatchAnsiPrefix() const {
680 const uint32_t idx = ePropertyShowRegexMatchAnsiPrefix;
682 idx, g_debugger_properties[idx].default_cstr_value);
683}
684
685llvm::StringRef Debugger::GetRegexMatchAnsiSuffix() const {
686 const uint32_t idx = ePropertyShowRegexMatchAnsiSuffix;
688 idx, g_debugger_properties[idx].default_cstr_value);
689}
690
692 const uint32_t idx = ePropertyShowDontUsePoHint;
694 idx, g_debugger_properties[idx].default_uint_value != 0);
695}
696
698 const uint32_t idx = ePropertyUseSourceCache;
700 idx, g_debugger_properties[idx].default_uint_value != 0);
701}
702
704 const uint32_t idx = ePropertyUseSourceCache;
705 bool ret = SetPropertyAtIndex(idx, b);
706 if (!ret) {
707 m_source_file_cache.Clear();
708 }
709 return ret;
710}
711
713 const uint32_t idx = ePropertyMarkHiddenFrames;
715 idx, g_debugger_properties[idx].default_uint_value != 0);
716}
717
719 const uint32_t idx = ePropertyHighlightSource;
721 idx, g_debugger_properties[idx].default_uint_value != 0);
722}
723
725 const uint32_t idx = ePropertyStopShowColumn;
727 idx, static_cast<lldb::StopShowColumn>(
728 g_debugger_properties[idx].default_uint_value));
729}
730
732 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
734 idx, g_debugger_properties[idx].default_cstr_value);
735}
736
738 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
740 idx, g_debugger_properties[idx].default_cstr_value);
741}
742
744 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
746 idx, g_debugger_properties[idx].default_cstr_value);
747}
748
750 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
752 idx, g_debugger_properties[idx].default_cstr_value);
753}
754
755uint64_t Debugger::GetStopSourceLineCount(bool before) const {
756 const uint32_t idx =
757 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
759 idx, g_debugger_properties[idx].default_uint_value);
760}
761
763 const uint32_t idx = ePropertyStopDisassemblyDisplay;
765 idx, static_cast<lldb::StopDisassemblyType>(
766 g_debugger_properties[idx].default_uint_value));
767}
768
770 const uint32_t idx = ePropertyStopDisassemblyCount;
772 idx, g_debugger_properties[idx].default_uint_value);
773}
774
776 const uint32_t idx = ePropertyAutoOneLineSummaries;
778 idx, g_debugger_properties[idx].default_uint_value != 0);
779}
780
782 const uint32_t idx = ePropertyEscapeNonPrintables;
784 idx, g_debugger_properties[idx].default_uint_value != 0);
785}
786
788 const uint32_t idx = ePropertyAutoIndent;
790 idx, g_debugger_properties[idx].default_uint_value != 0);
791}
792
794 const uint32_t idx = ePropertyAutoIndent;
795 return SetPropertyAtIndex(idx, b);
796}
797
799 const uint32_t idx = ePropertyPrintDecls;
801 idx, g_debugger_properties[idx].default_uint_value != 0);
802}
803
805 const uint32_t idx = ePropertyPrintDecls;
806 return SetPropertyAtIndex(idx, b);
807}
808
809uint64_t Debugger::GetTabSize() const {
810 const uint32_t idx = ePropertyTabSize;
812 idx, g_debugger_properties[idx].default_uint_value);
813}
814
815bool Debugger::SetTabSize(uint64_t tab_size) {
816 const uint32_t idx = ePropertyTabSize;
817 return SetPropertyAtIndex(idx, tab_size);
818}
819
821 const uint32_t idx = ePropertyDWIMPrintVerbosity;
823 idx, static_cast<lldb::DWIMPrintVerbosity>(
824 g_debugger_properties[idx].default_uint_value != 0));
825}
826
828 const uint32_t idx = ePropertyShowInlineDiagnostics;
830 idx, g_debugger_properties[idx].default_uint_value);
831}
832
834 const uint32_t idx = ePropertyShowInlineDiagnostics;
835 return SetPropertyAtIndex(idx, b);
836}
837
838#pragma mark Debugger
839
840// const DebuggerPropertiesSP &
841// Debugger::GetSettings() const
842//{
843// return m_properties_sp;
844//}
845//
846
848 assert(g_debugger_list_ptr == nullptr &&
849 "Debugger::Initialize called more than once!");
850 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
852 g_thread_pool = new llvm::DefaultThreadPool(llvm::optimal_concurrency());
853 g_load_plugin_callback = load_plugin_callback;
854}
855
857 assert(g_debugger_list_ptr &&
858 "Debugger::Terminate called without a matching Debugger::Initialize!");
859
860 {
861 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
863 for (const auto &debugger : *g_debugger_list_ptr)
864 debugger->HandleDestroyCallback();
865 }
866
867 if (g_thread_pool) {
868 // The destructor will wait for all the threads to complete.
869 delete g_thread_pool;
870 }
871
872 {
873 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
875 for (const DebuggerSP &debugger : *g_debugger_list_ptr)
876 debugger->Clear();
877 g_debugger_list_ptr->clear();
878
879 delete g_debugger_list_ptr;
880 g_debugger_list_ptr = nullptr;
881 }
882 }
883}
884
886
888
891 llvm::sys::DynamicLibrary dynlib =
892 g_load_plugin_callback(shared_from_this(), spec, error);
893 if (dynlib.isValid()) {
894 m_loaded_plugins.push_back(dynlib);
895 return true;
896 }
897 } else {
898 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
899 // if the public API layer isn't available (code is linking against all of
900 // the internal LLDB static libraries), then we can't load plugins
901 error = Status::FromErrorString("Public API layer is not available");
902 }
903 return false;
904}
905
907LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
908 llvm::StringRef path) {
910
911 static constexpr llvm::StringLiteral g_dylibext(".dylib");
912 static constexpr llvm::StringLiteral g_solibext(".so");
913
914 if (!baton)
916
917 Debugger *debugger = (Debugger *)baton;
918
919 namespace fs = llvm::sys::fs;
920 // If we have a regular file, a symbolic link or unknown file type, try and
921 // process the file. We must handle unknown as sometimes the directory
922 // enumeration might be enumerating a file system that doesn't have correct
923 // file type information.
924 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
925 ft == fs::file_type::type_unknown) {
926 FileSpec plugin_file_spec(path);
927 FileSystem::Instance().Resolve(plugin_file_spec);
928
929 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
930 plugin_file_spec.GetFileNameExtension() != g_solibext) {
932 }
933
934 Status plugin_load_error;
935 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
936
938 } else if (ft == fs::file_type::directory_file ||
939 ft == fs::file_type::symlink_file ||
940 ft == fs::file_type::type_unknown) {
941 // Try and recurse into anything that a directory or symbolic link. We must
942 // also do this for unknown as sometimes the directory enumeration might be
943 // enumerating a file system that doesn't have correct file type
944 // information.
946 }
947
949}
950
952 const bool find_directories = true;
953 const bool find_files = true;
954 const bool find_other = true;
955 char dir_path[PATH_MAX];
956 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
957 if (FileSystem::Instance().Exists(dir_spec) &&
958 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
959 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
960 find_files, find_other,
961 LoadPluginCallback, this);
962 }
963 }
964
965 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
966 if (FileSystem::Instance().Exists(dir_spec) &&
967 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
968 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
969 find_files, find_other,
970 LoadPluginCallback, this);
971 }
972 }
973
975}
976
978 void *baton) {
981 helper([](lldb_private::telemetry::DebuggerInfo *entry) {
983 });
984 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
985 helper.SetDebugger(debugger_sp.get());
986 {
987 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
989 g_debugger_list_ptr->push_back(debugger_sp);
990 }
991 debugger_sp->InstanceInitialize();
992 return debugger_sp;
993}
994
1000
1002 const lldb::user_id_t user_id = GetID();
1003 // Invoke and remove all the callbacks in an FIFO order. Callbacks which are
1004 // added during this loop will be appended, invoked and then removed last.
1005 // Callbacks which are removed during this loop will not be invoked.
1006 while (true) {
1007 DestroyCallbackInfo callback_info;
1008 {
1009 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1010 if (m_destroy_callbacks.empty())
1011 break;
1012 // Pop the first item in the list
1013 callback_info = m_destroy_callbacks.front();
1015 }
1016 // Call the destroy callback with user id and baton
1017 callback_info.callback(user_id, callback_info.baton);
1018 }
1019}
1020
1021void Debugger::Destroy(DebuggerSP &debugger_sp) {
1022 if (!debugger_sp)
1023 return;
1024
1025 debugger_sp->HandleDestroyCallback();
1026 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
1027
1028 if (cmd_interpreter.GetSaveSessionOnQuit()) {
1029 CommandReturnObject result(debugger_sp->GetUseColor());
1030 cmd_interpreter.SaveTranscript(result);
1031 if (result.Succeeded())
1032 (*debugger_sp->GetAsyncOutputStream())
1033 << result.GetOutputString() << '\n';
1034 else
1035 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorString() << '\n';
1036 }
1037
1038 debugger_sp->Clear();
1039
1040 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1041 if (g_debugger_list_ptr) {
1042 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1043 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1044 if ((*pos).get() == debugger_sp.get()) {
1045 g_debugger_list_ptr->erase(pos);
1046 return;
1047 }
1048 }
1049 }
1050}
1051
1053Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) {
1054 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1056 return nullptr;
1057
1058 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1059 if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name)
1060 return debugger_sp;
1061 }
1062
1063 return nullptr;
1064}
1065
1067 static constexpr llvm::StringLiteral class_name("lldb.debugger");
1068 return class_name;
1069}
1070
1072 : UserID(g_unique_id++),
1073 Properties(std::make_shared<OptionValueProperties>()),
1074 m_input_file_sp(std::make_shared<NativeFile>(
1075 stdin, File::eOpenOptionReadOnly, NativeFile::Unowned)),
1076 m_output_stream_sp(std::make_shared<LockableStreamFile>(
1077 stdout, NativeFile::Unowned, m_output_mutex)),
1078 m_error_stream_sp(std::make_shared<LockableStreamFile>(
1079 stderr, NativeFile::Unowned, m_output_mutex)),
1080 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
1082 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
1085 std::make_unique<CommandInterpreter>(*this, false)),
1087 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()),
1089 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
1093 // Initialize the debugger properties as early as possible as other parts of
1094 // LLDB will start querying them during construction.
1095 m_collection_sp->Initialize(g_debugger_properties_def);
1096 m_collection_sp->AppendProperty(
1097 "target", "Settings specify to debugging targets.", true,
1099 m_collection_sp->AppendProperty(
1100 "platform", "Platform settings.", true,
1102 m_collection_sp->AppendProperty(
1103 "symbols", "Symbol lookup and cache settings.", true,
1105 m_collection_sp->AppendProperty(
1106 LanguageProperties::GetSettingName(), "Language settings.", true,
1108 m_collection_sp->AppendProperty(
1109 "diagnostics", "Diagnostics settings.", true,
1112 m_collection_sp->AppendProperty(
1113 "interpreter",
1114 "Settings specify to the debugger's command interpreter.", true,
1115 m_command_interpreter_up->GetValueProperties());
1116 }
1117#ifndef NDEBUG
1118 m_collection_sp->AppendProperty(
1119 "testing", "Testing-only settings.", /*is_global=*/true,
1121#endif
1122
1123 if (log_callback)
1125 std::make_shared<CallbackLogHandler>(log_callback, baton);
1126 m_command_interpreter_up->Initialize();
1127 // Always add our default platform to the platform list
1128 PlatformSP default_platform_sp(Platform::GetHostPlatform());
1129 assert(default_platform_sp);
1130 m_platform_list.Append(default_platform_sp, true);
1131
1132 // Create the dummy target.
1133 {
1135 if (!arch.IsValid())
1136 arch = HostInfo::GetArchitecture();
1137 assert(arch.IsValid() && "No valid default or host archspec");
1138 const bool is_dummy_target = true;
1139 m_dummy_target_sp.reset(
1140 new Target(*this, arch, default_platform_sp, is_dummy_target));
1141 }
1142 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
1143
1144 OptionValueUInt64 *term_width =
1145 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1146 ePropertyTerminalWidth);
1147 term_width->SetMinimumValue(10);
1148
1149 OptionValueUInt64 *term_height =
1150 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1151 ePropertyTerminalHeight);
1152 term_height->SetMinimumValue(10);
1153
1154 // Turn off use-color if this is a dumb terminal.
1155 const char *term = getenv("TERM");
1156 auto disable_color = [&]() {
1157 SetUseColor(false);
1158 SetSeparator("| ");
1159 };
1160
1161 if (term && !strcmp(term, "dumb"))
1162 disable_color();
1163 // Turn off use-color if we don't write to a terminal with color support.
1164 if (!GetOutputFileSP()->GetIsTerminalWithColors())
1165 disable_color();
1166
1167#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
1168 // Enabling use of ANSI color codes because LLDB is using them to highlight
1169 // text.
1170 llvm::sys::Process::UseANSIEscapeCodes(true);
1171#endif
1172}
1173
1175
1177 // Make sure we call this function only once. With the C++ global destructor
1178 // chain having a list of debuggers and with code that can be running on
1179 // other threads, we need to ensure this doesn't happen multiple times.
1180 //
1181 // The following functions call Debugger::Clear():
1182 // Debugger::~Debugger();
1183 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
1184 // static void Debugger::Terminate();
1185 llvm::call_once(m_clear_once, [this]() {
1188 assert(this == info->debugger);
1189 (void)this;
1190 info->is_exit_entry = true;
1191 },
1192 this);
1196 m_listener_sp->Clear();
1197 for (TargetSP target_sp : m_target_list.Targets()) {
1198 if (target_sp) {
1199 if (ProcessSP process_sp = target_sp->GetProcessSP())
1200 process_sp->Finalize(false /* not destructing */);
1201 target_sp->Destroy();
1202 }
1203 }
1204 m_broadcaster_manager_sp->Clear();
1205
1206 // Close the input file _before_ we close the input read communications
1207 // class as it does NOT own the input file, our m_input_file does.
1208 m_terminal_state.Clear();
1209 GetInputFile().Close();
1210
1211 m_command_interpreter_up->Clear();
1212 });
1213}
1214
1216 return !m_command_interpreter_up->GetSynchronous();
1217}
1218
1219void Debugger::SetAsyncExecution(bool async_execution) {
1220 m_command_interpreter_up->SetSynchronous(!async_execution);
1221}
1222
1223static inline int OpenPipe(int fds[2], std::size_t size) {
1224#ifdef _WIN32
1225 return _pipe(fds, size, O_BINARY);
1226#else
1227 (void)size;
1228 return pipe(fds);
1229#endif
1230}
1231
1233 Status result;
1234 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
1235 int fds[2] = {-1, -1};
1236
1237 if (data == nullptr) {
1238 result = Status::FromErrorString("String data is null");
1239 return result;
1240 }
1241
1242 size_t size = strlen(data);
1243 if (size == 0) {
1244 result = Status::FromErrorString("String data is empty");
1245 return result;
1246 }
1247
1248 if (OpenPipe(fds, size) != 0) {
1249 result = Status::FromErrorString(
1250 "can't create pipe file descriptors for LLDB commands");
1251 return result;
1252 }
1253
1254 int r = write(fds[WRITE], data, size);
1255 (void)r;
1256 // Close the write end of the pipe, so that the command interpreter will exit
1257 // when it consumes all the data.
1258 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
1259
1260 // Open the read file descriptor as a FILE * that we can return as an input
1261 // handle.
1262 FILE *commands_file = fdopen(fds[READ], "rb");
1263 if (commands_file == nullptr) {
1265 "fdopen(%i, \"rb\") failed (errno = %i) "
1266 "when trying to open LLDB commands pipe",
1267 fds[READ], errno);
1268 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
1269 return result;
1270 }
1271
1272 SetInputFile((FileSP)std::make_shared<NativeFile>(
1273 commands_file, File::eOpenOptionReadOnly, true));
1274 return result;
1275}
1276
1278 assert(file_sp && file_sp->IsValid());
1279 m_input_file_sp = std::move(file_sp);
1280 // Save away the terminal state if that is relevant, so that we can restore
1281 // it in RestoreInputState.
1283}
1284
1286 assert(file_sp && file_sp->IsValid());
1288 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1289}
1290
1292 assert(file_sp && file_sp->IsValid());
1294 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1295}
1296
1298 {
1299 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1300 if (m_statusline)
1301 m_statusline->Disable();
1302 }
1303 int fd = GetInputFile().GetDescriptor();
1304 if (fd != File::kInvalidDescriptor)
1305 m_terminal_state.Save(fd, true);
1306}
1307
1309 m_terminal_state.Restore();
1310 {
1311 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1312 if (m_statusline)
1313 m_statusline->Enable(
1314 GetSelectedExecutionContext(/*adopt_dummy_target=*/true));
1315 }
1316}
1317
1319 std::optional<ExecutionContextRef> exe_ctx_ref) {
1320 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1321
1322 if (!m_statusline)
1323 return;
1324
1325 m_statusline->Redraw(exe_ctx_ref);
1326}
1327
1329 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1330
1331 if (!m_statusline)
1332 return;
1333
1334 m_statusline->ClearExecutionContext();
1335}
1336
1339 return ExecutionContext(GetSelectedExecutionContextRef(adopt_dummy_target));
1340}
1341
1344 if (TargetSP selected_target_sp = m_target_list.GetSelectedTarget())
1345 return ExecutionContextRef(selected_target_sp.get(),
1346 /*adopt_selected=*/true);
1347
1348 if (adopt_dummy_target)
1350 /*adopt_selected=*/false);
1351
1352 return ExecutionContextRef();
1353}
1354
1356 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1357 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1358 if (reader_sp)
1359 reader_sp->Interrupt();
1360}
1361
1363 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1364 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1365 if (reader_sp)
1366 reader_sp->GotEOF();
1367}
1368
1370 // The bottom input reader should be the main debugger input reader. We do
1371 // not want to close that one here.
1372 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1373 while (m_io_handler_stack.GetSize() > 1) {
1374 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1375 if (reader_sp)
1376 PopIOHandler(reader_sp);
1377 }
1378}
1379
1381 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1382 while (true) {
1383 if (!reader_sp)
1384 break;
1385
1386 reader_sp->Run();
1387 {
1388 std::lock_guard<std::recursive_mutex> guard(
1390
1391 // Remove all input readers that are done from the top of the stack
1392 while (true) {
1393 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1394 if (top_reader_sp && top_reader_sp->GetIsDone())
1395 PopIOHandler(top_reader_sp);
1396 else
1397 break;
1398 }
1399 reader_sp = m_io_handler_stack.Top();
1400 }
1401 }
1403}
1404
1406 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1407
1408 PushIOHandler(reader_sp);
1409 IOHandlerSP top_reader_sp = reader_sp;
1410
1411 while (top_reader_sp) {
1412 top_reader_sp->Run();
1413
1414 // Don't unwind past the starting point.
1415 if (top_reader_sp.get() == reader_sp.get()) {
1416 if (PopIOHandler(reader_sp))
1417 break;
1418 }
1419
1420 // If we pushed new IO handlers, pop them if they're done or restart the
1421 // loop to run them if they're not.
1422 while (true) {
1423 top_reader_sp = m_io_handler_stack.Top();
1424 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1425 PopIOHandler(top_reader_sp);
1426 // Don't unwind past the starting point.
1427 if (top_reader_sp.get() == reader_sp.get())
1428 return;
1429 } else {
1430 break;
1431 }
1432 }
1433 }
1434}
1435
1437 return m_io_handler_stack.IsTop(reader_sp);
1438}
1439
1441 IOHandler::Type second_top_type) {
1442 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1443}
1444
1445void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1446 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1447 if (!printed) {
1448 LockableStreamFileSP stream_sp =
1450 LockedStreamFile locked_stream = stream_sp->Lock();
1451 locked_stream.Write(s, len);
1452 }
1453}
1454
1456 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1457}
1458
1460 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1461}
1462
1464 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1465}
1466
1468 return PopIOHandler(reader_sp);
1469}
1470
1472 bool cancel_top_handler) {
1473 PushIOHandler(reader_sp, cancel_top_handler);
1474}
1475
1478 LockableStreamFileSP &err) {
1479 // Before an IOHandler runs, it must have in/out/err streams. This function
1480 // is called when one ore more of the streams are nullptr. We use the top
1481 // input reader's in/out/err streams, or fall back to the debugger file
1482 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1483
1484 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1485 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1486 // If no STDIN has been set, then set it appropriately
1487 if (!in || !in->IsValid()) {
1488 if (top_reader_sp)
1489 in = top_reader_sp->GetInputFileSP();
1490 else
1491 in = GetInputFileSP();
1492 // If there is nothing, use stdin
1493 if (!in)
1494 in = std::make_shared<NativeFile>(stdin, File::eOpenOptionReadOnly,
1496 }
1497 // If no STDOUT has been set, then set it appropriately
1498 if (!out || !out->GetUnlockedFile().IsValid()) {
1499 if (top_reader_sp)
1500 out = top_reader_sp->GetOutputStreamFileSP();
1501 else
1502 out = GetOutputStreamSP();
1503 // If there is nothing, use stdout
1504 if (!out)
1505 out = std::make_shared<LockableStreamFile>(stdout, NativeFile::Unowned,
1507 }
1508 // If no STDERR has been set, then set it appropriately
1509 if (!err || !err->GetUnlockedFile().IsValid()) {
1510 if (top_reader_sp)
1511 err = top_reader_sp->GetErrorStreamFileSP();
1512 else
1513 err = GetErrorStreamSP();
1514 // If there is nothing, use stderr
1515 if (!err)
1516 err = std::make_shared<LockableStreamFile>(stderr, NativeFile::Unowned,
1518 }
1519}
1520
1522 bool cancel_top_handler) {
1523 if (!reader_sp)
1524 return;
1525
1526 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1527
1528 // Get the current top input reader...
1529 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1530
1531 // Don't push the same IO handler twice...
1532 if (reader_sp == top_reader_sp)
1533 return;
1534
1535 // Push our new input reader
1536 m_io_handler_stack.Push(reader_sp);
1537 reader_sp->Activate();
1538
1539 // Interrupt the top input reader to it will exit its Run() function and let
1540 // this new input reader take over
1541 if (top_reader_sp) {
1542 top_reader_sp->Deactivate();
1543 if (cancel_top_handler)
1544 top_reader_sp->Cancel();
1545 }
1546}
1547
1548bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1549 if (!pop_reader_sp)
1550 return false;
1551
1552 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1553
1554 // The reader on the stop of the stack is done, so let the next read on the
1555 // stack refresh its prompt and if there is one...
1556 if (m_io_handler_stack.IsEmpty())
1557 return false;
1558
1559 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1560
1561 if (pop_reader_sp != reader_sp)
1562 return false;
1563
1564 reader_sp->Deactivate();
1565 reader_sp->Cancel();
1566 m_io_handler_stack.Pop();
1567
1568 reader_sp = m_io_handler_stack.Top();
1569 if (reader_sp)
1570 reader_sp->Activate();
1571
1572 return true;
1573}
1574
1576 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1577 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1578 if (reader_sp)
1579 reader_sp->Refresh();
1580}
1581
1583 return std::make_unique<StreamAsynchronousIO>(*this,
1585}
1586
1588 return std::make_unique<StreamAsynchronousIO>(*this,
1590}
1591
1593 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1595}
1596
1598 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1599 if (m_interrupt_requested > 0)
1601}
1602
1604 // This is the one we should call internally. This will return true either
1605 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1606 // or if we are on the IOHandler thread and there's a CommandInterpreter
1607 // interrupt.
1609 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1610 return m_interrupt_requested != 0;
1611 }
1613}
1614
1616 std::string function_name, const llvm::formatv_object_base &payload)
1617 : m_function_name(std::move(function_name)),
1618 m_interrupt_time(std::chrono::system_clock::now()),
1619 m_thread_id(llvm::get_threadid()) {
1620 llvm::raw_string_ostream desc(m_description);
1621 desc << payload << "\n";
1622}
1623
1625 // For now, just log the description:
1626 Log *log = GetLog(LLDBLog::Host);
1627 LLDB_LOG(log, "Interruption: {0}", report.m_description);
1628}
1629
1631 DebuggerList result;
1632 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1633 if (g_debugger_list_ptr) {
1634 for (auto debugger_sp : *g_debugger_list_ptr) {
1635 if (debugger_sp->InterruptRequested())
1636 result.push_back(debugger_sp);
1637 }
1638 }
1639 return result;
1640}
1641
1643 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1645 return 0;
1646
1647 return g_debugger_list_ptr->size();
1648}
1649
1651 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1653 return nullptr;
1654
1655 if (index < g_debugger_list_ptr->size())
1656 return g_debugger_list_ptr->at(index);
1657
1658 return nullptr;
1659}
1660
1662 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1664 return nullptr;
1665
1666 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1667 if (debugger_sp->GetID() == id)
1668 return debugger_sp;
1669 }
1670
1671 return nullptr;
1672}
1673
1675 const SymbolContext *sc,
1676 const SymbolContext *prev_sc,
1677 const ExecutionContext *exe_ctx,
1678 const Address *addr, Stream &s) {
1679 FormatEntity::Entry format_entry;
1680
1681 if (format == nullptr) {
1682 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) {
1683 format_entry =
1685 format = &format_entry;
1686 }
1687 if (format == nullptr) {
1688 FormatEntity::Parse("${addr}: ", format_entry);
1689 format = &format_entry;
1690 }
1691 }
1692 bool function_changed = false;
1693 bool initial_function = false;
1694 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1695 if (sc && (sc->function || sc->symbol)) {
1696 if (prev_sc->symbol && sc->symbol) {
1697 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1698 prev_sc->symbol->GetType())) {
1699 function_changed = true;
1700 }
1701 } else if (prev_sc->function && sc->function) {
1702 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1703 function_changed = true;
1704 }
1705 }
1706 }
1707 }
1708 // The first context on a list of instructions will have a prev_sc that has
1709 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1710 // would return false. But we do get a prev_sc pointer.
1711 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1712 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1713 initial_function = true;
1714 }
1715 return FormatEntity::Formatter(sc, exe_ctx, addr, function_changed,
1716 initial_function)
1717 .Format(*format, s);
1718}
1719
1720void Debugger::AssertCallback(llvm::StringRef message,
1721 llvm::StringRef backtrace,
1722 llvm::StringRef prompt) {
1723 Debugger::ReportError(llvm::formatv("{0}\n{1}{2}\n{3}", message, backtrace,
1724 GetVersion(), prompt)
1725 .str());
1726}
1727
1729 void *baton) {
1730 // For simplicity's sake, I am not going to deal with how to close down any
1731 // open logging streams, I just redirect everything from here on out to the
1732 // callback.
1734 std::make_shared<CallbackLogHandler>(log_callback, baton);
1735}
1736
1737std::vector<std::string>
1739 std::vector<std::string> copied;
1740 for (auto &entry : m_stream_handlers) {
1741 llvm::StringRef log_path = entry.first();
1742 llvm::StringRef file_name = llvm::sys::path::filename(log_path);
1743 FileSpec destination = dir.CopyByAppendingPathComponent(file_name);
1744 // Best-effort: skip logs that can't be copied rather than aborting.
1745 if (!llvm::sys::fs::copy_file(log_path, destination.GetPath()))
1746 copied.push_back(file_name.str());
1747 }
1748 return copied;
1749}
1750
1752 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1753 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1754 m_destroy_callbacks.clear();
1756 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1757}
1758
1760 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1761 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1763 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1764 return token;
1765}
1766
1768 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1769 for (auto it = m_destroy_callbacks.begin(); it != m_destroy_callbacks.end();
1770 ++it) {
1771 if (it->token == token) {
1772 m_destroy_callbacks.erase(it);
1773 return true;
1774 }
1775 }
1776 return false;
1777}
1778
1779static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1780 std::string title, std::string details,
1781 uint64_t completed, uint64_t total,
1782 bool is_debugger_specific,
1783 uint32_t progress_broadcast_bit) {
1784 // Only deliver progress events if we have any progress listeners.
1785 if (!debugger.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit))
1786 return;
1787
1788 EventSP event_sp(new Event(
1789 progress_broadcast_bit,
1790 new ProgressEventData(progress_id, std::move(title), std::move(details),
1791 completed, total, is_debugger_specific)));
1792 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1793}
1794
1795void Debugger::ReportProgress(uint64_t progress_id, std::string title,
1796 std::string details, uint64_t completed,
1797 uint64_t total,
1798 std::optional<lldb::user_id_t> debugger_id,
1799 uint32_t progress_broadcast_bit) {
1800 // Check if this progress is for a specific debugger.
1801 if (debugger_id) {
1802 // It is debugger specific, grab it and deliver the event if the debugger
1803 // still exists.
1804 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1805 if (debugger_sp)
1806 PrivateReportProgress(*debugger_sp, progress_id, std::move(title),
1807 std::move(details), completed, total,
1808 /*is_debugger_specific*/ true,
1809 progress_broadcast_bit);
1810 return;
1811 }
1812 // The progress event is not debugger specific, iterate over all debuggers
1813 // and deliver a progress event to each one.
1814 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1815 if (g_debugger_list_ptr) {
1816 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1817 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1818 PrivateReportProgress(*(*pos), progress_id, title, details, completed,
1819 total, /*is_debugger_specific*/ false,
1820 progress_broadcast_bit);
1821 }
1822}
1823
1824static void PrivateReportDiagnostic(Debugger &debugger, Severity severity,
1825 std::string message,
1826 bool debugger_specific) {
1827 uint32_t event_type = 0;
1828 switch (severity) {
1829 case eSeverityInfo:
1830 assert(false && "eSeverityInfo should not be broadcast");
1831 return;
1832 case eSeverityWarning:
1833 event_type = lldb::eBroadcastBitWarning;
1834 break;
1835 case eSeverityError:
1836 event_type = lldb::eBroadcastBitError;
1837 break;
1838 }
1839
1840 Broadcaster &broadcaster = debugger.GetBroadcaster();
1841 if (!broadcaster.EventTypeHasListeners(event_type)) {
1842 // Diagnostics are too important to drop. If nobody is listening, print the
1843 // diagnostic directly to the debugger's error stream.
1844 DiagnosticEventData event_data(severity, std::move(message),
1845 debugger_specific);
1846 event_data.Dump(debugger.GetAsyncErrorStream().get());
1847 return;
1848 }
1849 EventSP event_sp = std::make_shared<Event>(
1850 event_type,
1851 new DiagnosticEventData(severity, std::move(message), debugger_specific));
1852 broadcaster.BroadcastEvent(event_sp);
1853}
1854
1855void Debugger::ReportDiagnosticImpl(Severity severity, std::string message,
1856 std::optional<lldb::user_id_t> debugger_id,
1857 std::once_flag *once) {
1858 auto ReportDiagnosticLambda = [&]() {
1859 // Always log diagnostics to the system log.
1860 Host::SystemLog(severity, message);
1861
1862 // The diagnostic subsystem is optional but we still want to broadcast
1863 // events when it's disabled.
1865 Diagnostics::Instance().Record(message);
1866
1867 // We don't broadcast info events.
1868 if (severity == lldb::eSeverityInfo)
1869 return;
1870
1871 // Check if this diagnostic is for a specific debugger.
1872 if (debugger_id) {
1873 // It is debugger specific, grab it and deliver the event if the debugger
1874 // still exists.
1875 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1876 if (debugger_sp)
1877 PrivateReportDiagnostic(*debugger_sp, severity, std::move(message),
1878 true);
1879 return;
1880 }
1881 // The diagnostic event is not debugger specific, iterate over all debuggers
1882 // and deliver a diagnostic event to each one.
1883 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1884 if (g_debugger_list_ptr) {
1885 for (const auto &debugger : *g_debugger_list_ptr)
1886 PrivateReportDiagnostic(*debugger, severity, message, false);
1887 }
1888 };
1889
1890 if (once)
1891 std::call_once(*once, ReportDiagnosticLambda);
1892 else
1893 ReportDiagnosticLambda();
1894}
1895
1896void Debugger::ReportWarning(std::string message,
1897 std::optional<lldb::user_id_t> debugger_id,
1898 std::once_flag *once) {
1899 ReportDiagnosticImpl(eSeverityWarning, std::move(message), debugger_id, once);
1900}
1901
1902void Debugger::ReportError(std::string message,
1903 std::optional<lldb::user_id_t> debugger_id,
1904 std::once_flag *once) {
1905 ReportDiagnosticImpl(eSeverityError, std::move(message), debugger_id, once);
1906}
1907
1908void Debugger::ReportInfo(std::string message,
1909 std::optional<lldb::user_id_t> debugger_id,
1910 std::once_flag *once) {
1911 ReportDiagnosticImpl(eSeverityInfo, std::move(message), debugger_id, once);
1912}
1913
1915 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1917 return;
1918
1919 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1920 EventSP event_sp = std::make_shared<Event>(
1922 new SymbolChangeEventData(debugger_sp, module_spec));
1923 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1924 }
1925}
1926
1927static std::shared_ptr<LogHandler>
1928CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1929 size_t buffer_size) {
1930 switch (log_handler_kind) {
1931 case eLogHandlerStream:
1932 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1934 return std::make_shared<RotatingLogHandler>(buffer_size);
1935 case eLogHandlerSystem:
1936 return std::make_shared<SystemLogHandler>();
1938 return {};
1939 }
1940 return {};
1941}
1942
1943llvm::Error Debugger::EnableLog(llvm::StringRef channel,
1944 llvm::ArrayRef<const char *> categories,
1945 llvm::StringRef log_file, uint32_t log_options,
1946 size_t buffer_size,
1947 LogHandlerKind log_handler_kind) {
1948
1949 std::shared_ptr<LogHandler> log_handler_sp;
1951 log_handler_sp = m_callback_handler_sp;
1952 // For now when using the callback mode you always get thread & timestamp.
1953 log_options |=
1955 } else if (log_file.empty()) {
1956 log_handler_sp =
1957 CreateLogHandler(log_handler_kind, GetOutputFileSP()->GetDescriptor(),
1958 /*should_close=*/false, buffer_size);
1959 } else {
1960 auto pos = m_stream_handlers.find(log_file);
1961 if (pos != m_stream_handlers.end())
1962 log_handler_sp = pos->second.lock();
1963 if (!log_handler_sp) {
1964 File::OpenOptions flags =
1966 if (log_options & LLDB_LOG_OPTION_APPEND)
1967 flags |= File::eOpenOptionAppend;
1968 else
1970 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1971 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1972 if (!file)
1973 return llvm::createStringErrorV("Unable to open log file '{}': {}",
1974 log_file,
1975 llvm::fmt_consume(file.takeError()));
1976
1977 log_handler_sp =
1978 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1979 /*should_close=*/true, buffer_size);
1980 m_stream_handlers[log_file] = log_handler_sp;
1981 }
1982 }
1983 assert(log_handler_sp);
1984
1985 if (log_options == 0)
1987
1988 return Log::EnableLogChannel(log_handler_sp, log_options, channel,
1989 categories);
1990}
1991
1994 std::optional<lldb::ScriptLanguage> language) {
1995 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1996 lldb::ScriptLanguage script_language =
1997 language ? *language : GetScriptLanguage();
1998
1999 if (!m_script_interpreters[script_language]) {
2000 if (!can_create)
2001 return nullptr;
2002 m_script_interpreters[script_language] =
2003 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
2004 }
2005
2006 return m_script_interpreters[script_language].get();
2007}
2008
2011 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2012 return *m_source_manager_up;
2013}
2014
2015// This function handles events that were broadcast by the process.
2017 using namespace lldb;
2018 const uint32_t event_type =
2020 event_sp);
2021
2022 // if (event_type & eBreakpointEventTypeAdded
2023 // || event_type & eBreakpointEventTypeRemoved
2024 // || event_type & eBreakpointEventTypeEnabled
2025 // || event_type & eBreakpointEventTypeDisabled
2026 // || event_type & eBreakpointEventTypeCommandChanged
2027 // || event_type & eBreakpointEventTypeConditionChanged
2028 // || event_type & eBreakpointEventTypeIgnoreChanged
2029 // || event_type & eBreakpointEventTypeLocationsResolved)
2030 // {
2031 // // Don't do anything about these events, since the breakpoint
2032 // commands already echo these actions.
2033 // }
2034 //
2035 if (event_type & eBreakpointEventTypeLocationsAdded) {
2036 uint32_t num_new_locations =
2038 event_sp);
2039 if (num_new_locations > 0) {
2040 BreakpointSP breakpoint =
2042 if (StreamUP output_up = GetAsyncOutputStream()) {
2043 output_up->Printf("%d location%s added to breakpoint %d\n",
2044 num_new_locations, num_new_locations == 1 ? "" : "s",
2045 breakpoint->GetID());
2046 output_up->Flush();
2047 }
2048 }
2049 }
2050 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
2051 // {
2052 // // These locations just get disabled, not sure it is worth spamming
2053 // folks about this on the command line.
2054 // }
2055 // else if (event_type & eBreakpointEventTypeLocationsResolved)
2056 // {
2057 // // This might be an interesting thing to note, but I'm going to
2058 // leave it quiet for now, it just looked noisy.
2059 // }
2060}
2061
2062void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
2063 bool flush_stderr) {
2064 const auto &flush = [&](Stream &stream,
2065 size_t (Process::*get)(char *, size_t, Status &)) {
2066 Status error;
2067 size_t len;
2068 char buffer[1024];
2069 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
2070 stream.Write(buffer, len);
2071 stream.Flush();
2072 };
2073
2074 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
2075 if (flush_stdout)
2077 if (flush_stderr)
2079}
2080
2081// This function handles events that were broadcast by the process.
2083 const uint32_t event_type = event_sp->GetType();
2084 ProcessSP process_sp =
2088
2089 StreamUP output_stream_up = GetAsyncOutputStream();
2090 StreamUP error_stream_up = GetAsyncErrorStream();
2091 const bool gui_enabled = IsForwardingEvents();
2092
2093 if (!gui_enabled) {
2094 bool pop_process_io_handler = false;
2095 assert(process_sp);
2096
2097 bool state_is_stopped = false;
2098 const bool got_state_changed =
2099 (event_type & Process::eBroadcastBitStateChanged) != 0;
2100 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
2101 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
2102 const bool got_structured_data =
2103 (event_type & Process::eBroadcastBitStructuredData) != 0;
2104
2105 if (got_state_changed) {
2106 StateType event_state =
2108 state_is_stopped = StateIsStoppedState(event_state, false);
2109 }
2110
2111 // Display running state changes first before any STDIO
2112 if (got_state_changed && !state_is_stopped) {
2113 // This is a public stop which we are going to announce to the user, so
2114 // we should force the most relevant frame selection here.
2115 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2117 pop_process_io_handler);
2118 }
2119
2120 // Now display STDOUT and STDERR
2121 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
2122 got_stderr || got_state_changed);
2123
2124 // Give structured data events an opportunity to display.
2125 if (got_structured_data) {
2126 StructuredDataPluginSP plugin_sp =
2128 if (plugin_sp) {
2129 auto structured_data_sp =
2131 StreamString content_stream;
2132 Status error =
2133 plugin_sp->GetDescription(structured_data_sp, content_stream);
2134 if (error.Success()) {
2135 if (!content_stream.GetString().empty()) {
2136 // Add newline.
2137 content_stream.PutChar('\n');
2138 content_stream.Flush();
2139
2140 // Print it.
2141 output_stream_up->PutCString(content_stream.GetString());
2142 }
2143 } else {
2144 error_stream_up->Format("Failed to print structured "
2145 "data with plugin {0}: {1}",
2146 plugin_sp->GetPluginName(), error);
2147 }
2148 }
2149 }
2150
2151 // Now display any stopped state changes after any STDIO
2152 if (got_state_changed && state_is_stopped) {
2153 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2155 pop_process_io_handler);
2156 }
2157
2158 output_stream_up->Flush();
2159 error_stream_up->Flush();
2160
2161 if (pop_process_io_handler)
2162 process_sp->PopProcessIOHandler();
2163 }
2164 return process_sp;
2165}
2166
2168 // At present the only thread event we handle is the Frame Changed event, and
2169 // all we do for that is just reprint the thread status for that thread.
2170 const uint32_t event_type = event_sp->GetType();
2171 const bool stop_format = true;
2172 ThreadSP thread_sp;
2173 if (event_type == Thread::eBroadcastBitStackChanged ||
2175 thread_sp = Thread::ThreadEventData::GetThreadFromEvent(event_sp.get());
2176 if (thread_sp) {
2177 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format,
2178 /*show_hidden*/ true);
2179 }
2180 }
2181 return thread_sp;
2182}
2183
2185
2187 m_forward_listener_sp = listener_sp;
2188}
2189
2191 m_forward_listener_sp.reset();
2192}
2193
2194/// Conservative heuristic to detect whether OSC 9;4 progress is supported by
2195/// the current terminal.
2197#if defined(_WIN32)
2198 // On Windows, we assume that the user is using the Windows Terminal.
2199 return true;
2200#else
2201 static std::once_flag g_once_flag;
2202 static bool g_supports_osc_progress = false;
2203
2204 std::call_once(g_once_flag, []() {
2205 // Check TERM_PROGRAM for known supported terminals. This can lead to false
2206 // negatives, for example when using tmux.
2207 if (const char *term_program = std::getenv("TERM_PROGRAM")) {
2208 llvm::StringRef term_program_str(term_program);
2209 if (term_program_str.starts_with("ghostty") ||
2210 term_program_str.starts_with("wezterm")) {
2211 g_supports_osc_progress = true;
2212 return;
2213 }
2214 }
2215
2216 // Check other known environment variables.
2217 std::array<const char *, 3> known_env_vars = {
2218 "ConEmuPID", // https://conemu.github.io/en/ConEmuEnvironment.html
2219 "GHOSTTY_RESOURCES_DIR", // https://ghostty.org/docs/features/shell-integration
2220 "OSC_PROGRESS", // LLDB specific override.
2221 };
2222 for (const char *env_var : known_env_vars) {
2223 if (std::getenv(env_var)) {
2224 g_supports_osc_progress = true;
2225 return;
2226 }
2227 }
2228 });
2229
2230 return g_supports_osc_progress;
2231#endif
2232}
2233
2236 File &file = stream_sp->GetUnlockedFile();
2237 return file.GetIsInteractive() && file.GetIsRealTerminal() &&
2239 }
2240 return false;
2241}
2242
2244// We have trouble with the contol codes on Windows, see
2245// https://github.com/llvm/llvm-project/issues/134846.
2246#ifndef _WIN32
2248#else
2249 return false;
2250#endif
2251}
2252
2253static bool RequiresFollowChildWorkaround(const Process &process) {
2254 // FIXME: https://github.com/llvm/llvm-project/issues/160216
2255 return process.GetFollowForkMode() == eFollowChild;
2256}
2257
2259 ListenerSP listener_sp(GetListener());
2260 llvm::StringRef broadcaster_class_target(Target::GetStaticBroadcasterClass());
2261 llvm::StringRef broadcaster_class_process(
2263 llvm::StringRef broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
2264 BroadcastEventSpec target_event_spec(broadcaster_class_target,
2266
2267 BroadcastEventSpec process_event_spec(
2268 broadcaster_class_process,
2271
2272 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
2275
2276 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2277 target_event_spec);
2278 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2279 process_event_spec);
2280 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2281 thread_event_spec);
2282 listener_sp->StartListeningForEvents(
2287
2288 listener_sp->StartListeningForEvents(
2293
2294 // Let the thread that spawned us know that we have started up and that we
2295 // are now listening to all required events so no events get missed
2297
2298 if (StatuslineSupported()) {
2299 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2300 if (!m_statusline) {
2301 m_statusline.emplace(*this);
2302 m_statusline->Enable(
2303 GetSelectedExecutionContextRef(/*adopt_dummy_target=*/true));
2304 }
2305 }
2306
2307 bool done = false;
2308 while (!done) {
2309 EventSP event_sp;
2310 if (listener_sp->GetEvent(event_sp, std::nullopt)) {
2311 std::optional<ExecutionContextRef> exe_ctx_ref = std::nullopt;
2312 if (event_sp) {
2313 Broadcaster *broadcaster = event_sp->GetBroadcaster();
2314 if (broadcaster) {
2315 uint32_t event_type = event_sp->GetType();
2316 llvm::StringRef broadcaster_class(broadcaster->GetBroadcasterClass());
2317 if (broadcaster_class == broadcaster_class_process) {
2318 if (ProcessSP process_sp = HandleProcessEvent(event_sp)) {
2319 // Don't pass adopt_selected = true if this is a stop for an
2320 // auto-continue event (e.g. an auto-continue breakpoint). We
2321 // would be fetching stale state, since the process resumed since
2322 // this event, and we'd needlessly interrupt the target to do so.
2323 const bool adopt_selected =
2324 process_sp->GetPrivateState() == eStateStopped &&
2326 event_sp.get());
2327 if (!RequiresFollowChildWorkaround(*process_sp))
2328 exe_ctx_ref =
2329 ExecutionContextRef(process_sp.get(), adopt_selected);
2330 }
2331 } else if (broadcaster_class == broadcaster_class_target) {
2333 event_sp.get())) {
2334 HandleBreakpointEvent(event_sp);
2335 }
2336 } else if (broadcaster_class == broadcaster_class_thread) {
2337 if (ThreadSP thread_sp = HandleThreadEvent(event_sp))
2338 if (!RequiresFollowChildWorkaround(*thread_sp->GetProcess()))
2339 exe_ctx_ref = ExecutionContextRef(thread_sp.get(),
2340 /*adopt_selected=*/true);
2341 } else if (broadcaster == m_command_interpreter_up.get()) {
2342 if (event_type &
2344 done = true;
2345 } else if (event_type &
2347 const char *data = static_cast<const char *>(
2348 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2349 if (data && data[0]) {
2350 StreamUP error_up = GetAsyncErrorStream();
2351 error_up->PutCString(data);
2352 error_up->Flush();
2353 }
2354 } else if (event_type & CommandInterpreter::
2355 eBroadcastBitAsynchronousOutputData) {
2356 const char *data = static_cast<const char *>(
2357 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2358 if (data && data[0]) {
2359 StreamUP output_up = GetAsyncOutputStream();
2360 output_up->PutCString(data);
2361 output_up->Flush();
2362 }
2363 }
2364 } else if (broadcaster == &m_broadcaster) {
2365 if (event_type & lldb::eBroadcastBitProgress ||
2367 HandleProgressEvent(event_sp);
2368 else if (event_type & lldb::eBroadcastBitWarning)
2369 HandleDiagnosticEvent(event_sp);
2370 else if (event_type & lldb::eBroadcastBitError)
2371 HandleDiagnosticEvent(event_sp);
2372 }
2373 }
2374
2376 m_forward_listener_sp->AddEvent(event_sp);
2377 }
2378 RedrawStatusline(exe_ctx_ref);
2379 }
2380 }
2381
2382 {
2383 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2384 if (m_statusline)
2385 m_statusline.reset();
2386 }
2387
2388 return {};
2389}
2390
2392 if (!m_event_handler_thread.IsJoinable()) {
2393 // We must synchronize with the DefaultEventHandler() thread to ensure it
2394 // is up and running and listening to events before we return from this
2395 // function. We do this by listening to events for the
2396 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2397 llvm::StringRef full_name("lldb.debugger.event-handler");
2398 ListenerSP listener_sp(Listener::MakeListener(full_name));
2399 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
2401
2402 llvm::StringRef thread_name =
2403 full_name.size() < llvm::get_max_thread_name_length()
2404 ? full_name
2405 : "dbg.evt-handler";
2406
2407 // Use larger 8MB stack for this thread
2408 llvm::Expected<HostThread> event_handler_thread =
2410 thread_name, [this] { return DefaultEventHandler(); },
2412
2413 if (event_handler_thread) {
2414 m_event_handler_thread = *event_handler_thread;
2415 } else {
2416 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(),
2417 "failed to launch host thread: {0}");
2418 }
2419
2420 // Make sure DefaultEventHandler() is running and listening to events
2421 // before we return from this function. We are only listening for events of
2422 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2423 // event, we just need to wait an infinite amount of time for it (nullptr
2424 // timeout as the first parameter)
2425 lldb::EventSP event_sp;
2426 listener_sp->GetEvent(event_sp, std::nullopt);
2427 }
2428 return m_event_handler_thread.IsJoinable();
2429}
2430
2438
2444
2446 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
2447 if (!data)
2448 return;
2449
2450 // Make a local copy of the incoming progress report that we'll store.
2451 ProgressReport progress_report{data->GetID(), data->GetCompleted(),
2452 data->GetTotal(), data->GetMessage()};
2453
2454 {
2455 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2456
2457 // Do some bookkeeping regardless of whether we're going to display
2458 // progress reports.
2459 auto it = llvm::find_if(m_progress_reports, [&](const auto &report) {
2460 return report.id == progress_report.id;
2461 });
2462 if (it != m_progress_reports.end()) {
2463 const bool complete = data->GetCompleted() == data->GetTotal();
2464 if (complete)
2465 m_progress_reports.erase(it);
2466 else
2467 *it = progress_report;
2468 } else {
2469 m_progress_reports.push_back(progress_report);
2470 }
2471
2472 // Show progress using Operating System Command (OSC) sequences.
2476
2477 // Clear progress if this was the last progress event.
2478 if (m_progress_reports.empty()) {
2479 stream_sp->Lock() << OSC_PROGRESS_REMOVE;
2480 return;
2481 }
2482
2483 const ProgressReport &report = m_progress_reports.back();
2484
2485 // Show indeterminate progress.
2486 if (report.total == UINT64_MAX) {
2487 stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE;
2488 return;
2489 }
2490
2491 // Compute and show the progress value (0-100).
2492 const unsigned value = (report.completed / report.total) * 100;
2493 stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value);
2494 }
2495 }
2496 }
2497}
2498
2499std::optional<Debugger::ProgressReport>
2501 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2502 if (m_progress_reports.empty())
2503 return std::nullopt;
2504 return m_progress_reports.back();
2505}
2506
2508 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
2509 if (!data)
2510 return;
2511
2512 data->Dump(GetAsyncErrorStream().get());
2513}
2514
2516 return m_io_handler_thread.IsJoinable();
2517}
2518
2521 m_io_handler_thread = new_thread;
2522 return old_host;
2523}
2524
2526 if (!m_io_handler_thread.IsJoinable()) {
2527 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
2528 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2529 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2530 if (io_handler_thread) {
2531 m_io_handler_thread = *io_handler_thread;
2532 } else {
2533 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(),
2534 "failed to launch host thread: {0}");
2535 }
2536 }
2537 return m_io_handler_thread.IsJoinable();
2538}
2539
2541 if (m_io_handler_thread.IsJoinable()) {
2542 GetInputFile().Close();
2543 m_io_handler_thread.Join(nullptr);
2544 }
2545}
2546
2554
2556 if (!HasIOHandlerThread())
2557 return false;
2558 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread());
2559}
2560
2562 if (!prefer_dummy) {
2563 if (TargetSP class="code hl_variable" href="classlldb__private_1_1Debugger.html#aa05f5fc946265727cf3fa3f765e845df">m_target_list.GetSelectedTarget())
2564 return *target;
2565 }
2566 return GetDummyTarget();
2567}
2568
2569Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
2570 Status err;
2571 FileSpec repl_executable;
2572
2573 if (language == eLanguageTypeUnknown)
2574 language = GetREPLLanguage();
2575
2576 if (language == eLanguageTypeUnknown) {
2578
2579 if (auto single_lang = repl_languages.GetSingularLanguage()) {
2580 language = *single_lang;
2581 } else if (repl_languages.Empty()) {
2583 "LLDB isn't configured with REPL support for any languages.");
2584 return err;
2585 } else {
2587 "Multiple possible REPL languages. Please specify a language.");
2588 return err;
2589 }
2590 }
2591
2592 Target *const>
2593 nullptr; // passing in an empty target means the REPL must create one
2594
2595 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2596
2597 if (!err.Success()) {
2598 return err;
2599 }
2600
2601 if (!repl_sp) {
2603 "couldn't find a REPL for %s",
2605 return err;
2606 }
2607
2608 repl_sp->SetCompilerOptions(repl_options);
2609 repl_sp->RunLoop();
2610
2611 return err;
2612}
2613
2614llvm::ThreadPoolInterface &Debugger::GetThreadPool() {
2615 assert(g_thread_pool &&
2616 "Debugger::GetThreadPool called before Debugger::Initialize");
2617 return *g_thread_pool;
2618}
2619
2621 llvm::StringRef name, bool value,
2622 llvm::StringRef description) {
2623 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2624 entry_up->AddBooleanItem("value", value);
2625 entry_up->AddStringItem("description", description);
2626 dict.AddItem(name, std::move(entry_up));
2627}
2628
2630 auto array_up = std::make_unique<StructuredData::Array>();
2631#define LLVM_TARGET(target) \
2632 array_up->AddItem(std::make_unique<StructuredData::String>(#target));
2633#include "llvm/Config/Targets.def"
2634 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2635 entry_up->AddItem("value", std::move(array_up));
2636 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
2637 dict.AddItem("targets", std::move(entry_up));
2638}
2639
2641 auto config_up = std::make_unique<StructuredData::Dictionary>();
2643 *config_up, "xml", XMLDocument::XMLEnabled(),
2644 "A boolean value that indicates if XML support is enabled in LLDB");
2646 *config_up, "curl", LLVM_ENABLE_CURL,
2647 "A boolean value that indicates if CURL support is enabled in LLDB");
2649 *config_up, "curses", LLDB_ENABLE_CURSES,
2650 "A boolean value that indicates if curses support is enabled in LLDB");
2652 *config_up, "editline", LLDB_ENABLE_LIBEDIT,
2653 "A boolean value that indicates if editline support is enabled in LLDB");
2654 AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,
2655 "A boolean value that indicates if editline wide "
2656 "characters support is enabled in LLDB");
2658 *config_up, "zlib", LLVM_ENABLE_ZLIB,
2659 "A boolean value that indicates if zlib support is enabled in LLDB");
2661 *config_up, "lzma", LLVM_ENABLE_LZMA,
2662 "A boolean value that indicates if lzma support is enabled in LLDB");
2664 *config_up, "python", LLDB_ENABLE_PYTHON,
2665 "A boolean value that indicates if python support is enabled in LLDB");
2667 *config_up, "lua", LLDB_ENABLE_LUA,
2668 "A boolean value that indicates if lua support is enabled in LLDB");
2669 AddLLVMTargets(*config_up);
2670 return config_up;
2671}
#define OSC_PROGRESS_REMOVE
#define OSC_PROGRESS_INDETERMINATE
#define OSC_PROGRESS_SHOW
static llvm::raw_ostream & error(Stream &strm)
static bool RequiresFollowChildWorkaround(const Process &process)
static llvm::DefaultThreadPool * g_thread_pool
Definition Debugger.cpp:117
static constexpr OptionEnumValueElement g_show_disassembly_enum_values[]
Definition Debugger.cpp:119
static bool TerminalSupportsOSCProgress()
Conservative heuristic to detect whether OSC 9;4 progress is supported by the current terminal.
static lldb::user_id_t g_unique_id
Definition Debugger.cpp:108
static constexpr OptionEnumValueElement g_language_enumerators[]
Definition Debugger.cpp:144
static void PrivateReportDiagnostic(Debugger &debugger, Severity severity, std::string message, bool debugger_specific)
static constexpr OptionEnumValueElement g_dwim_print_verbosities[]
Definition Debugger.cpp:162
static constexpr OptionEnumValueElement s_stop_show_column_values[]
Definition Debugger.cpp:172
static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id, std::string title, std::string details, uint64_t completed, uint64_t total, bool is_debugger_specific, uint32_t progress_broadcast_bit)
static Debugger::DebuggerList * g_debugger_list_ptr
Definition Debugger.cpp:116
static int OpenPipe(int fds[2], std::size_t size)
static size_t g_debugger_event_thread_stack_bytes
Definition Debugger.cpp:109
static constexpr OptionEnumValueElement g_show_autosuggestion_enum_values[]
Definition Debugger.cpp:200
static std::mutex & GetDebuggerListMutex()
Definition Debugger.cpp:111
static FileSystem::EnumerateDirectoryResult LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path)
Definition Debugger.cpp:907
static std::shared_ptr< LogHandler > CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close, size_t buffer_size)
static void AddBoolConfigEntry(StructuredData::Dictionary &dict, llvm::StringRef name, bool value, llvm::StringRef description)
static void AddLLVMTargets(StructuredData::Dictionary &dict)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_OPTION_APPEND
Definition Log.h:45
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_LOG_OPTION_PREPEND_TIMESTAMP
Definition Log.h:41
#define LLDB_LOG_OPTION_PREPEND_THREAD_NAME
Definition Log.h:43
PIPES
Definition PipePosix.cpp:32
@ WRITE
Definition PipePosix.cpp:32
@ READ
Definition PipePosix.cpp:32
A section + offset based address class.
Definition Address.h:62
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:455
static lldb::BreakpointEventType GetBreakpointEventTypeFromEvent(const lldb::EventSP &event_sp)
static lldb::BreakpointSP GetBreakpointFromEvent(const lldb::EventSP &event_sp)
static const BreakpointEventData * GetEventDataFromEvent(const Event *event_sp)
static size_t GetNumBreakpointLocationsFromEvent(const lldb::EventSP &event_sp)
lldb::BroadcastEventSpec
Definition Broadcaster.h:40
An event broadcasting class.
bool EventTypeHasListeners(uint32_t event_type)
virtual llvm::StringRef GetBroadcasterClass() const
This needs to be filled in if you are going to register the broadcaster with the broadcaster manager ...
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
void UpdatePrompt(llvm::StringRef prompt)
bool SaveTranscript(CommandReturnObject &result, std::optional< std::string > output_file=std::nullopt)
Save the current debugger session transcript to a file on disk.
std::string GetErrorString(bool with_diagnostics=true) const
Return the errors as a string.
llvm::StringRef GetOutputString() const
const std::chrono::time_point< std::chrono::system_clock > m_interrupt_time
Definition Debugger.h:546
InterruptionReport(std::string function_name, std::string description)
Definition Debugger.h:528
A class to manage flag bits.
Definition Debugger.h:101
static void AssertCallback(llvm::StringRef message, llvm::StringRef backtrace, llvm::StringRef prompt)
llvm::StringRef GetAutosuggestionAnsiPrefix() const
Definition Debugger.cpp:667
bool SetUseExternalEditor(bool use_external_editor_p)
Definition Debugger.cpp:527
PlatformList m_platform_list
Definition Debugger.h:795
HostThread m_event_handler_thread
Definition Debugger.h:826
FormatEntity::Entry GetDisassemblyFormat() const
Definition Debugger.cpp:392
uint64_t GetDisassemblyLineCount() const
Definition Debugger.cpp:769
llvm::StringRef GetDisabledAnsiSuffix() const
Definition Debugger.cpp:647
uint64_t GetTerminalHeight() const
Definition Debugger.cpp:490
lldb::LockableStreamFileSP m_output_stream_sp
Definition Debugger.h:782
bool SetExternalEditor(llvm::StringRef editor)
Definition Debugger.cpp:538
void RequestInterrupt()
Interruption in LLDB:
void ReportInterruption(const InterruptionReport &report)
const std::string m_instance_name
Definition Debugger.h:821
static void Terminate()
Definition Debugger.cpp:856
lldb::ThreadSP HandleThreadEvent(const lldb::EventSP &event_sp)
void HandleProgressEvent(const lldb::EventSP &event_sp)
SourceManager & GetSourceManager()
bool SetTerminalDimensions(uint64_t term_width, uint64_t term_height)
Set the terminal width and height together, so observers are notified once with both dimensions curre...
Definition Debugger.cpp:500
bool SetShowProgress(bool show_progress)
Definition Debugger.cpp:564
bool StartEventHandlerThread()
Manually start the global event handler thread.
bool SetUseSourceCache(bool use_source_cache)
Definition Debugger.cpp:703
static const FileSpecList & GetDefaultSafeAutoLoadPaths()
Definition Debugger.cpp:237
void StopEventHandlerThread()
Manually stop the debugger's default event handler.
static void ReportInfo(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report info events.
void SetAsyncExecution(bool async)
ExecutionContext GetSelectedExecutionContext(bool adopt_dummy_target)
Get the execution context representing the selected entities in the selected target.
HostThread SetIOHandlerThread(HostThread &new_thread)
void CancelForwardEvents(const lldb::ListenerSP &listener_sp)
bool GetPrintDecls() const
Definition Debugger.cpp:798
lldb::FileSP GetInputFileSP()
Definition Debugger.h:156
bool GetHighlightSource() const
Definition Debugger.cpp:718
llvm::StringMap< std::weak_ptr< LogHandler > > m_stream_handlers
Definition Debugger.h:819
llvm::StringRef GetLabelAnsiSuffix() const
Definition Debugger.cpp:587
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:183
FormatEntity::Entry GetStatuslineFormat() const
Definition Debugger.cpp:623
llvm::StringRef GetDividerAnsiPrefix() const
Definition Debugger.cpp:605
LoadedPluginsList m_loaded_plugins
Definition Debugger.h:825
bool GetShowInlineDiagnostics() const
Definition Debugger.cpp:827
bool SetTabSize(uint64_t tab_size)
Definition Debugger.cpp:815
void HandleDiagnosticEvent(const lldb::EventSP &event_sp)
static lldb::DebuggerSP GetDebuggerAtIndex(size_t index)
llvm::StringRef GetAutosuggestionAnsiSuffix() const
Definition Debugger.cpp:673
lldb::ListenerSP m_listener_sp
Definition Debugger.h:796
void PushIOHandler(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
std::mutex m_destroy_callback_mutex
Definition Debugger.h:840
lldb::callback_token_t AddDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback, void *baton)
Add a callback for when the debugger is destroyed.
lldb::thread_result_t IOHandlerThread()
FormatEntity::Entry GetFrameFormatUnique() const
Definition Debugger.cpp:402
std::optional< ProgressReport > GetCurrentProgressReport() const
llvm::StringRef GetDisabledAnsiPrefix() const
Definition Debugger.cpp:641
bool GetUseExternalEditor() const
Definition Debugger.cpp:521
TerminalState m_terminal_state
Definition Debugger.h:792
lldb::StreamUP GetAsyncErrorStream()
bool GetEscapeNonPrintables() const
Definition Debugger.cpp:781
lldb::TargetSP m_dummy_target_sp
Definition Debugger.h:832
llvm::SmallVector< DestroyCallbackInfo, 2 > m_destroy_callbacks
Definition Debugger.h:852
std::unique_ptr< CommandInterpreter > m_command_interpreter_up
Definition Debugger.h:806
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
static bool FormatDisassemblerAddress(const FormatEntity::Entry *format, const SymbolContext *sc, const SymbolContext *prev_sc, const ExecutionContext *exe_ctx, const Address *addr, Stream &s)
static void SettingsInitialize()
Definition Debugger.cpp:885
LockableStreamFile::Mutex m_output_mutex
Definition Debugger.h:784
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
llvm::StringRef GetShowProgressAnsiSuffix() const
Definition Debugger.cpp:575
bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp)
bool HasIOHandlerThread() const
llvm::SmallVector< ProgressReport, 4 > m_progress_reports
Bookkeeping for command line progress events.
Definition Debugger.h:836
bool IsIOHandlerThreadCurrentThread() const
ExecutionContextRef GetSelectedExecutionContextRef(bool adopt_dummy_target)
Like GetSelectedExecutionContext but returns an ExecutionContextRef.
void DispatchClientTelemetry(const lldb_private::StructuredDataImpl &entry)
Definition Debugger.cpp:995
std::mutex m_progress_reports_mutex
Definition Debugger.h:837
lldb::ProcessSP HandleProcessEvent(const lldb::EventSP &event_sp)
lldb::ListenerSP m_forward_listener_sp
Definition Debugger.h:830
std::array< lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown > m_script_interpreters
Definition Debugger.h:810
std::shared_ptr< CallbackLogHandler > m_callback_handler_sp
Definition Debugger.h:820
void SetDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback, void *baton)
DEPRECATED: We used to only support one Destroy callback.
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:159
Broadcaster m_broadcaster
Public Debugger event broadcaster.
Definition Debugger.h:829
static void Initialize(LoadPluginCallbackType load_plugin_callback)
Definition Debugger.cpp:847
static lldb::DebuggerSP FindDebuggerWithInstanceName(llvm::StringRef instance_name)
uint64_t GetTerminalWidth() const
Definition Debugger.cpp:480
std::mutex m_interrupt_mutex
Definition Debugger.h:855
std::recursive_mutex m_io_handler_synchronous_mutex
Definition Debugger.h:813
bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp)
Remove the given IO handler if it's currently active.
bool GetAutoOneLineSummaries() const
Definition Debugger.cpp:775
const char * GetIOHandlerCommandPrefix()
std::optional< Statusline > m_statusline
Definition Debugger.h:817
llvm::StringRef GetDividerAnsiSuffix() const
Definition Debugger.cpp:611
bool GetUseColor() const
Definition Debugger.cpp:543
llvm::StringRef GetTitleAnsiPrefix() const
Definition Debugger.cpp:593
lldb::BroadcasterManagerSP m_broadcaster_manager_sp
Definition Debugger.h:786
void FlushStatusLine()
Flush cached state (e.g. stale execution context in the statusline).
Status RunREPL(lldb::LanguageType language, const char *repl_options)
bool PopIOHandler(const lldb::IOHandlerSP &reader_sp)
static StructuredData::DictionarySP GetBuildConfiguration()
Get the build configuration as structured data.
bool RemoveDestroyCallback(lldb::callback_token_t token)
Remove the specified callback. Return true if successful.
static LoadPluginCallbackType g_load_plugin_callback
Definition Debugger.h:823
bool GetShowStatusline() const
Definition Debugger.cpp:617
std::recursive_mutex m_script_interpreter_mutex
Definition Debugger.h:808
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
void SetInputFile(lldb::FileSP file)
lldb::LockableStreamFileSP GetOutputStreamSP()
Except for Debugger and IOHandler, GetOutputStreamSP and GetErrorStreamSP should not be used directly...
Definition Debugger.h:736
void SetPrompt(llvm::StringRef p)
Definition Debugger.cpp:437
llvm::StringRef GetSeparator() const
Definition Debugger.cpp:635
bool StatuslineSupported()
Whether the statusline can be drawn: show-statusline is enabled and the output is an escape-code-capa...
uint64_t GetStopDisassemblyMaxSize() const
Definition Debugger.cpp:407
bool SetTerminalHeight(uint64_t term_height)
Definition Debugger.cpp:496
Broadcaster m_sync_broadcaster
Private debugger synchronization.
Definition Debugger.h:828
llvm::StringRef GetTitleAnsiSuffix() const
Definition Debugger.cpp:599
bool GetUseSourceCache() const
Definition Debugger.cpp:697
HostThread m_io_handler_thread
Definition Debugger.h:827
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:685
static llvm::StringRef GetStaticBroadcasterClass()
lldb::FileSP m_input_file_sp
Definition Debugger.h:781
bool SetREPLLanguage(lldb::LanguageType repl_lang)
Definition Debugger.cpp:475
bool GetAutoIndent() const
Definition Debugger.cpp:787
AutosuggestionMode GetAutosuggestionMode() const
Definition Debugger.cpp:660
llvm::StringRef GetStopShowColumnAnsiSuffix() const
Definition Debugger.cpp:737
Status SetPropertyValue(const ExecutionContext *exe_ctx, VarSetOperationType op, llvm::StringRef property_path, llvm::StringRef value) override
Definition Debugger.cpp:299
llvm::StringRef GetPromptAnsiSuffix() const
Definition Debugger.cpp:431
FormatEntity::Entry GetThreadStopFormat() const
Definition Debugger.cpp:453
void SetErrorFile(lldb::FileSP file)
bool GetAutoConfirm() const
Definition Debugger.cpp:386
TargetList m_target_list
Definition Debugger.h:793
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:458
lldb::callback_token_t m_destroy_callback_next_token
Definition Debugger.h:841
std::unique_ptr< SourceManager > m_source_manager_up
Definition Debugger.h:797
static lldb::DebuggerSP CreateInstance(lldb::LogOutputCallback log_callback=nullptr, void *baton=nullptr)
Definition Debugger.cpp:977
lldb::StopShowColumn GetStopShowColumn() const
Definition Debugger.cpp:724
static void ReportSymbolChange(const ModuleSpec &module_spec)
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
bool SetPrintDecls(bool b)
Definition Debugger.cpp:804
bool SetScriptLanguage(lldb::ScriptLanguage script_lang)
Definition Debugger.cpp:465
lldb::LockableStreamFileSP m_error_stream_sp
Definition Debugger.h:783
bool SetShowInlineDiagnostics(bool)
Definition Debugger.cpp:833
bool LoadPlugin(const FileSpec &spec, Status &error)
Definition Debugger.cpp:889
void SetOutputFile(lldb::FileSP file)
uint64_t GetStopSourceLineCount(bool before) const
Definition Debugger.cpp:755
bool SetStatuslineFormat(const FormatEntity::Entry &format)
Definition Debugger.cpp:628
void EnableForwardEvents(const lldb::ListenerSP &listener_sp)
static lldb::DebuggerSP FindDebuggerWithID(lldb::user_id_t id)
void HandleBreakpointEvent(const lldb::EventSP &event_sp)
bool CheckTopIOHandlerTypes(IOHandler::Type top_type, IOHandler::Type second_top_type)
Target & GetDummyTarget()
Definition Debugger.h:561
lldb::ListenerSP GetListener()
Definition Debugger.h:192
static void Destroy(lldb::DebuggerSP &debugger_sp)
SourceManager::SourceFileCache m_source_file_cache
Definition Debugger.h:801
llvm::StringRef GetPromptAnsiPrefix() const
Definition Debugger.cpp:425
lldb::StreamUP GetAsyncOutputStream()
void RedrawStatusline(std::optional< ExecutionContextRef > exe_ctx_ref)
Redraw the statusline if enabled.
void RunIOHandlerSync(const lldb::IOHandlerSP &reader_sp)
Run the given IO handler and block until it's complete.
Broadcaster & GetBroadcaster()
Get the public broadcaster for this debugger.
Definition Debugger.h:108
llvm::StringRef GetStopShowLineMarkerAnsiPrefix() const
Definition Debugger.cpp:743
bool GetShowDontUsePoHint() const
Definition Debugger.cpp:691
uint64_t GetTabSize() const
Definition Debugger.cpp:809
bool GetShowProgress() const
Definition Debugger.cpp:558
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:679
std::mutex m_output_flush_mutex
Definition Debugger.h:776
llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const
Definition Debugger.cpp:749
bool SetSeparator(llvm::StringRef s)
Definition Debugger.cpp:653
bool SetUseColor(bool use_color)
Definition Debugger.cpp:549
std::mutex m_statusline_mutex
Mutex protecting the m_statusline member.
Definition Debugger.h:816
const char * GetIOHandlerHelpPrologue()
Status SetInputString(const char *data)
llvm::StringRef GetLabelAnsiPrefix() const
Definition Debugger.cpp:581
Target & GetSelectedOrDummyTarget(bool prefer_dummy=false)
std::vector< std::string > CopyLogFilesToDirectory(const FileSpec &dir)
Copy this debugger's file-backed log files into the given directory, for inclusion in a diagnostics b...
IOHandlerStack m_io_handler_stack
Definition Debugger.h:812
llvm::once_flag m_clear_once
Definition Debugger.h:831
static void SettingsTerminate()
Definition Debugger.cpp:887
static void ReportProgress(uint64_t progress_id, std::string title, std::string details, uint64_t completed, uint64_t total, std::optional< lldb::user_id_t > debugger_id, uint32_t progress_category_bit=lldb::eBroadcastBitProgress)
Report progress events.
lldb::LanguageType GetREPLLanguage() const
Definition Debugger.cpp:470
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
void SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton)
bool SetTerminalWidth(uint64_t term_width)
Definition Debugger.cpp:486
Debugger(lldb::LogOutputCallback m_log_callback, void *baton)
llvm::StringRef GetExternalEditor() const
Definition Debugger.cpp:532
static size_t GetNumDebuggers()
FormatEntity::Entry GetThreadFormat() const
Definition Debugger.cpp:448
uint32_t m_interrupt_requested
Tracks interrupt requests.
Definition Debugger.h:854
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition Debugger.cpp:820
bool GetMarkHiddenFrames() const
Definition Debugger.cpp:712
lldb::thread_result_t DefaultEventHandler()
void PrintAsync(const char *s, size_t len, bool is_stdout)
lldb::LockableStreamFileSP GetErrorStreamSP()
Definition Debugger.h:737
llvm::Error EnableLog(llvm::StringRef channel, llvm::ArrayRef< const char * > categories, llvm::StringRef log_file, uint32_t log_options, size_t buffer_size, LogHandlerKind log_handler_kind)
llvm::StringRef GetPrompt() const
Definition Debugger.cpp:419
bool GetNotifyVoid() const
Definition Debugger.cpp:413
llvm::StringRef GetShowProgressAnsiPrefix() const
Definition Debugger.cpp:569
void AdoptTopIOHandlerFilesIfInvalid(lldb::FileSP &in, lldb::LockableStreamFileSP &out, lldb::LockableStreamFileSP &err)
FormatEntity::Entry GetFrameFormat() const
Definition Debugger.cpp:397
lldb::StopDisassemblyType GetStopDisassemblyDisplay() const
Definition Debugger.cpp:762
llvm::StringRef GetTopIOHandlerControlSequence(char ch)
void FlushProcessOutput(Process &process, bool flush_stdout, bool flush_stderr)
Force flushing the process's pending stdout and stderr to the debugger's asynchronous stdout and stde...
void CancelInterruptRequest()
Decrement the "interrupt requested" counter.
static void ReportDiagnosticImpl(lldb::Severity severity, std::string message, std::optional< lldb::user_id_t > debugger_id, std::once_flag *once)
std::vector< lldb::DebuggerSP > DebuggerList
Definition Debugger.h:103
bool SetAutoIndent(bool b)
Definition Debugger.cpp:793
friend class CommandInterpreter
Definition Debugger.h:683
llvm::StringRef GetStopShowColumnAnsiPrefix() const
Definition Debugger.cpp:731
static DebuggerList DebuggersRequestingInterruption()
void Dump(Stream *s) const override
static const DiagnosticEventData * GetEventDataFromEvent(const Event *event_ptr)
static DiagnosticsProperties & GetGlobalProperties()
void Record(llvm::StringRef message)
Record a diagnostic message into the always-on, in-memory log.
static Diagnostics & Instance()
static const void * GetBytesFromEvent(const Event *event_ptr)
Definition Event.cpp:146
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Event.cpp:247
static lldb::StructuredDataPluginSP GetPluginFromEvent(const Event *event_ptr)
Definition Event.cpp:265
static StructuredData::ObjectSP GetObjectFromEvent(const Event *event_ptr)
Definition Event.cpp:256
Execution context objects refer to objects in the execution of the program that is being debugged.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
bool HasTargetScope() const
Returns true the ExecutionContext object contains a valid target.
Target & GetTargetRef() const
Returns a reference to the target object.
A file collection class.
void EmplaceBack(Args &&...args)
Inserts a new FileSpec into the FileSpecList constructed in-place with the given arguments.
A file utility class.
Definition FileSpec.h:56
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:410
void EnumerateDirectory(llvm::Twine path, bool find_directories, bool find_files, bool find_other, EnumerateDirectoryCallbackType callback, void *callback_baton)
@ eEnumerateDirectoryResultEnter
Recurse into the current entry if it is a directory or symlink, or next if not.
Definition FileSystem.h:185
@ eEnumerateDirectoryResultNext
Enumerate next entry in the current directory.
Definition FileSystem.h:182
@ eEnumerateDirectoryResultQuit
Stop directory enumerations at any level.
Definition FileSystem.h:187
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
An abstract base class for files.
Definition FileBase.h:34
bool GetIsRealTerminal()
Return true if this file from a real terminal.
Definition File.cpp:168
static int kInvalidDescriptor
Definition FileBase.h:36
virtual int GetDescriptor() const
Get underlying OS file descriptor for this file, or kInvalidDescriptor.
Definition File.cpp:119
bool GetIsTerminalWithColors()
Return true if this file is a terminal which supports colors.
Definition File.cpp:174
Status Close() override
Flush any buffers and release any resources owned by the file.
Definition File.cpp:108
bool GetIsInteractive()
Return true if this file is interactive.
Definition File.cpp:162
bool Format(const Entry &entry, Stream &s, ValueObject *valobj=nullptr)
const Mangled & GetMangled() const
Definition Function.h:541
static void SystemLog(lldb::Severity severity, llvm::StringRef message)
Emit the given message to the operating system log.
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
static llvm::StringRef GetSettingName()
Definition Language.cpp:45
static LanguageSet GetLanguagesSupportingREPLs()
Definition Language.cpp:489
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:305
static LanguageProperties & GetGlobalLanguageProperties()
Definition Language.cpp:40
static lldb::ListenerSP MakeListener(llvm::StringRef name)
Definition Listener.cpp:373
static llvm::Error EnableLogChannel(const std::shared_ptr< LogHandler > &log_handler_sp, uint32_t log_options, llvm::StringRef channel, llvm::ArrayRef< const char * > categories)
Definition Log.cpp:230
static ModuleListProperties & GetGlobalModuleListProperties()
void AppendCurrentValue(const FileSpec &value)
void SetCurrentValue(const FileSpecList &value)
static lldb::PlatformSP GetHostPlatform()
Get the native host platform plug-in.
Definition Platform.cpp:150
static PlatformProperties & GetGlobalPlatformProperties()
Definition Platform.cpp:156
static lldb::ScriptInterpreterSP GetScriptInterpreterForLanguage(lldb::ScriptLanguage script_lang, Debugger &debugger)
static void DebuggerInitialize(Debugger &debugger)
FollowForkMode GetFollowForkMode() const
Definition Process.cpp:430
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4799
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4783
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4791
A plug-in interface definition class for debugging a process.
Definition Process.h:369
static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp, Stream *stream, SelectMostRelevant select_most_relevant, bool &pop_process_io_handler)
Centralize the code that handles and prints descriptions for process state changes.
Definition Process.cpp:796
static llvm::StringRef GetStaticBroadcasterClass()
Definition Process.cpp:481
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4986
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4967
static const ProgressEventData * GetEventDataFromEvent(const Event *event_ptr)
lldb::OptionValuePropertiesSP m_collection_sp
virtual Status SetPropertyValue(const ExecutionContext *exe_ctx, VarSetOperationType op, llvm::StringRef property_path, llvm::StringRef value)
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
lldb::OptionValuePropertiesSP GetValueProperties() const
static lldb::REPLSP Create(Status &Status, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options)
Get a REPL with an existing target (or, failing that, a debugger to use), and (optional) extra argume...
Definition REPL.cpp:38
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Success() const
Test for success condition.
Definition Status.cpp:303
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition Stream.h:111
size_t PutChar(char ch)
Definition Stream.cpp:131
virtual void Flush()=0
Flush the stream.
void AddItem(llvm::StringRef key, ObjectSP value_sp)
std::shared_ptr< Dictionary > DictionarySP
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Symbol * symbol
The Symbol for a given query.
bool Compare(ConstString name, lldb::SymbolType type) const
Definition Symbol.cpp:424
ConstString GetName() const
Definition Symbol.cpp:612
lldb::SymbolType GetType() const
Definition Symbol.h:197
Debugger & GetDebugger() const
Definition Target.h:1362
static void SettingsTerminate()
Definition Target.cpp:2921
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:177
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3471
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2931
@ eBroadcastBitBreakpointChanged
Definition Target.h:607
static void SettingsInitialize()
Definition Target.cpp:2919
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
static lldb::ThreadSP GetThreadFromEvent(const Event *event_ptr)
Definition Thread.cpp:189
@ eBroadcastBitThreadSelected
Definition Thread.h:81
static llvm::StringRef GetStaticBroadcasterClass()
Definition Thread.cpp:221
static bool XMLEnabled()
Definition XML.cpp:83
virtual void DispatchClientTelemetry(const lldb_private::StructuredDataImpl &entry, Debugger *debugger)
static TelemetryManager * GetInstance()
#define UINT64_MAX
@ SelectMostRelevantFrame
#define LLDB_INVALID_HOST_THREAD
Definition lldb-types.h:69
Status Parse(const llvm::StringRef &format, Entry &entry)
std::string FormatAnsiTerminalCodes(llvm::StringRef format, bool do_color=true)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
LoadScriptFromSymFile
Definition Target.h:61
@ eLoadScriptFromSymFileTrue
Definition Target.h:62
@ eLoadScriptFromSymFileFalse
Definition Target.h:63
@ eLoadScriptFromSymFileWarn
Definition Target.h:64
const char * GetVersion()
Retrieves a string representing the complete LLDB version, which includes the lldb version number,...
Definition Version.cpp:38
void(* DebuggerDestroyCallback)(lldb::user_id_t debugger_id, void *baton)
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
NativeFilePosix NativeFile
Definition File.h:29
llvm::sys::DynamicLibrary(* LoadPluginCallbackType)(const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, Status &error)
VarSetOperationType
Settable state variable types.
AutosuggestionMode
Controls how the show-autosuggestion setting drives inline suggestions in the interactive command lin...
@ eAutosuggestionTabMode
Show the prefix that tab completion would insert for the current line.
@ eAutosuggestionOn
Show a suggestion sourced from previously entered commands.
@ eAutosuggestionOff
Do not show any autosuggestion.
ScriptLanguage
Script interpreter types.
@ eScriptLanguageDefault
@ eScriptLanguageNone
@ eScriptLanguagePython
Severity
Used for expressing severity in logs and diagnostics.
@ eBroadcastBitExternalProgress
@ eBroadcastBitProgress
@ eBroadcastSymbolChange
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::Thread > ThreadSP
void * thread_result_t
Definition lldb-types.h:62
std::shared_ptr< lldb_private::Platform > PlatformSP
DWIMPrintVerbosity
Enum to control the verbosity level of dwim-print execution.
@ eDWIMPrintVerbosityFull
Always print a message indicating how dwim-print is evaluating its expression.
@ eDWIMPrintVerbosityNone
Run dwim-print with no verbosity.
@ eDWIMPrintVerbosityExpression
Print a message when dwim-print uses expression evaluation.
StateType
Process and Thread States.
@ eStateStopped
Process or thread is stopped and can be examined.
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::StructuredDataPlugin > StructuredDataPluginSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
StopDisassemblyType
Used to determine when to show disassembly.
@ eStopDisassemblyTypeNever
@ eStopDisassemblyTypeNoSource
@ eStopDisassemblyTypeAlways
@ eStopDisassemblyTypeNoDebugInfo
@ eStopShowColumnAnsi
@ eStopShowColumnCaret
@ eStopShowColumnNone
@ eStopShowColumnAnsiOrCaret
std::shared_ptr< lldb_private::Event > EventSP
std::shared_ptr< lldb_private::Listener > ListenerSP
int32_t callback_token_t
Definition lldb-types.h:82
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
void(* LogOutputCallback)(const char *, void *baton)
Definition lldb-types.h:73
std::shared_ptr< lldb_private::Target > TargetSP
std::unique_ptr< lldb_private::Stream > StreamUP
std::shared_ptr< lldb_private::File > FileSP
std::shared_ptr< lldb_private::REPL > REPLSP
lldb_private::DebuggerDestroyCallback callback
Definition Debugger.h:849
A SmallBitVector that represents a set of source languages (lldb::LanguageType).
Definition Type.h:38
std::optional< lldb::LanguageType > GetSingularLanguage()
If the set contains a single language only, return it.
void AppendSafeAutoLoadPaths(FileSpec path)
Appends a path to the testing.safe-auto-load-paths setting.
Definition Debugger.cpp:283
static TestingProperties & GetGlobalTestingProperties()
Definition Debugger.cpp:270
FileSpecList GetSafeAutoLoadPaths() const
Callers should use Debugger::GetSafeAutoLoadPaths since it accounts for default paths configured via ...
Definition Debugger.cpp:291
void SetSafeAutoLoadPaths(FileSpecList paths)
Overwrites the testing.safe-auto-load-paths settings.
Definition Debugger.cpp:275
UserID(lldb::user_id_t uid=LLDB_INVALID_UID)
Construct with optional user ID.
Definition UserID.h:33
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47
Helper RAII class for collecting telemetry.
Definition Telemetry.h:269
#define PATH_MAX