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_platform_list(), 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_target_group_list.Clear();
1205 m_broadcaster_manager_sp->Clear();
1206
1207 // Close the input file _before_ we close the input read communications
1208 // class as it does NOT own the input file, our m_input_file does.
1209 m_terminal_state.Clear();
1210 GetInputFile().Close();
1211
1212 m_command_interpreter_up->Clear();
1213 });
1214}
1215
1217 return !m_command_interpreter_up->GetSynchronous();
1218}
1219
1220void Debugger::SetAsyncExecution(bool async_execution) {
1221 m_command_interpreter_up->SetSynchronous(!async_execution);
1222}
1223
1224static inline int OpenPipe(int fds[2], std::size_t size) {
1225#ifdef _WIN32
1226 return _pipe(fds, size, O_BINARY);
1227#else
1228 (void)size;
1229 return pipe(fds);
1230#endif
1231}
1232
1234 Status result;
1235 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
1236 int fds[2] = {-1, -1};
1237
1238 if (data == nullptr) {
1239 result = Status::FromErrorString("String data is null");
1240 return result;
1241 }
1242
1243 size_t size = strlen(data);
1244 if (size == 0) {
1245 result = Status::FromErrorString("String data is empty");
1246 return result;
1247 }
1248
1249 if (OpenPipe(fds, size) != 0) {
1250 result = Status::FromErrorString(
1251 "can't create pipe file descriptors for LLDB commands");
1252 return result;
1253 }
1254
1255 int r = write(fds[WRITE], data, size);
1256 (void)r;
1257 // Close the write end of the pipe, so that the command interpreter will exit
1258 // when it consumes all the data.
1259 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
1260
1261 // Open the read file descriptor as a FILE * that we can return as an input
1262 // handle.
1263 FILE *commands_file = fdopen(fds[READ], "rb");
1264 if (commands_file == nullptr) {
1266 "fdopen(%i, \"rb\") failed (errno = %i) "
1267 "when trying to open LLDB commands pipe",
1268 fds[READ], errno);
1269 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
1270 return result;
1271 }
1272
1273 SetInputFile((FileSP)std::make_shared<NativeFile>(
1274 commands_file, File::eOpenOptionReadOnly, true));
1275 return result;
1276}
1277
1279 assert(file_sp && file_sp->IsValid());
1280 m_input_file_sp = std::move(file_sp);
1281 // Save away the terminal state if that is relevant, so that we can restore
1282 // it in RestoreInputState.
1284}
1285
1287 assert(file_sp && file_sp->IsValid());
1289 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1290}
1291
1293 assert(file_sp && file_sp->IsValid());
1295 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1296}
1297
1299 {
1300 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1301 if (m_statusline)
1302 m_statusline->Disable();
1303 }
1304 int fd = GetInputFile().GetDescriptor();
1305 if (fd != File::kInvalidDescriptor)
1306 m_terminal_state.Save(fd, true);
1307}
1308
1310 m_terminal_state.Restore();
1311 {
1312 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1313 if (m_statusline)
1314 m_statusline->Enable(
1315 GetSelectedExecutionContext(/*adopt_dummy_target=*/true));
1316 }
1317}
1318
1320 std::optional<ExecutionContextRef> exe_ctx_ref) {
1321 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1322
1323 const bool flush = m_flush_statusline.exchange(false);
1324 if (!m_statusline)
1325 return;
1326
1327 if (flush)
1328 m_statusline->ClearExecutionContext();
1329 m_statusline->Redraw(exe_ctx_ref);
1330}
1331
1333
1336 return ExecutionContext(GetSelectedExecutionContextRef(adopt_dummy_target));
1337}
1338
1341 if (TargetSP selected_target_sp = m_target_list.GetSelectedTarget())
1342 return ExecutionContextRef(selected_target_sp.get(),
1343 /*adopt_selected=*/true);
1344
1345 if (adopt_dummy_target)
1347 /*adopt_selected=*/false);
1348
1349 return ExecutionContextRef();
1350}
1351
1353 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1354 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1355 if (reader_sp)
1356 reader_sp->Interrupt();
1357}
1358
1360 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1361 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1362 if (reader_sp)
1363 reader_sp->GotEOF();
1364}
1365
1367 // The bottom input reader should be the main debugger input reader. We do
1368 // not want to close that one here.
1369 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1370 while (m_io_handler_stack.GetSize() > 1) {
1371 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1372 if (reader_sp)
1373 PopIOHandler(reader_sp);
1374 }
1375}
1376
1378 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1379 while (true) {
1380 if (!reader_sp)
1381 break;
1382
1383 reader_sp->Run();
1384 {
1385 std::lock_guard<std::recursive_mutex> guard(
1387
1388 // Remove all input readers that are done from the top of the stack
1389 while (true) {
1390 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1391 if (top_reader_sp && top_reader_sp->GetIsDone())
1392 PopIOHandler(top_reader_sp);
1393 else
1394 break;
1395 }
1396 reader_sp = m_io_handler_stack.Top();
1397 }
1398 }
1400}
1401
1403 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1404
1405 PushIOHandler(reader_sp);
1406 IOHandlerSP top_reader_sp = reader_sp;
1407
1408 while (top_reader_sp) {
1409 top_reader_sp->Run();
1410
1411 // Don't unwind past the starting point.
1412 if (top_reader_sp.get() == reader_sp.get()) {
1413 if (PopIOHandler(reader_sp))
1414 break;
1415 }
1416
1417 // If we pushed new IO handlers, pop them if they're done or restart the
1418 // loop to run them if they're not.
1419 while (true) {
1420 top_reader_sp = m_io_handler_stack.Top();
1421 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1422 PopIOHandler(top_reader_sp);
1423 // Don't unwind past the starting point.
1424 if (top_reader_sp.get() == reader_sp.get())
1425 return;
1426 } else {
1427 break;
1428 }
1429 }
1430 }
1431}
1432
1434 return m_io_handler_stack.IsTop(reader_sp);
1435}
1436
1438 IOHandler::Type second_top_type) {
1439 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1440}
1441
1442void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1443 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1444 if (!printed) {
1445 LockableStreamFileSP stream_sp =
1447 LockedStreamFile locked_stream = stream_sp->Lock();
1448 locked_stream.Write(s, len);
1449 }
1450}
1451
1453 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1454}
1455
1457 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1458}
1459
1461 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1462}
1463
1465 return PopIOHandler(reader_sp);
1466}
1467
1469 bool cancel_top_handler) {
1470 PushIOHandler(reader_sp, cancel_top_handler);
1471}
1472
1475 LockableStreamFileSP &err) {
1476 // Before an IOHandler runs, it must have in/out/err streams. This function
1477 // is called when one ore more of the streams are nullptr. We use the top
1478 // input reader's in/out/err streams, or fall back to the debugger file
1479 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1480
1481 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1482 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1483 // If no STDIN has been set, then set it appropriately
1484 if (!in || !in->IsValid()) {
1485 if (top_reader_sp)
1486 in = top_reader_sp->GetInputFileSP();
1487 else
1488 in = GetInputFileSP();
1489 // If there is nothing, use stdin
1490 if (!in)
1491 in = std::make_shared<NativeFile>(stdin, File::eOpenOptionReadOnly,
1493 }
1494 // If no STDOUT has been set, then set it appropriately
1495 if (!out || !out->GetUnlockedFile().IsValid()) {
1496 if (top_reader_sp)
1497 out = top_reader_sp->GetOutputStreamFileSP();
1498 else
1499 out = GetOutputStreamSP();
1500 // If there is nothing, use stdout
1501 if (!out)
1502 out = std::make_shared<LockableStreamFile>(stdout, NativeFile::Unowned,
1504 }
1505 // If no STDERR has been set, then set it appropriately
1506 if (!err || !err->GetUnlockedFile().IsValid()) {
1507 if (top_reader_sp)
1508 err = top_reader_sp->GetErrorStreamFileSP();
1509 else
1510 err = GetErrorStreamSP();
1511 // If there is nothing, use stderr
1512 if (!err)
1513 err = std::make_shared<LockableStreamFile>(stderr, NativeFile::Unowned,
1515 }
1516}
1517
1519 bool cancel_top_handler) {
1520 if (!reader_sp)
1521 return;
1522
1523 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1524
1525 // Get the current top input reader...
1526 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1527
1528 // Don't push the same IO handler twice...
1529 if (reader_sp == top_reader_sp)
1530 return;
1531
1532 // Push our new input reader
1533 m_io_handler_stack.Push(reader_sp);
1534 reader_sp->Activate();
1535
1536 // Interrupt the top input reader to it will exit its Run() function and let
1537 // this new input reader take over
1538 if (top_reader_sp) {
1539 top_reader_sp->Deactivate();
1540 if (cancel_top_handler)
1541 top_reader_sp->Cancel();
1542 }
1543}
1544
1545bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1546 if (!pop_reader_sp)
1547 return false;
1548
1549 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1550
1551 // The reader on the stop of the stack is done, so let the next read on the
1552 // stack refresh its prompt and if there is one...
1553 if (m_io_handler_stack.IsEmpty())
1554 return false;
1555
1556 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1557
1558 if (pop_reader_sp != reader_sp)
1559 return false;
1560
1561 reader_sp->Deactivate();
1562 reader_sp->Cancel();
1563 m_io_handler_stack.Pop();
1564
1565 reader_sp = m_io_handler_stack.Top();
1566 if (reader_sp)
1567 reader_sp->Activate();
1568
1569 return true;
1570}
1571
1573 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1574 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1575 if (reader_sp)
1576 reader_sp->Refresh();
1577}
1578
1580 return std::make_unique<StreamAsynchronousIO>(*this,
1582}
1583
1585 return std::make_unique<StreamAsynchronousIO>(*this,
1587}
1588
1590 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1592}
1593
1595 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1596 if (m_interrupt_requested > 0)
1598}
1599
1601 // This is the one we should call internally. This will return true either
1602 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1603 // or if we are on the IOHandler thread and there's a CommandInterpreter
1604 // interrupt.
1606 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1607 return m_interrupt_requested != 0;
1608 }
1610}
1611
1613 std::string function_name, const llvm::formatv_object_base &payload)
1614 : m_function_name(std::move(function_name)),
1615 m_interrupt_time(std::chrono::system_clock::now()),
1616 m_thread_id(llvm::get_threadid()) {
1617 llvm::raw_string_ostream desc(m_description);
1618 desc << payload << "\n";
1619}
1620
1622 // For now, just log the description:
1623 Log *log = GetLog(LLDBLog::Host);
1624 LLDB_LOG(log, "Interruption: {0}", report.m_description);
1625}
1626
1628 DebuggerList result;
1629 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1630 if (g_debugger_list_ptr) {
1631 for (auto debugger_sp : *g_debugger_list_ptr) {
1632 if (debugger_sp->InterruptRequested())
1633 result.push_back(debugger_sp);
1634 }
1635 }
1636 return result;
1637}
1638
1640 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1642 return 0;
1643
1644 return g_debugger_list_ptr->size();
1645}
1646
1648 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1650 return nullptr;
1651
1652 if (index < g_debugger_list_ptr->size())
1653 return g_debugger_list_ptr->at(index);
1654
1655 return nullptr;
1656}
1657
1659 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1661 return nullptr;
1662
1663 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1664 if (debugger_sp->GetID() == id)
1665 return debugger_sp;
1666 }
1667
1668 return nullptr;
1669}
1670
1672 const SymbolContext *sc,
1673 const SymbolContext *prev_sc,
1674 const ExecutionContext *exe_ctx,
1675 const Address *addr, Stream &s) {
1676 FormatEntity::Entry format_entry;
1677
1678 if (format == nullptr) {
1679 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) {
1680 format_entry =
1682 format = &format_entry;
1683 }
1684 if (format == nullptr) {
1685 FormatEntity::Parse("${addr}: ", format_entry);
1686 format = &format_entry;
1687 }
1688 }
1689 bool function_changed = false;
1690 bool initial_function = false;
1691 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1692 if (sc && (sc->function || sc->symbol)) {
1693 if (prev_sc->symbol && sc->symbol) {
1694 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1695 prev_sc->symbol->GetType())) {
1696 function_changed = true;
1697 }
1698 } else if (prev_sc->function && sc->function) {
1699 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1700 function_changed = true;
1701 }
1702 }
1703 }
1704 }
1705 // The first context on a list of instructions will have a prev_sc that has
1706 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1707 // would return false. But we do get a prev_sc pointer.
1708 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1709 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1710 initial_function = true;
1711 }
1712 return FormatEntity::Formatter(sc, exe_ctx, addr, function_changed,
1713 initial_function)
1714 .Format(*format, s);
1715}
1716
1717void Debugger::AssertCallback(llvm::StringRef message,
1718 llvm::StringRef backtrace,
1719 llvm::StringRef prompt) {
1720 Debugger::ReportError(llvm::formatv("{0}\n{1}{2}\n{3}", message, backtrace,
1721 GetVersion(), prompt)
1722 .str());
1723}
1724
1726 void *baton) {
1727 // For simplicity's sake, I am not going to deal with how to close down any
1728 // open logging streams, I just redirect everything from here on out to the
1729 // callback.
1731 std::make_shared<CallbackLogHandler>(log_callback, baton);
1732}
1733
1734std::vector<std::string>
1736 std::vector<std::string> copied;
1737 for (auto &entry : m_stream_handlers) {
1738 llvm::StringRef log_path = entry.first();
1739 llvm::StringRef file_name = llvm::sys::path::filename(log_path);
1740 FileSpec destination = dir.CopyByAppendingPathComponent(file_name);
1741 // Best-effort: skip logs that can't be copied rather than aborting.
1742 if (!llvm::sys::fs::copy_file(log_path, destination.GetPath()))
1743 copied.push_back(file_name.str());
1744 }
1745 return copied;
1746}
1747
1749 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1750 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1751 m_destroy_callbacks.clear();
1753 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1754}
1755
1757 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1758 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1760 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1761 return token;
1762}
1763
1765 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1766 for (auto it = m_destroy_callbacks.begin(); it != m_destroy_callbacks.end();
1767 ++it) {
1768 if (it->token == token) {
1769 m_destroy_callbacks.erase(it);
1770 return true;
1771 }
1772 }
1773 return false;
1774}
1775
1776static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1777 std::string title, std::string details,
1778 uint64_t completed, uint64_t total,
1779 bool is_debugger_specific,
1780 uint32_t progress_broadcast_bit) {
1781 // Only deliver progress events if we have any progress listeners.
1782 if (!debugger.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit))
1783 return;
1784
1785 EventSP event_sp(new Event(
1786 progress_broadcast_bit,
1787 new ProgressEventData(progress_id, std::move(title), std::move(details),
1788 completed, total, is_debugger_specific)));
1789 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1790}
1791
1792void Debugger::ReportProgress(uint64_t progress_id, std::string title,
1793 std::string details, uint64_t completed,
1794 uint64_t total,
1795 std::optional<lldb::user_id_t> debugger_id,
1796 uint32_t progress_broadcast_bit) {
1797 // Check if this progress is for a specific debugger.
1798 if (debugger_id) {
1799 // It is debugger specific, grab it and deliver the event if the debugger
1800 // still exists.
1801 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1802 if (debugger_sp)
1803 PrivateReportProgress(*debugger_sp, progress_id, std::move(title),
1804 std::move(details), completed, total,
1805 /*is_debugger_specific*/ true,
1806 progress_broadcast_bit);
1807 return;
1808 }
1809 // The progress event is not debugger specific, iterate over all debuggers
1810 // and deliver a progress event to each one.
1811 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1812 if (g_debugger_list_ptr) {
1813 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1814 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1815 PrivateReportProgress(*(*pos), progress_id, title, details, completed,
1816 total, /*is_debugger_specific*/ false,
1817 progress_broadcast_bit);
1818 }
1819}
1820
1821static void PrivateReportDiagnostic(Debugger &debugger, Severity severity,
1822 std::string message,
1823 bool debugger_specific) {
1824 uint32_t event_type = 0;
1825 switch (severity) {
1826 case eSeverityInfo:
1827 assert(false && "eSeverityInfo should not be broadcast");
1828 return;
1829 case eSeverityWarning:
1830 event_type = lldb::eBroadcastBitWarning;
1831 break;
1832 case eSeverityError:
1833 event_type = lldb::eBroadcastBitError;
1834 break;
1835 }
1836
1837 Broadcaster &broadcaster = debugger.GetBroadcaster();
1838 if (!broadcaster.EventTypeHasListeners(event_type)) {
1839 // Diagnostics are too important to drop. If nobody is listening, print the
1840 // diagnostic directly to the debugger's error stream.
1841 DiagnosticEventData event_data(severity, std::move(message),
1842 debugger_specific);
1843 event_data.Dump(debugger.GetAsyncErrorStream().get());
1844 return;
1845 }
1846 EventSP event_sp = std::make_shared<Event>(
1847 event_type,
1848 new DiagnosticEventData(severity, std::move(message), debugger_specific));
1849 broadcaster.BroadcastEvent(event_sp);
1850}
1851
1852void Debugger::ReportDiagnosticImpl(Severity severity, std::string message,
1853 std::optional<lldb::user_id_t> debugger_id,
1854 std::once_flag *once) {
1855 auto ReportDiagnosticLambda = [&]() {
1856 // Always log diagnostics to the system log.
1857 Host::SystemLog(severity, message);
1858
1859 // The diagnostic subsystem is optional but we still want to broadcast
1860 // events when it's disabled.
1862 Diagnostics::Instance().Record(message);
1863
1864 // We don't broadcast info events.
1865 if (severity == lldb::eSeverityInfo)
1866 return;
1867
1868 // Check if this diagnostic is for a specific debugger.
1869 if (debugger_id) {
1870 // It is debugger specific, grab it and deliver the event if the debugger
1871 // still exists.
1872 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1873 if (debugger_sp)
1874 PrivateReportDiagnostic(*debugger_sp, severity, std::move(message),
1875 true);
1876 return;
1877 }
1878 // The diagnostic event is not debugger specific, iterate over all debuggers
1879 // and deliver a diagnostic event to each one.
1880 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1881 if (g_debugger_list_ptr) {
1882 for (const auto &debugger : *g_debugger_list_ptr)
1883 PrivateReportDiagnostic(*debugger, severity, message, false);
1884 }
1885 };
1886
1887 if (once)
1888 std::call_once(*once, ReportDiagnosticLambda);
1889 else
1890 ReportDiagnosticLambda();
1891}
1892
1893void Debugger::ReportWarning(std::string message,
1894 std::optional<lldb::user_id_t> debugger_id,
1895 std::once_flag *once) {
1896 ReportDiagnosticImpl(eSeverityWarning, std::move(message), debugger_id, once);
1897}
1898
1899void Debugger::ReportError(std::string message,
1900 std::optional<lldb::user_id_t> debugger_id,
1901 std::once_flag *once) {
1902 ReportDiagnosticImpl(eSeverityError, std::move(message), debugger_id, once);
1903}
1904
1905void Debugger::ReportInfo(std::string message,
1906 std::optional<lldb::user_id_t> debugger_id,
1907 std::once_flag *once) {
1908 ReportDiagnosticImpl(eSeverityInfo, std::move(message), debugger_id, once);
1909}
1910
1912 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1914 return;
1915
1916 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1917 EventSP event_sp = std::make_shared<Event>(
1919 new SymbolChangeEventData(debugger_sp, module_spec));
1920 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1921 }
1922}
1923
1924static std::shared_ptr<LogHandler>
1925CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1926 size_t buffer_size) {
1927 switch (log_handler_kind) {
1928 case eLogHandlerStream:
1929 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1931 return std::make_shared<RotatingLogHandler>(buffer_size);
1932 case eLogHandlerSystem:
1933 return std::make_shared<SystemLogHandler>();
1935 return {};
1936 }
1937 return {};
1938}
1939
1940llvm::Error Debugger::EnableLog(llvm::StringRef channel,
1941 llvm::ArrayRef<const char *> categories,
1942 llvm::StringRef log_file, uint32_t log_options,
1943 size_t buffer_size,
1944 LogHandlerKind log_handler_kind) {
1945
1946 std::shared_ptr<LogHandler> log_handler_sp;
1948 log_handler_sp = m_callback_handler_sp;
1949 // For now when using the callback mode you always get thread & timestamp.
1950 log_options |=
1952 } else if (log_file.empty()) {
1953 log_handler_sp =
1954 CreateLogHandler(log_handler_kind, GetOutputFileSP()->GetDescriptor(),
1955 /*should_close=*/false, buffer_size);
1956 } else {
1957 auto pos = m_stream_handlers.find(log_file);
1958 if (pos != m_stream_handlers.end())
1959 log_handler_sp = pos->second.lock();
1960 if (!log_handler_sp) {
1961 File::OpenOptions flags =
1963 if (log_options & LLDB_LOG_OPTION_APPEND)
1964 flags |= File::eOpenOptionAppend;
1965 else
1967 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1968 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1969 if (!file)
1970 return llvm::createStringErrorV("Unable to open log file '{}': {}",
1971 log_file,
1972 llvm::fmt_consume(file.takeError()));
1973
1974 log_handler_sp =
1975 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1976 /*should_close=*/true, buffer_size);
1977 m_stream_handlers[log_file] = log_handler_sp;
1978 }
1979 }
1980 assert(log_handler_sp);
1981
1982 if (log_options == 0)
1984
1985 return Log::EnableLogChannel(log_handler_sp, log_options, channel,
1986 categories);
1987}
1988
1991 std::optional<lldb::ScriptLanguage> language) {
1992 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1993 lldb::ScriptLanguage script_language =
1994 language ? *language : GetScriptLanguage();
1995
1996 if (!m_script_interpreters[script_language]) {
1997 if (!can_create)
1998 return nullptr;
1999 m_script_interpreters[script_language] =
2000 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
2001 }
2002
2003 return m_script_interpreters[script_language].get();
2004}
2005
2008 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2009 return *m_source_manager_up;
2010}
2011
2012// This function handles events that were broadcast by the process.
2014 using namespace lldb;
2015 const uint32_t event_type =
2017 event_sp);
2018
2019 // if (event_type & eBreakpointEventTypeAdded
2020 // || event_type & eBreakpointEventTypeRemoved
2021 // || event_type & eBreakpointEventTypeEnabled
2022 // || event_type & eBreakpointEventTypeDisabled
2023 // || event_type & eBreakpointEventTypeCommandChanged
2024 // || event_type & eBreakpointEventTypeConditionChanged
2025 // || event_type & eBreakpointEventTypeIgnoreChanged
2026 // || event_type & eBreakpointEventTypeLocationsResolved)
2027 // {
2028 // // Don't do anything about these events, since the breakpoint
2029 // commands already echo these actions.
2030 // }
2031 //
2032 if (event_type & eBreakpointEventTypeLocationsAdded) {
2033 uint32_t num_new_locations =
2035 event_sp);
2036 if (num_new_locations > 0) {
2037 BreakpointSP breakpoint =
2039 if (StreamUP output_up = GetAsyncOutputStream()) {
2040 output_up->Printf("%d location%s added to breakpoint %d\n",
2041 num_new_locations, num_new_locations == 1 ? "" : "s",
2042 breakpoint->GetID());
2043 output_up->Flush();
2044 }
2045 }
2046 }
2047 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
2048 // {
2049 // // These locations just get disabled, not sure it is worth spamming
2050 // folks about this on the command line.
2051 // }
2052 // else if (event_type & eBreakpointEventTypeLocationsResolved)
2053 // {
2054 // // This might be an interesting thing to note, but I'm going to
2055 // leave it quiet for now, it just looked noisy.
2056 // }
2057}
2058
2059void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
2060 bool flush_stderr) {
2061 const auto &flush = [&](Stream &stream,
2062 size_t (Process::*get)(char *, size_t, Status &)) {
2063 Status error;
2064 size_t len;
2065 char buffer[1024];
2066 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
2067 stream.Write(buffer, len);
2068 stream.Flush();
2069 };
2070
2071 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
2072 if (flush_stdout)
2074 if (flush_stderr)
2076}
2077
2078// This function handles events that were broadcast by the process.
2080 const uint32_t event_type = event_sp->GetType();
2081 ProcessSP process_sp =
2085
2086 StreamUP output_stream_up = GetAsyncOutputStream();
2087 StreamUP error_stream_up = GetAsyncErrorStream();
2088 const bool gui_enabled = IsForwardingEvents();
2089
2090 if (!gui_enabled) {
2091 bool pop_process_io_handler = false;
2092 assert(process_sp);
2093
2094 bool state_is_stopped = false;
2095 const bool got_state_changed =
2096 (event_type & Process::eBroadcastBitStateChanged) != 0;
2097 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
2098 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
2099 const bool got_structured_data =
2100 (event_type & Process::eBroadcastBitStructuredData) != 0;
2101
2102 if (got_state_changed) {
2103 StateType event_state =
2105 state_is_stopped = StateIsStoppedState(event_state, false);
2106 }
2107
2108 // Display running state changes first before any STDIO
2109 if (got_state_changed && !state_is_stopped) {
2110 // This is a public stop which we are going to announce to the user, so
2111 // we should force the most relevant frame selection here.
2112 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2114 pop_process_io_handler);
2115 }
2116
2117 // Now display STDOUT and STDERR
2118 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
2119 got_stderr || got_state_changed);
2120
2121 // Give structured data events an opportunity to display.
2122 if (got_structured_data) {
2123 StructuredDataPluginSP plugin_sp =
2125 if (plugin_sp) {
2126 auto structured_data_sp =
2128 StreamString content_stream;
2129 Status error =
2130 plugin_sp->GetDescription(structured_data_sp, content_stream);
2131 if (error.Success()) {
2132 if (!content_stream.GetString().empty()) {
2133 // Add newline.
2134 content_stream.PutChar('\n');
2135 content_stream.Flush();
2136
2137 // Print it.
2138 output_stream_up->PutCString(content_stream.GetString());
2139 }
2140 } else {
2141 error_stream_up->Format("Failed to print structured "
2142 "data with plugin {0}: {1}",
2143 plugin_sp->GetPluginName(), error);
2144 }
2145 }
2146 }
2147
2148 // Now display any stopped state changes after any STDIO
2149 if (got_state_changed && state_is_stopped) {
2150 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2152 pop_process_io_handler);
2153 }
2154
2155 output_stream_up->Flush();
2156 error_stream_up->Flush();
2157
2158 if (pop_process_io_handler)
2159 process_sp->PopProcessIOHandler();
2160 }
2161 return process_sp;
2162}
2163
2165 // At present the only thread event we handle is the Frame Changed event, and
2166 // all we do for that is just reprint the thread status for that thread.
2167 const uint32_t event_type = event_sp->GetType();
2168 const bool stop_format = true;
2169 ThreadSP thread_sp;
2170 if (event_type == Thread::eBroadcastBitStackChanged ||
2172 thread_sp = Thread::ThreadEventData::GetThreadFromEvent(event_sp.get());
2173 if (thread_sp) {
2174 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format,
2175 /*show_hidden*/ true);
2176 }
2177 }
2178 return thread_sp;
2179}
2180
2182
2184 m_forward_listener_sp = listener_sp;
2185}
2186
2188 m_forward_listener_sp.reset();
2189}
2190
2191/// Conservative heuristic to detect whether OSC 9;4 progress is supported by
2192/// the current terminal.
2194#if defined(_WIN32)
2195 // On Windows, we assume that the user is using the Windows Terminal.
2196 return true;
2197#else
2198 static std::once_flag g_once_flag;
2199 static bool g_supports_osc_progress = false;
2200
2201 std::call_once(g_once_flag, []() {
2202 // Check TERM_PROGRAM for known supported terminals. This can lead to false
2203 // negatives, for example when using tmux.
2204 if (const char *term_program = std::getenv("TERM_PROGRAM")) {
2205 llvm::StringRef term_program_str(term_program);
2206 if (term_program_str.starts_with("ghostty") ||
2207 term_program_str.starts_with("wezterm")) {
2208 g_supports_osc_progress = true;
2209 return;
2210 }
2211 }
2212
2213 // Check other known environment variables.
2214 std::array<const char *, 3> known_env_vars = {
2215 "ConEmuPID", // https://conemu.github.io/en/ConEmuEnvironment.html
2216 "GHOSTTY_RESOURCES_DIR", // https://ghostty.org/docs/features/shell-integration
2217 "OSC_PROGRESS", // LLDB specific override.
2218 };
2219 for (const char *env_var : known_env_vars) {
2220 if (std::getenv(env_var)) {
2221 g_supports_osc_progress = true;
2222 return;
2223 }
2224 }
2225 });
2226
2227 return g_supports_osc_progress;
2228#endif
2229}
2230
2233 File &file = stream_sp->GetUnlockedFile();
2234 return file.GetIsInteractive() && file.GetIsRealTerminal() &&
2236 }
2237 return false;
2238}
2239
2241// We have trouble with the contol codes on Windows, see
2242// https://github.com/llvm/llvm-project/issues/134846.
2243#ifndef _WIN32
2245#else
2246 return false;
2247#endif
2248}
2249
2250static bool RequiresFollowChildWorkaround(const Process &process) {
2251 // FIXME: https://github.com/llvm/llvm-project/issues/160216
2252 return process.GetFollowForkMode() == eFollowChild;
2253}
2254
2256 ListenerSP listener_sp(GetListener());
2257 llvm::StringRef broadcaster_class_target(Target::GetStaticBroadcasterClass());
2258 llvm::StringRef broadcaster_class_process(
2260 llvm::StringRef broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
2261 BroadcastEventSpec target_event_spec(broadcaster_class_target,
2263
2264 BroadcastEventSpec process_event_spec(
2265 broadcaster_class_process,
2268
2269 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
2272
2273 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2274 target_event_spec);
2275 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2276 process_event_spec);
2277 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2278 thread_event_spec);
2279 listener_sp->StartListeningForEvents(
2284
2285 listener_sp->StartListeningForEvents(
2290
2291 // Let the thread that spawned us know that we have started up and that we
2292 // are now listening to all required events so no events get missed
2294
2295 if (StatuslineSupported()) {
2296 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2297 if (!m_statusline) {
2298 m_statusline.emplace(*this);
2299 m_statusline->Enable(
2300 GetSelectedExecutionContextRef(/*adopt_dummy_target=*/true));
2301 }
2302 }
2303
2304 bool done = false;
2305 while (!done) {
2306 EventSP event_sp;
2307 if (listener_sp->GetEvent(event_sp, std::nullopt)) {
2308 std::optional<ExecutionContextRef> exe_ctx_ref = std::nullopt;
2309 if (event_sp) {
2310 Broadcaster *broadcaster = event_sp->GetBroadcaster();
2311 if (broadcaster) {
2312 uint32_t event_type = event_sp->GetType();
2313 llvm::StringRef broadcaster_class(broadcaster->GetBroadcasterClass());
2314 if (broadcaster_class == broadcaster_class_process) {
2315 if (ProcessSP process_sp = HandleProcessEvent(event_sp)) {
2316 // Don't pass adopt_selected = true if this is a stop for an
2317 // auto-continue event (e.g. an auto-continue breakpoint). We
2318 // would be fetching stale state, since the process resumed since
2319 // this event, and we'd needlessly interrupt the target to do so.
2320 const bool adopt_selected =
2321 process_sp->GetPrivateState() == eStateStopped &&
2323 event_sp.get());
2324 if (!RequiresFollowChildWorkaround(*process_sp))
2325 exe_ctx_ref =
2326 ExecutionContextRef(process_sp.get(), adopt_selected);
2327 }
2328 } else if (broadcaster_class == broadcaster_class_target) {
2330 event_sp.get())) {
2331 HandleBreakpointEvent(event_sp);
2332 }
2333 } else if (broadcaster_class == broadcaster_class_thread) {
2334 if (ThreadSP thread_sp = HandleThreadEvent(event_sp))
2335 if (!RequiresFollowChildWorkaround(*thread_sp->GetProcess()))
2336 exe_ctx_ref = ExecutionContextRef(thread_sp.get(),
2337 /*adopt_selected=*/true);
2338 } else if (broadcaster == m_command_interpreter_up.get()) {
2339 if (event_type &
2341 done = true;
2342 } else if (event_type &
2344 const char *data = static_cast<const char *>(
2345 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2346 if (data && data[0]) {
2347 StreamUP error_up = GetAsyncErrorStream();
2348 error_up->PutCString(data);
2349 error_up->Flush();
2350 }
2351 } else if (event_type & CommandInterpreter::
2352 eBroadcastBitAsynchronousOutputData) {
2353 const char *data = static_cast<const char *>(
2354 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2355 if (data && data[0]) {
2356 StreamUP output_up = GetAsyncOutputStream();
2357 output_up->PutCString(data);
2358 output_up->Flush();
2359 }
2360 }
2361 } else if (broadcaster == &m_broadcaster) {
2362 if (event_type & lldb::eBroadcastBitProgress ||
2364 HandleProgressEvent(event_sp);
2365 else if (event_type & lldb::eBroadcastBitWarning)
2366 HandleDiagnosticEvent(event_sp);
2367 else if (event_type & lldb::eBroadcastBitError)
2368 HandleDiagnosticEvent(event_sp);
2369 }
2370 }
2371
2373 m_forward_listener_sp->AddEvent(event_sp);
2374 }
2375 RedrawStatusline(exe_ctx_ref);
2376 }
2377 }
2378
2379 {
2380 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2381 if (m_statusline)
2382 m_statusline.reset();
2383 }
2384
2385 return {};
2386}
2387
2389 if (!m_event_handler_thread.IsJoinable()) {
2390 // We must synchronize with the DefaultEventHandler() thread to ensure it
2391 // is up and running and listening to events before we return from this
2392 // function. We do this by listening to events for the
2393 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2394 llvm::StringRef full_name("lldb.debugger.event-handler");
2395 ListenerSP listener_sp(Listener::MakeListener(full_name));
2396 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
2398
2399 llvm::StringRef thread_name =
2400 full_name.size() < llvm::get_max_thread_name_length()
2401 ? full_name
2402 : "dbg.evt-handler";
2403
2404 // Use larger 8MB stack for this thread
2405 llvm::Expected<HostThread> event_handler_thread =
2407 thread_name, [this] { return DefaultEventHandler(); },
2409
2410 if (event_handler_thread) {
2411 m_event_handler_thread = *event_handler_thread;
2412 } else {
2413 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(),
2414 "failed to launch host thread: {0}");
2415 }
2416
2417 // Make sure DefaultEventHandler() is running and listening to events
2418 // before we return from this function. We are only listening for events of
2419 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2420 // event, we just need to wait an infinite amount of time for it (nullptr
2421 // timeout as the first parameter)
2422 lldb::EventSP event_sp;
2423 listener_sp->GetEvent(event_sp, std::nullopt);
2424 }
2425 return m_event_handler_thread.IsJoinable();
2426}
2427
2435
2441
2443 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
2444 if (!data)
2445 return;
2446
2447 // Make a local copy of the incoming progress report that we'll store.
2448 ProgressReport progress_report{data->GetID(), data->GetCompleted(),
2449 data->GetTotal(), data->GetMessage()};
2450
2451 {
2452 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2453
2454 // Do some bookkeeping regardless of whether we're going to display
2455 // progress reports.
2456 auto it = llvm::find_if(m_progress_reports, [&](const auto &report) {
2457 return report.id == progress_report.id;
2458 });
2459 if (it != m_progress_reports.end()) {
2460 const bool complete = data->GetCompleted() == data->GetTotal();
2461 if (complete)
2462 m_progress_reports.erase(it);
2463 else
2464 *it = progress_report;
2465 } else {
2466 m_progress_reports.push_back(progress_report);
2467 }
2468
2469 // Show progress using Operating System Command (OSC) sequences.
2473
2474 // Clear progress if this was the last progress event.
2475 if (m_progress_reports.empty()) {
2476 stream_sp->Lock() << OSC_PROGRESS_REMOVE;
2477 return;
2478 }
2479
2480 const ProgressReport &report = m_progress_reports.back();
2481
2482 // Show indeterminate progress.
2483 if (report.total == UINT64_MAX) {
2484 stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE;
2485 return;
2486 }
2487
2488 // Compute and show the progress value (0-100).
2489 const unsigned value = (report.completed / report.total) * 100;
2490 stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value);
2491 }
2492 }
2493 }
2494}
2495
2496std::optional<Debugger::ProgressReport>
2498 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2499 if (m_progress_reports.empty())
2500 return std::nullopt;
2501 return m_progress_reports.back();
2502}
2503
2505 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
2506 if (!data)
2507 return;
2508
2509 data->Dump(GetAsyncErrorStream().get());
2510}
2511
2513 return m_io_handler_thread.IsJoinable();
2514}
2515
2518 m_io_handler_thread = new_thread;
2519 return old_host;
2520}
2521
2523 if (!m_io_handler_thread.IsJoinable()) {
2524 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
2525 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2526 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2527 if (io_handler_thread) {
2528 m_io_handler_thread = *io_handler_thread;
2529 } else {
2530 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(),
2531 "failed to launch host thread: {0}");
2532 }
2533 }
2534 return m_io_handler_thread.IsJoinable();
2535}
2536
2538 if (m_io_handler_thread.IsJoinable()) {
2539 GetInputFile().Close();
2540 m_io_handler_thread.Join(nullptr);
2541 }
2542}
2543
2551
2553 if (!HasIOHandlerThread())
2554 return false;
2555 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread());
2556}
2557
2559 if (!prefer_dummy) {
2560 if (TargetSP class="code hl_variable" href="classlldb__private_1_1Debugger.html#aa05f5fc946265727cf3fa3f765e845df">m_target_list.GetSelectedTarget())
2561 return *target;
2562 }
2563 return GetDummyTarget();
2564}
2565
2566Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
2567 Status err;
2568 FileSpec repl_executable;
2569
2570 if (language == eLanguageTypeUnknown)
2571 language = GetREPLLanguage();
2572
2573 if (language == eLanguageTypeUnknown) {
2575
2576 if (auto single_lang = repl_languages.GetSingularLanguage()) {
2577 language = *single_lang;
2578 } else if (repl_languages.Empty()) {
2580 "LLDB isn't configured with REPL support for any languages.");
2581 return err;
2582 } else {
2584 "Multiple possible REPL languages. Please specify a language.");
2585 return err;
2586 }
2587 }
2588
2589 Target *const>
2590 nullptr; // passing in an empty target means the REPL must create one
2591
2592 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2593
2594 if (!err.Success()) {
2595 return err;
2596 }
2597
2598 if (!repl_sp) {
2600 "couldn't find a REPL for %s",
2602 return err;
2603 }
2604
2605 repl_sp->SetCompilerOptions(repl_options);
2606 repl_sp->RunLoop();
2607
2608 return err;
2609}
2610
2611llvm::ThreadPoolInterface &Debugger::GetThreadPool() {
2612 assert(g_thread_pool &&
2613 "Debugger::GetThreadPool called before Debugger::Initialize");
2614 return *g_thread_pool;
2615}
2616
2618 llvm::StringRef name, bool value,
2619 llvm::StringRef description) {
2620 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2621 entry_up->AddBooleanItem("value", value);
2622 entry_up->AddStringItem("description", description);
2623 dict.AddItem(name, std::move(entry_up));
2624}
2625
2627 auto array_up = std::make_unique<StructuredData::Array>();
2628#define LLVM_TARGET(target) \
2629 array_up->AddItem(std::make_unique<StructuredData::String>(#target));
2630#include "llvm/Config/Targets.def"
2631 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2632 entry_up->AddItem("value", std::move(array_up));
2633 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
2634 dict.AddItem("targets", std::move(entry_up));
2635}
2636
2638 auto config_up = std::make_unique<StructuredData::Dictionary>();
2640 *config_up, "xml", XMLDocument::XMLEnabled(),
2641 "A boolean value that indicates if XML support is enabled in LLDB");
2643 *config_up, "curl", LLVM_ENABLE_CURL,
2644 "A boolean value that indicates if CURL support is enabled in LLDB");
2646 *config_up, "curses", LLDB_ENABLE_CURSES,
2647 "A boolean value that indicates if curses support is enabled in LLDB");
2649 *config_up, "editline", LLDB_ENABLE_LIBEDIT,
2650 "A boolean value that indicates if editline support is enabled in LLDB");
2651 AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,
2652 "A boolean value that indicates if editline wide "
2653 "characters support is enabled in LLDB");
2655 *config_up, "zlib", LLVM_ENABLE_ZLIB,
2656 "A boolean value that indicates if zlib support is enabled in LLDB");
2658 *config_up, "lzma", LLVM_ENABLE_LZMA,
2659 "A boolean value that indicates if lzma support is enabled in LLDB");
2661 *config_up, "python", LLDB_ENABLE_PYTHON,
2662 "A boolean value that indicates if python support is enabled in LLDB");
2664 *config_up, "lua", LLDB_ENABLE_LUA,
2665 "A boolean value that indicates if lua support is enabled in LLDB");
2666 AddLLVMTargets(*config_up);
2667 return config_up;
2668}
#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:552
InterruptionReport(std::string function_name, std::string description)
Definition Debugger.h:534
A class to manage flag bits.
Definition Debugger.h:103
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:802
HostThread m_event_handler_thread
Definition Debugger.h:835
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:788
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:830
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:158
bool GetHighlightSource() const
Definition Debugger.cpp:718
llvm::StringMap< std::weak_ptr< LogHandler > > m_stream_handlers
Definition Debugger.h:828
llvm::StringRef GetLabelAnsiSuffix() const
Definition Debugger.cpp:587
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:185
FormatEntity::Entry GetStatuslineFormat() const
Definition Debugger.cpp:623
llvm::StringRef GetDividerAnsiPrefix() const
Definition Debugger.cpp:605
LoadedPluginsList m_loaded_plugins
Definition Debugger.h:834
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:803
void PushIOHandler(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
std::mutex m_destroy_callback_mutex
Definition Debugger.h:849
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:798
lldb::StreamUP GetAsyncErrorStream()
bool GetEscapeNonPrintables() const
Definition Debugger.cpp:781
lldb::TargetSP m_dummy_target_sp
Definition Debugger.h:841
llvm::SmallVector< DestroyCallbackInfo, 2 > m_destroy_callbacks
Definition Debugger.h:861
std::unique_ptr< CommandInterpreter > m_command_interpreter_up
Definition Debugger.h:813
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:790
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:845
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:846
lldb::ProcessSP HandleProcessEvent(const lldb::EventSP &event_sp)
lldb::ListenerSP m_forward_listener_sp
Definition Debugger.h:839
std::array< lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown > m_script_interpreters
Definition Debugger.h:817
std::atomic< bool > m_flush_statusline
Raised by FlushStatusLine to request a flush at the next redraw.
Definition Debugger.h:826
std::shared_ptr< CallbackLogHandler > m_callback_handler_sp
Definition Debugger.h:829
void SetDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback, void *baton)
DEPRECATED: We used to only support one Destroy callback.
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:161
Broadcaster m_broadcaster
Public Debugger event broadcaster.
Definition Debugger.h:838
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:864
std::recursive_mutex m_io_handler_synchronous_mutex
Definition Debugger.h:820
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:824
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:792
void FlushStatusLine()
Discard the statusline's cached frame at its next redraw.
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:832
bool GetShowStatusline() const
Definition Debugger.cpp:617
std::recursive_mutex m_script_interpreter_mutex
Definition Debugger.h:815
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:742
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:837
llvm::StringRef GetTitleAnsiSuffix() const
Definition Debugger.cpp:599
bool GetUseSourceCache() const
Definition Debugger.cpp:697
HostThread m_io_handler_thread
Definition Debugger.h:836
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:685
static llvm::StringRef GetStaticBroadcasterClass()
lldb::FileSP m_input_file_sp
Definition Debugger.h:787
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:799
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:458
lldb::callback_token_t m_destroy_callback_next_token
Definition Debugger.h:850
std::unique_ptr< SourceManager > m_source_manager_up
Definition Debugger.h:804
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:789
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:567
TargetGroupList m_target_group_list
Definition Debugger.h:800
lldb::ListenerSP GetListener()
Definition Debugger.h:194
static void Destroy(lldb::DebuggerSP &debugger_sp)
SourceManager::SourceFileCache m_source_file_cache
Definition Debugger.h:808
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:110
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:782
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:823
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:819
llvm::once_flag m_clear_once
Definition Debugger.h:840
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:863
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:743
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:105
bool SetAutoIndent(bool b)
Definition Debugger.cpp:793
friend class CommandInterpreter
Definition Debugger.h:689
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:47
static LanguageSet GetLanguagesSupportingREPLs()
Definition Language.cpp:518
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:334
static LanguageProperties & GetGlobalLanguageProperties()
Definition Language.cpp:42
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:4810
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4794
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4802
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:4997
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4978
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:1365
static void SettingsTerminate()
Definition Target.cpp:2935
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:177
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3485
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2945
@ eBroadcastBitBreakpointChanged
Definition Target.h:610
static void SettingsInitialize()
Definition Target.cpp:2933
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:64
@ eLoadScriptFromSymFileTrue
Definition Target.h:65
@ eLoadScriptFromSymFileFalse
Definition Target.h:66
@ eLoadScriptFromSymFileWarn
Definition Target.h:67
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:858
A SmallBitVector that represents a set of source languages (lldb::LanguageType).
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