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