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