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