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);
331 m_statusline->Enable(
332 GetSelectedExecutionContextRef(/*adopt_dummy_target=*/true));
333 } else {
334 m_statusline.reset();
335 }
336 } else if (property_path ==
337 g_debugger_properties[ePropertyStatuslineFormat].name ||
338 property_path ==
339 g_debugger_properties[ePropertySeparator].name) {
340 // Statusline format changed. Redraw the statusline.
341 RedrawStatusline(std::nullopt);
342 } else if (property_path ==
343 g_debugger_properties[ePropertyUseSourceCache].name) {
344 // use-source-cache changed. Wipe out the cache contents if it was
345 // disabled.
346 if (!GetUseSourceCache()) {
347 m_source_file_cache.Clear();
348 }
349 } else if (is_load_script && target_sp &&
350 load_script_old_value == eLoadScriptFromSymFileWarn) {
351 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
353 std::list<Status> errors;
354 if (!target_sp->LoadScriptingResources(errors)) {
356 for (auto &error : errors)
357 s->Printf("%s\n", error.AsCString());
358 }
359 }
360 }
361 }
362 return error;
363}
364
366 constexpr uint32_t idx = ePropertyAutoConfirm;
368 idx, g_debugger_properties[idx].default_uint_value != 0);
369}
370
372 constexpr uint32_t idx = ePropertyDisassemblyFormat;
374}
375
377 constexpr uint32_t idx = ePropertyFrameFormat;
379}
380
382 constexpr uint32_t idx = ePropertyFrameFormatUnique;
384}
385
387 constexpr uint32_t idx = ePropertyStopDisassemblyMaxSize;
389 idx, g_debugger_properties[idx].default_uint_value);
390}
391
393 constexpr uint32_t idx = ePropertyNotiftVoid;
395 idx, g_debugger_properties[idx].default_uint_value != 0);
396}
397
398llvm::StringRef Debugger::GetPrompt() const {
399 constexpr uint32_t idx = ePropertyPrompt;
401 idx, g_debugger_properties[idx].default_cstr_value);
402}
403
404llvm::StringRef Debugger::GetPromptAnsiPrefix() const {
405 const uint32_t idx = ePropertyPromptAnsiPrefix;
407 idx, g_debugger_properties[idx].default_cstr_value);
408}
409
410llvm::StringRef Debugger::GetPromptAnsiSuffix() const {
411 const uint32_t idx = ePropertyPromptAnsiSuffix;
413 idx, g_debugger_properties[idx].default_cstr_value);
414}
415
416void Debugger::SetPrompt(llvm::StringRef p) {
417 constexpr uint32_t idx = ePropertyPrompt;
418 SetPropertyAtIndex(idx, p);
419 llvm::StringRef new_prompt = GetPrompt();
420 std::string str =
422 if (str.length())
423 new_prompt = str;
425}
426
428 constexpr uint32_t idx = ePropertyThreadFormat;
430}
431
433 constexpr uint32_t idx = ePropertyThreadStopFormat;
435}
436
438 const uint32_t idx = ePropertyScriptLanguage;
440 idx, static_cast<lldb::ScriptLanguage>(
441 g_debugger_properties[idx].default_uint_value));
442}
443
445 const uint32_t idx = ePropertyScriptLanguage;
446 return SetPropertyAtIndex(idx, script_lang);
447}
448
450 const uint32_t idx = ePropertyREPLLanguage;
452}
453
455 const uint32_t idx = ePropertyREPLLanguage;
456 return SetPropertyAtIndex(idx, repl_lang);
457}
458
460 const uint32_t idx = ePropertyTerminalWidth;
462 idx, g_debugger_properties[idx].default_uint_value);
463}
464
465bool Debugger::SetTerminalWidth(uint64_t term_width) {
466 const uint32_t idx = ePropertyTerminalWidth;
467 const bool success = SetPropertyAtIndex(idx, term_width);
468
469 if (auto handler_sp = m_io_handler_stack.Top())
470 handler_sp->TerminalSizeChanged();
471
472 {
473 std::lock_guard<std::mutex> guard(m_statusline_mutex);
474 if (m_statusline)
475 m_statusline->TerminalSizeChanged();
476 }
477
478 return success;
479}
480
482 const uint32_t idx = ePropertyTerminalHeight;
484 idx, g_debugger_properties[idx].default_uint_value);
485}
486
487bool Debugger::SetTerminalHeight(uint64_t term_height) {
488 const uint32_t idx = ePropertyTerminalHeight;
489 const bool success = SetPropertyAtIndex(idx, term_height);
490
491 if (auto handler_sp = m_io_handler_stack.Top())
492 handler_sp->TerminalSizeChanged();
493
494 {
495 std::lock_guard<std::mutex> guard(m_statusline_mutex);
496 if (m_statusline)
497 m_statusline->TerminalSizeChanged();
498 }
499
500 return success;
501}
502
504 const uint32_t idx = ePropertyUseExternalEditor;
506 idx, g_debugger_properties[idx].default_uint_value != 0);
507}
508
510 const uint32_t idx = ePropertyUseExternalEditor;
511 return SetPropertyAtIndex(idx, b);
512}
513
514llvm::StringRef Debugger::GetExternalEditor() const {
515 const uint32_t idx = ePropertyExternalEditor;
517 idx, g_debugger_properties[idx].default_cstr_value);
518}
519
520bool Debugger::SetExternalEditor(llvm::StringRef editor) {
521 const uint32_t idx = ePropertyExternalEditor;
522 return SetPropertyAtIndex(idx, editor);
523}
524
526 const uint32_t idx = ePropertyUseColor;
528 idx, g_debugger_properties[idx].default_uint_value != 0);
529}
530
532 const uint32_t idx = ePropertyUseColor;
533 bool ret = SetPropertyAtIndex(idx, b);
534
537 return ret;
538}
539
541 const uint32_t idx = ePropertyShowProgress;
543 idx, g_debugger_properties[idx].default_uint_value != 0);
544}
545
546bool Debugger::SetShowProgress(bool show_progress) {
547 const uint32_t idx = ePropertyShowProgress;
548 return SetPropertyAtIndex(idx, show_progress);
549}
550
551llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const {
552 const uint32_t idx = ePropertyShowProgressAnsiPrefix;
554 idx, g_debugger_properties[idx].default_cstr_value);
555}
556
557llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const {
558 const uint32_t idx = ePropertyShowProgressAnsiSuffix;
560 idx, g_debugger_properties[idx].default_cstr_value);
561}
562
564 const uint32_t idx = ePropertyShowStatusline;
566 idx, g_debugger_properties[idx].default_uint_value != 0);
567}
568
570 constexpr uint32_t idx = ePropertyStatuslineFormat;
572}
573
575 constexpr uint32_t idx = ePropertyStatuslineFormat;
576 bool ret = SetPropertyAtIndex(idx, format);
577 RedrawStatusline(std::nullopt);
578 return ret;
579}
580
581llvm::StringRef Debugger::GetSeparator() const {
582 constexpr uint32_t idx = ePropertySeparator;
584 idx, g_debugger_properties[idx].default_cstr_value);
585}
586
587llvm::StringRef Debugger::GetDisabledAnsiPrefix() const {
588 const uint32_t idx = ePropertyShowDisabledAnsiPrefix;
590 idx, g_debugger_properties[idx].default_cstr_value);
591}
592
593llvm::StringRef Debugger::GetDisabledAnsiSuffix() const {
594 const uint32_t idx = ePropertyShowDisabledAnsiSuffix;
596 idx, g_debugger_properties[idx].default_cstr_value);
597}
598
599bool Debugger::SetSeparator(llvm::StringRef s) {
600 constexpr uint32_t idx = ePropertySeparator;
601 bool ret = SetPropertyAtIndex(idx, s);
602 RedrawStatusline(std::nullopt);
603 return ret;
604}
605
607 const uint32_t idx = ePropertyShowAutosuggestion;
609 idx, g_debugger_properties[idx].default_uint_value != 0);
610}
611
613 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix;
615 idx, g_debugger_properties[idx].default_cstr_value);
616}
617
619 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix;
621 idx, g_debugger_properties[idx].default_cstr_value);
622}
623
624llvm::StringRef Debugger::GetRegexMatchAnsiPrefix() const {
625 const uint32_t idx = ePropertyShowRegexMatchAnsiPrefix;
627 idx, g_debugger_properties[idx].default_cstr_value);
628}
629
630llvm::StringRef Debugger::GetRegexMatchAnsiSuffix() const {
631 const uint32_t idx = ePropertyShowRegexMatchAnsiSuffix;
633 idx, g_debugger_properties[idx].default_cstr_value);
634}
635
637 const uint32_t idx = ePropertyShowDontUsePoHint;
639 idx, g_debugger_properties[idx].default_uint_value != 0);
640}
641
643 const uint32_t idx = ePropertyUseSourceCache;
645 idx, g_debugger_properties[idx].default_uint_value != 0);
646}
647
649 const uint32_t idx = ePropertyUseSourceCache;
650 bool ret = SetPropertyAtIndex(idx, b);
651 if (!ret) {
652 m_source_file_cache.Clear();
653 }
654 return ret;
655}
656
658 const uint32_t idx = ePropertyMarkHiddenFrames;
660 idx, g_debugger_properties[idx].default_uint_value != 0);
661}
662
664 const uint32_t idx = ePropertyHighlightSource;
666 idx, g_debugger_properties[idx].default_uint_value != 0);
667}
668
670 const uint32_t idx = ePropertyStopShowColumn;
672 idx, static_cast<lldb::StopShowColumn>(
673 g_debugger_properties[idx].default_uint_value));
674}
675
677 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
679 idx, g_debugger_properties[idx].default_cstr_value);
680}
681
683 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
685 idx, g_debugger_properties[idx].default_cstr_value);
686}
687
689 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
691 idx, g_debugger_properties[idx].default_cstr_value);
692}
693
695 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
697 idx, g_debugger_properties[idx].default_cstr_value);
698}
699
700uint64_t Debugger::GetStopSourceLineCount(bool before) const {
701 const uint32_t idx =
702 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
704 idx, g_debugger_properties[idx].default_uint_value);
705}
706
708 const uint32_t idx = ePropertyStopDisassemblyDisplay;
710 idx, static_cast<lldb::StopDisassemblyType>(
711 g_debugger_properties[idx].default_uint_value));
712}
713
715 const uint32_t idx = ePropertyStopDisassemblyCount;
717 idx, g_debugger_properties[idx].default_uint_value);
718}
719
721 const uint32_t idx = ePropertyAutoOneLineSummaries;
723 idx, g_debugger_properties[idx].default_uint_value != 0);
724}
725
727 const uint32_t idx = ePropertyEscapeNonPrintables;
729 idx, g_debugger_properties[idx].default_uint_value != 0);
730}
731
733 const uint32_t idx = ePropertyAutoIndent;
735 idx, g_debugger_properties[idx].default_uint_value != 0);
736}
737
739 const uint32_t idx = ePropertyAutoIndent;
740 return SetPropertyAtIndex(idx, b);
741}
742
744 const uint32_t idx = ePropertyPrintDecls;
746 idx, g_debugger_properties[idx].default_uint_value != 0);
747}
748
750 const uint32_t idx = ePropertyPrintDecls;
751 return SetPropertyAtIndex(idx, b);
752}
753
754uint64_t Debugger::GetTabSize() const {
755 const uint32_t idx = ePropertyTabSize;
757 idx, g_debugger_properties[idx].default_uint_value);
758}
759
760bool Debugger::SetTabSize(uint64_t tab_size) {
761 const uint32_t idx = ePropertyTabSize;
762 return SetPropertyAtIndex(idx, tab_size);
763}
764
766 const uint32_t idx = ePropertyDWIMPrintVerbosity;
768 idx, static_cast<lldb::DWIMPrintVerbosity>(
769 g_debugger_properties[idx].default_uint_value != 0));
770}
771
773 const uint32_t idx = ePropertyShowInlineDiagnostics;
775 idx, g_debugger_properties[idx].default_uint_value);
776}
777
779 const uint32_t idx = ePropertyShowInlineDiagnostics;
780 return SetPropertyAtIndex(idx, b);
781}
782
783#pragma mark Debugger
784
785// const DebuggerPropertiesSP &
786// Debugger::GetSettings() const
787//{
788// return m_properties_sp;
789//}
790//
791
793 assert(g_debugger_list_ptr == nullptr &&
794 "Debugger::Initialize called more than once!");
795 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
797 g_thread_pool = new llvm::DefaultThreadPool(llvm::optimal_concurrency());
798 g_load_plugin_callback = load_plugin_callback;
799}
800
802 assert(g_debugger_list_ptr &&
803 "Debugger::Terminate called without a matching Debugger::Initialize!");
804
805 {
806 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
808 for (const auto &debugger : *g_debugger_list_ptr)
809 debugger->HandleDestroyCallback();
810 }
811
812 if (g_thread_pool) {
813 // The destructor will wait for all the threads to complete.
814 delete g_thread_pool;
815 }
816
817 {
818 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
820 for (const DebuggerSP &debugger : *g_debugger_list_ptr)
821 debugger->Clear();
822 g_debugger_list_ptr->clear();
823
824 delete g_debugger_list_ptr;
825 g_debugger_list_ptr = nullptr;
826 }
827 }
828}
829
831
833
836 llvm::sys::DynamicLibrary dynlib =
837 g_load_plugin_callback(shared_from_this(), spec, error);
838 if (dynlib.isValid()) {
839 m_loaded_plugins.push_back(dynlib);
840 return true;
841 }
842 } else {
843 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
844 // if the public API layer isn't available (code is linking against all of
845 // the internal LLDB static libraries), then we can't load plugins
846 error = Status::FromErrorString("Public API layer is not available");
847 }
848 return false;
849}
850
852LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
853 llvm::StringRef path) {
855
856 static constexpr llvm::StringLiteral g_dylibext(".dylib");
857 static constexpr llvm::StringLiteral g_solibext(".so");
858
859 if (!baton)
861
862 Debugger *debugger = (Debugger *)baton;
863
864 namespace fs = llvm::sys::fs;
865 // If we have a regular file, a symbolic link or unknown file type, try and
866 // process the file. We must handle unknown as sometimes the directory
867 // enumeration might be enumerating a file system that doesn't have correct
868 // file type information.
869 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
870 ft == fs::file_type::type_unknown) {
871 FileSpec plugin_file_spec(path);
872 FileSystem::Instance().Resolve(plugin_file_spec);
873
874 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
875 plugin_file_spec.GetFileNameExtension() != g_solibext) {
877 }
878
879 Status plugin_load_error;
880 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
881
883 } else if (ft == fs::file_type::directory_file ||
884 ft == fs::file_type::symlink_file ||
885 ft == fs::file_type::type_unknown) {
886 // Try and recurse into anything that a directory or symbolic link. We must
887 // also do this for unknown as sometimes the directory enumeration might be
888 // enumerating a file system that doesn't have correct file type
889 // information.
891 }
892
894}
895
897 const bool find_directories = true;
898 const bool find_files = true;
899 const bool find_other = true;
900 char dir_path[PATH_MAX];
901 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
902 if (FileSystem::Instance().Exists(dir_spec) &&
903 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
904 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
905 find_files, find_other,
906 LoadPluginCallback, this);
907 }
908 }
909
910 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
911 if (FileSystem::Instance().Exists(dir_spec) &&
912 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
913 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
914 find_files, find_other,
915 LoadPluginCallback, this);
916 }
917 }
918
920}
921
923 void *baton) {
926 helper([](lldb_private::telemetry::DebuggerInfo *entry) {
928 });
929 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
930 helper.SetDebugger(debugger_sp.get());
931 {
932 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
934 g_debugger_list_ptr->push_back(debugger_sp);
935 }
936 debugger_sp->InstanceInitialize();
937 return debugger_sp;
938}
939
945
947 const lldb::user_id_t user_id = GetID();
948 // Invoke and remove all the callbacks in an FIFO order. Callbacks which are
949 // added during this loop will be appended, invoked and then removed last.
950 // Callbacks which are removed during this loop will not be invoked.
951 while (true) {
952 DestroyCallbackInfo callback_info;
953 {
954 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
955 if (m_destroy_callbacks.empty())
956 break;
957 // Pop the first item in the list
958 callback_info = m_destroy_callbacks.front();
960 }
961 // Call the destroy callback with user id and baton
962 callback_info.callback(user_id, callback_info.baton);
963 }
964}
965
966void Debugger::Destroy(DebuggerSP &debugger_sp) {
967 if (!debugger_sp)
968 return;
969
970 debugger_sp->HandleDestroyCallback();
971 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
972
973 if (cmd_interpreter.GetSaveSessionOnQuit()) {
974 CommandReturnObject result(debugger_sp->GetUseColor());
975 cmd_interpreter.SaveTranscript(result);
976 if (result.Succeeded())
977 (*debugger_sp->GetAsyncOutputStream())
978 << result.GetOutputString() << '\n';
979 else
980 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorString() << '\n';
981 }
982
983 debugger_sp->Clear();
984
985 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
987 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
988 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
989 if ((*pos).get() == debugger_sp.get()) {
990 g_debugger_list_ptr->erase(pos);
991 return;
992 }
993 }
994 }
995}
996
998Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) {
999 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1001 return nullptr;
1002
1003 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1004 if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name)
1005 return debugger_sp;
1006 }
1007
1008 return nullptr;
1009}
1010
1012 static constexpr llvm::StringLiteral class_name("lldb.debugger");
1013 return class_name;
1014}
1015
1017 : UserID(g_unique_id++),
1018 Properties(std::make_shared<OptionValueProperties>()),
1019 m_input_file_sp(std::make_shared<NativeFile>(
1020 stdin, File::eOpenOptionReadOnly, NativeFile::Unowned)),
1021 m_output_stream_sp(std::make_shared<LockableStreamFile>(
1022 stdout, NativeFile::Unowned, m_output_mutex)),
1023 m_error_stream_sp(std::make_shared<LockableStreamFile>(
1024 stderr, NativeFile::Unowned, m_output_mutex)),
1025 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
1027 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
1030 std::make_unique<CommandInterpreter>(*this, false)),
1032 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()),
1034 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
1038 // Initialize the debugger properties as early as possible as other parts of
1039 // LLDB will start querying them during construction.
1040 m_collection_sp->Initialize(g_debugger_properties_def);
1041 m_collection_sp->AppendProperty(
1042 "target", "Settings specify to debugging targets.", true,
1044 m_collection_sp->AppendProperty(
1045 "platform", "Platform settings.", true,
1047 m_collection_sp->AppendProperty(
1048 "symbols", "Symbol lookup and cache settings.", true,
1050 m_collection_sp->AppendProperty(
1051 LanguageProperties::GetSettingName(), "Language settings.", true,
1054 m_collection_sp->AppendProperty(
1055 "interpreter",
1056 "Settings specify to the debugger's command interpreter.", true,
1057 m_command_interpreter_up->GetValueProperties());
1058 }
1059#ifndef NDEBUG
1060 m_collection_sp->AppendProperty(
1061 "testing", "Testing-only settings.", /*is_global=*/true,
1063#endif
1064
1065 if (log_callback)
1067 std::make_shared<CallbackLogHandler>(log_callback, baton);
1068 m_command_interpreter_up->Initialize();
1069 // Always add our default platform to the platform list
1070 PlatformSP default_platform_sp(Platform::GetHostPlatform());
1071 assert(default_platform_sp);
1072 m_platform_list.Append(default_platform_sp, true);
1073
1074 // Create the dummy target.
1075 {
1077 if (!arch.IsValid())
1078 arch = HostInfo::GetArchitecture();
1079 assert(arch.IsValid() && "No valid default or host archspec");
1080 const bool is_dummy_target = true;
1081 m_dummy_target_sp.reset(
1082 new Target(*this, arch, default_platform_sp, is_dummy_target));
1083 }
1084 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
1085
1086 OptionValueUInt64 *term_width =
1087 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1088 ePropertyTerminalWidth);
1089 term_width->SetMinimumValue(10);
1090
1091 OptionValueUInt64 *term_height =
1092 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1093 ePropertyTerminalHeight);
1094 term_height->SetMinimumValue(10);
1095
1096 // Turn off use-color if this is a dumb terminal.
1097 const char *term = getenv("TERM");
1098 auto disable_color = [&]() {
1099 SetUseColor(false);
1100 SetSeparator("| ");
1101 };
1102
1103 if (term && !strcmp(term, "dumb"))
1104 disable_color();
1105 // Turn off use-color if we don't write to a terminal with color support.
1106 if (!GetOutputFileSP()->GetIsTerminalWithColors())
1107 disable_color();
1108
1109 if (Diagnostics::Enabled()) {
1111 [this](const FileSpec &dir) -> llvm::Error {
1112 for (auto &entry : m_stream_handlers) {
1113 llvm::StringRef log_path = entry.first();
1114 llvm::StringRef file_name = llvm::sys::path::filename(log_path);
1115 FileSpec destination = dir.CopyByAppendingPathComponent(file_name);
1116 std::error_code ec =
1117 llvm::sys::fs::copy_file(log_path, destination.GetPath());
1118 if (ec)
1119 return llvm::errorCodeToError(ec);
1120 }
1121 return llvm::Error::success();
1122 });
1123 }
1124
1125#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
1126 // Enabling use of ANSI color codes because LLDB is using them to highlight
1127 // text.
1128 llvm::sys::Process::UseANSIEscapeCodes(true);
1129#endif
1130}
1131
1133
1135 // Make sure we call this function only once. With the C++ global destructor
1136 // chain having a list of debuggers and with code that can be running on
1137 // other threads, we need to ensure this doesn't happen multiple times.
1138 //
1139 // The following functions call Debugger::Clear():
1140 // Debugger::~Debugger();
1141 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
1142 // static void Debugger::Terminate();
1143 llvm::call_once(m_clear_once, [this]() {
1146 assert(this == info->debugger);
1147 (void)this;
1148 info->is_exit_entry = true;
1149 },
1150 this);
1154 m_listener_sp->Clear();
1155 for (TargetSP target_sp : m_target_list.Targets()) {
1156 if (target_sp) {
1157 if (ProcessSP process_sp = target_sp->GetProcessSP())
1158 process_sp->Finalize(false /* not destructing */);
1159 target_sp->Destroy();
1160 }
1161 }
1162 m_broadcaster_manager_sp->Clear();
1163
1164 // Close the input file _before_ we close the input read communications
1165 // class as it does NOT own the input file, our m_input_file does.
1166 m_terminal_state.Clear();
1167 GetInputFile().Close();
1168
1169 m_command_interpreter_up->Clear();
1170
1173 });
1174}
1175
1177 return !m_command_interpreter_up->GetSynchronous();
1178}
1179
1180void Debugger::SetAsyncExecution(bool async_execution) {
1181 m_command_interpreter_up->SetSynchronous(!async_execution);
1182}
1183
1184static inline int OpenPipe(int fds[2], std::size_t size) {
1185#ifdef _WIN32
1186 return _pipe(fds, size, O_BINARY);
1187#else
1188 (void)size;
1189 return pipe(fds);
1190#endif
1191}
1192
1194 Status result;
1195 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
1196 int fds[2] = {-1, -1};
1197
1198 if (data == nullptr) {
1199 result = Status::FromErrorString("String data is null");
1200 return result;
1201 }
1202
1203 size_t size = strlen(data);
1204 if (size == 0) {
1205 result = Status::FromErrorString("String data is empty");
1206 return result;
1207 }
1208
1209 if (OpenPipe(fds, size) != 0) {
1210 result = Status::FromErrorString(
1211 "can't create pipe file descriptors for LLDB commands");
1212 return result;
1213 }
1214
1215 int r = write(fds[WRITE], data, size);
1216 (void)r;
1217 // Close the write end of the pipe, so that the command interpreter will exit
1218 // when it consumes all the data.
1219 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
1220
1221 // Open the read file descriptor as a FILE * that we can return as an input
1222 // handle.
1223 FILE *commands_file = fdopen(fds[READ], "rb");
1224 if (commands_file == nullptr) {
1226 "fdopen(%i, \"rb\") failed (errno = %i) "
1227 "when trying to open LLDB commands pipe",
1228 fds[READ], errno);
1229 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
1230 return result;
1231 }
1232
1233 SetInputFile((FileSP)std::make_shared<NativeFile>(
1234 commands_file, File::eOpenOptionReadOnly, true));
1235 return result;
1236}
1237
1239 assert(file_sp && file_sp->IsValid());
1240 m_input_file_sp = std::move(file_sp);
1241 // Save away the terminal state if that is relevant, so that we can restore
1242 // it in RestoreInputState.
1244}
1245
1247 assert(file_sp && file_sp->IsValid());
1249 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1250}
1251
1253 assert(file_sp && file_sp->IsValid());
1255 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1256}
1257
1259 {
1260 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1261 if (m_statusline)
1262 m_statusline->Disable();
1263 }
1264 int fd = GetInputFile().GetDescriptor();
1265 if (fd != File::kInvalidDescriptor)
1266 m_terminal_state.Save(fd, true);
1267}
1268
1270 m_terminal_state.Restore();
1271 {
1272 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1273 if (m_statusline)
1274 m_statusline->Enable(
1275 GetSelectedExecutionContext(/*adopt_dummy_target=*/true));
1276 }
1277}
1278
1280 std::optional<ExecutionContextRef> exe_ctx_ref) {
1281 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1282
1283 if (!m_statusline)
1284 return;
1285
1286 m_statusline->Redraw(exe_ctx_ref);
1287}
1288
1290 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1291
1292 if (!m_statusline)
1293 return;
1294
1295 m_statusline->ClearExecutionContext();
1296}
1297
1300 return ExecutionContext(GetSelectedExecutionContextRef(adopt_dummy_target));
1301}
1302
1305 if (TargetSP selected_target_sp = GetSelectedTarget())
1306 return ExecutionContextRef(selected_target_sp.get(),
1307 /*adopt_selected=*/true);
1308
1309 if (adopt_dummy_target)
1311 /*adopt_selected=*/false);
1312
1313 return ExecutionContextRef();
1314}
1315
1317 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1318 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1319 if (reader_sp)
1320 reader_sp->Interrupt();
1321}
1322
1324 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1325 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1326 if (reader_sp)
1327 reader_sp->GotEOF();
1328}
1329
1331 // The bottom input reader should be the main debugger input reader. We do
1332 // not want to close that one here.
1333 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1334 while (m_io_handler_stack.GetSize() > 1) {
1335 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1336 if (reader_sp)
1337 PopIOHandler(reader_sp);
1338 }
1339}
1340
1342 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1343 while (true) {
1344 if (!reader_sp)
1345 break;
1346
1347 reader_sp->Run();
1348 {
1349 std::lock_guard<std::recursive_mutex> guard(
1351
1352 // Remove all input readers that are done from the top of the stack
1353 while (true) {
1354 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1355 if (top_reader_sp && top_reader_sp->GetIsDone())
1356 PopIOHandler(top_reader_sp);
1357 else
1358 break;
1359 }
1360 reader_sp = m_io_handler_stack.Top();
1361 }
1362 }
1364}
1365
1367 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1368
1369 PushIOHandler(reader_sp);
1370 IOHandlerSP top_reader_sp = reader_sp;
1371
1372 while (top_reader_sp) {
1373 top_reader_sp->Run();
1374
1375 // Don't unwind past the starting point.
1376 if (top_reader_sp.get() == reader_sp.get()) {
1377 if (PopIOHandler(reader_sp))
1378 break;
1379 }
1380
1381 // If we pushed new IO handlers, pop them if they're done or restart the
1382 // loop to run them if they're not.
1383 while (true) {
1384 top_reader_sp = m_io_handler_stack.Top();
1385 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1386 PopIOHandler(top_reader_sp);
1387 // Don't unwind past the starting point.
1388 if (top_reader_sp.get() == reader_sp.get())
1389 return;
1390 } else {
1391 break;
1392 }
1393 }
1394 }
1395}
1396
1398 return m_io_handler_stack.IsTop(reader_sp);
1399}
1400
1402 IOHandler::Type second_top_type) {
1403 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1404}
1405
1406void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1407 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1408 if (!printed) {
1409 LockableStreamFileSP stream_sp =
1411 LockedStreamFile locked_stream = stream_sp->Lock();
1412 locked_stream.Write(s, len);
1413 }
1414}
1415
1417 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1418}
1419
1421 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1422}
1423
1425 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1426}
1427
1429 return PopIOHandler(reader_sp);
1430}
1431
1433 bool cancel_top_handler) {
1434 PushIOHandler(reader_sp, cancel_top_handler);
1435}
1436
1439 LockableStreamFileSP &err) {
1440 // Before an IOHandler runs, it must have in/out/err streams. This function
1441 // is called when one ore more of the streams are nullptr. We use the top
1442 // input reader's in/out/err streams, or fall back to the debugger file
1443 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1444
1445 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1446 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1447 // If no STDIN has been set, then set it appropriately
1448 if (!in || !in->IsValid()) {
1449 if (top_reader_sp)
1450 in = top_reader_sp->GetInputFileSP();
1451 else
1452 in = GetInputFileSP();
1453 // If there is nothing, use stdin
1454 if (!in)
1455 in = std::make_shared<NativeFile>(stdin, File::eOpenOptionReadOnly,
1457 }
1458 // If no STDOUT has been set, then set it appropriately
1459 if (!out || !out->GetUnlockedFile().IsValid()) {
1460 if (top_reader_sp)
1461 out = top_reader_sp->GetOutputStreamFileSP();
1462 else
1463 out = GetOutputStreamSP();
1464 // If there is nothing, use stdout
1465 if (!out)
1466 out = std::make_shared<LockableStreamFile>(stdout, NativeFile::Unowned,
1468 }
1469 // If no STDERR has been set, then set it appropriately
1470 if (!err || !err->GetUnlockedFile().IsValid()) {
1471 if (top_reader_sp)
1472 err = top_reader_sp->GetErrorStreamFileSP();
1473 else
1474 err = GetErrorStreamSP();
1475 // If there is nothing, use stderr
1476 if (!err)
1477 err = std::make_shared<LockableStreamFile>(stderr, NativeFile::Unowned,
1479 }
1480}
1481
1483 bool cancel_top_handler) {
1484 if (!reader_sp)
1485 return;
1486
1487 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1488
1489 // Get the current top input reader...
1490 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1491
1492 // Don't push the same IO handler twice...
1493 if (reader_sp == top_reader_sp)
1494 return;
1495
1496 // Push our new input reader
1497 m_io_handler_stack.Push(reader_sp);
1498 reader_sp->Activate();
1499
1500 // Interrupt the top input reader to it will exit its Run() function and let
1501 // this new input reader take over
1502 if (top_reader_sp) {
1503 top_reader_sp->Deactivate();
1504 if (cancel_top_handler)
1505 top_reader_sp->Cancel();
1506 }
1507}
1508
1509bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1510 if (!pop_reader_sp)
1511 return false;
1512
1513 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1514
1515 // The reader on the stop of the stack is done, so let the next read on the
1516 // stack refresh its prompt and if there is one...
1517 if (m_io_handler_stack.IsEmpty())
1518 return false;
1519
1520 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1521
1522 if (pop_reader_sp != reader_sp)
1523 return false;
1524
1525 reader_sp->Deactivate();
1526 reader_sp->Cancel();
1527 m_io_handler_stack.Pop();
1528
1529 reader_sp = m_io_handler_stack.Top();
1530 if (reader_sp)
1531 reader_sp->Activate();
1532
1533 return true;
1534}
1535
1537 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1538 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1539 if (reader_sp)
1540 reader_sp->Refresh();
1541}
1542
1544 return std::make_unique<StreamAsynchronousIO>(*this,
1546}
1547
1549 return std::make_unique<StreamAsynchronousIO>(*this,
1551}
1552
1554 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1556}
1557
1559 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1560 if (m_interrupt_requested > 0)
1562}
1563
1565 // This is the one we should call internally. This will return true either
1566 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1567 // or if we are on the IOHandler thread and there's a CommandInterpreter
1568 // interrupt.
1570 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1571 return m_interrupt_requested != 0;
1572 }
1574}
1575
1577 std::string function_name, const llvm::formatv_object_base &payload)
1578 : m_function_name(std::move(function_name)),
1579 m_interrupt_time(std::chrono::system_clock::now()),
1580 m_thread_id(llvm::get_threadid()) {
1581 llvm::raw_string_ostream desc(m_description);
1582 desc << payload << "\n";
1583}
1584
1586 // For now, just log the description:
1587 Log *log = GetLog(LLDBLog::Host);
1588 LLDB_LOG(log, "Interruption: {0}", report.m_description);
1589}
1590
1592 DebuggerList result;
1593 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1594 if (g_debugger_list_ptr) {
1595 for (auto debugger_sp : *g_debugger_list_ptr) {
1596 if (debugger_sp->InterruptRequested())
1597 result.push_back(debugger_sp);
1598 }
1599 }
1600 return result;
1601}
1602
1604 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1606 return 0;
1607
1608 return g_debugger_list_ptr->size();
1609}
1610
1612 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1614 return nullptr;
1615
1616 if (index < g_debugger_list_ptr->size())
1617 return g_debugger_list_ptr->at(index);
1618
1619 return nullptr;
1620}
1621
1623 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1625 return nullptr;
1626
1627 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1628 if (debugger_sp->GetID() == id)
1629 return debugger_sp;
1630 }
1631
1632 return nullptr;
1633}
1634
1636 const SymbolContext *sc,
1637 const SymbolContext *prev_sc,
1638 const ExecutionContext *exe_ctx,
1639 const Address *addr, Stream &s) {
1640 FormatEntity::Entry format_entry;
1641
1642 if (format == nullptr) {
1643 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) {
1644 format_entry =
1646 format = &format_entry;
1647 }
1648 if (format == nullptr) {
1649 FormatEntity::Parse("${addr}: ", format_entry);
1650 format = &format_entry;
1651 }
1652 }
1653 bool function_changed = false;
1654 bool initial_function = false;
1655 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1656 if (sc && (sc->function || sc->symbol)) {
1657 if (prev_sc->symbol && sc->symbol) {
1658 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1659 prev_sc->symbol->GetType())) {
1660 function_changed = true;
1661 }
1662 } else if (prev_sc->function && sc->function) {
1663 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1664 function_changed = true;
1665 }
1666 }
1667 }
1668 }
1669 // The first context on a list of instructions will have a prev_sc that has
1670 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1671 // would return false. But we do get a prev_sc pointer.
1672 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1673 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1674 initial_function = true;
1675 }
1676 return FormatEntity::Formatter(sc, exe_ctx, addr, function_changed,
1677 initial_function)
1678 .Format(*format, s);
1679}
1680
1681void Debugger::AssertCallback(llvm::StringRef message,
1682 llvm::StringRef backtrace,
1683 llvm::StringRef prompt) {
1684 Debugger::ReportError(llvm::formatv("{0}\n{1}{2}\n{3}", message, backtrace,
1685 GetVersion(), prompt)
1686 .str());
1687}
1688
1690 void *baton) {
1691 // For simplicity's sake, I am not going to deal with how to close down any
1692 // open logging streams, I just redirect everything from here on out to the
1693 // callback.
1695 std::make_shared<CallbackLogHandler>(log_callback, baton);
1696}
1697
1699 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1700 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1701 m_destroy_callbacks.clear();
1703 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1704}
1705
1707 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1708 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1710 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1711 return token;
1712}
1713
1715 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1716 for (auto it = m_destroy_callbacks.begin(); it != m_destroy_callbacks.end();
1717 ++it) {
1718 if (it->token == token) {
1719 m_destroy_callbacks.erase(it);
1720 return true;
1721 }
1722 }
1723 return false;
1724}
1725
1726static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1727 std::string title, std::string details,
1728 uint64_t completed, uint64_t total,
1729 bool is_debugger_specific,
1730 uint32_t progress_broadcast_bit) {
1731 // Only deliver progress events if we have any progress listeners.
1732 if (!debugger.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit))
1733 return;
1734
1735 EventSP event_sp(new Event(
1736 progress_broadcast_bit,
1737 new ProgressEventData(progress_id, std::move(title), std::move(details),
1738 completed, total, is_debugger_specific)));
1739 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1740}
1741
1742void Debugger::ReportProgress(uint64_t progress_id, std::string title,
1743 std::string details, uint64_t completed,
1744 uint64_t total,
1745 std::optional<lldb::user_id_t> debugger_id,
1746 uint32_t progress_broadcast_bit) {
1747 // Check if this progress is for a specific debugger.
1748 if (debugger_id) {
1749 // It is debugger specific, grab it and deliver the event if the debugger
1750 // still exists.
1751 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1752 if (debugger_sp)
1753 PrivateReportProgress(*debugger_sp, progress_id, std::move(title),
1754 std::move(details), completed, total,
1755 /*is_debugger_specific*/ true,
1756 progress_broadcast_bit);
1757 return;
1758 }
1759 // The progress event is not debugger specific, iterate over all debuggers
1760 // and deliver a progress event to each one.
1761 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1762 if (g_debugger_list_ptr) {
1763 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1764 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1765 PrivateReportProgress(*(*pos), progress_id, title, details, completed,
1766 total, /*is_debugger_specific*/ false,
1767 progress_broadcast_bit);
1768 }
1769}
1770
1771static void PrivateReportDiagnostic(Debugger &debugger, Severity severity,
1772 std::string message,
1773 bool debugger_specific) {
1774 uint32_t event_type = 0;
1775 switch (severity) {
1776 case eSeverityInfo:
1777 assert(false && "eSeverityInfo should not be broadcast");
1778 return;
1779 case eSeverityWarning:
1780 event_type = lldb::eBroadcastBitWarning;
1781 break;
1782 case eSeverityError:
1783 event_type = lldb::eBroadcastBitError;
1784 break;
1785 }
1786
1787 Broadcaster &broadcaster = debugger.GetBroadcaster();
1788 if (!broadcaster.EventTypeHasListeners(event_type)) {
1789 // Diagnostics are too important to drop. If nobody is listening, print the
1790 // diagnostic directly to the debugger's error stream.
1791 DiagnosticEventData event_data(severity, std::move(message),
1792 debugger_specific);
1793 event_data.Dump(debugger.GetAsyncErrorStream().get());
1794 return;
1795 }
1796 EventSP event_sp = std::make_shared<Event>(
1797 event_type,
1798 new DiagnosticEventData(severity, std::move(message), debugger_specific));
1799 broadcaster.BroadcastEvent(event_sp);
1800}
1801
1802void Debugger::ReportDiagnosticImpl(Severity severity, std::string message,
1803 std::optional<lldb::user_id_t> debugger_id,
1804 std::once_flag *once) {
1805 auto ReportDiagnosticLambda = [&]() {
1806 // Always log diagnostics to the system log.
1807 Host::SystemLog(severity, message);
1808
1809 // The diagnostic subsystem is optional but we still want to broadcast
1810 // events when it's disabled.
1812 Diagnostics::Instance().Report(message);
1813
1814 // We don't broadcast info events.
1815 if (severity == lldb::eSeverityInfo)
1816 return;
1817
1818 // Check if this diagnostic is for a specific debugger.
1819 if (debugger_id) {
1820 // It is debugger specific, grab it and deliver the event if the debugger
1821 // still exists.
1822 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1823 if (debugger_sp)
1824 PrivateReportDiagnostic(*debugger_sp, severity, std::move(message),
1825 true);
1826 return;
1827 }
1828 // The diagnostic event is not debugger specific, iterate over all debuggers
1829 // and deliver a diagnostic event to each one.
1830 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1831 if (g_debugger_list_ptr) {
1832 for (const auto &debugger : *g_debugger_list_ptr)
1833 PrivateReportDiagnostic(*debugger, severity, message, false);
1834 }
1835 };
1836
1837 if (once)
1838 std::call_once(*once, ReportDiagnosticLambda);
1839 else
1840 ReportDiagnosticLambda();
1841}
1842
1843void Debugger::ReportWarning(std::string message,
1844 std::optional<lldb::user_id_t> debugger_id,
1845 std::once_flag *once) {
1846 ReportDiagnosticImpl(eSeverityWarning, std::move(message), debugger_id, once);
1847}
1848
1849void Debugger::ReportError(std::string message,
1850 std::optional<lldb::user_id_t> debugger_id,
1851 std::once_flag *once) {
1852 ReportDiagnosticImpl(eSeverityError, std::move(message), debugger_id, once);
1853}
1854
1855void Debugger::ReportInfo(std::string message,
1856 std::optional<lldb::user_id_t> debugger_id,
1857 std::once_flag *once) {
1858 ReportDiagnosticImpl(eSeverityInfo, std::move(message), debugger_id, once);
1859}
1860
1862 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1864 return;
1865
1866 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1867 EventSP event_sp = std::make_shared<Event>(
1869 new SymbolChangeEventData(debugger_sp, module_spec));
1870 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1871 }
1872}
1873
1874static std::shared_ptr<LogHandler>
1875CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1876 size_t buffer_size) {
1877 switch (log_handler_kind) {
1878 case eLogHandlerStream:
1879 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1881 return std::make_shared<RotatingLogHandler>(buffer_size);
1882 case eLogHandlerSystem:
1883 return std::make_shared<SystemLogHandler>();
1885 return {};
1886 }
1887 return {};
1888}
1889
1890bool Debugger::EnableLog(llvm::StringRef channel,
1891 llvm::ArrayRef<const char *> categories,
1892 llvm::StringRef log_file, uint32_t log_options,
1893 size_t buffer_size, LogHandlerKind log_handler_kind,
1894 llvm::raw_ostream &error_stream) {
1895
1896 std::shared_ptr<LogHandler> log_handler_sp;
1898 log_handler_sp = m_callback_handler_sp;
1899 // For now when using the callback mode you always get thread & timestamp.
1900 log_options |=
1902 } else if (log_file.empty()) {
1903 log_handler_sp =
1904 CreateLogHandler(log_handler_kind, GetOutputFileSP()->GetDescriptor(),
1905 /*should_close=*/false, buffer_size);
1906 } else {
1907 auto pos = m_stream_handlers.find(log_file);
1908 if (pos != m_stream_handlers.end())
1909 log_handler_sp = pos->second.lock();
1910 if (!log_handler_sp) {
1911 File::OpenOptions flags =
1913 if (log_options & LLDB_LOG_OPTION_APPEND)
1914 flags |= File::eOpenOptionAppend;
1915 else
1917 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1918 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1919 if (!file) {
1920 error_stream << "Unable to open log file '" << log_file
1921 << "': " << llvm::toString(file.takeError()) << "\n";
1922 return false;
1923 }
1924
1925 log_handler_sp =
1926 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1927 /*should_close=*/true, buffer_size);
1928 m_stream_handlers[log_file] = log_handler_sp;
1929 }
1930 }
1931 assert(log_handler_sp);
1932
1933 if (log_options == 0)
1935
1936 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories,
1937 error_stream);
1938}
1939
1942 std::optional<lldb::ScriptLanguage> language) {
1943 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1944 lldb::ScriptLanguage script_language =
1945 language ? *language : GetScriptLanguage();
1946
1947 if (!m_script_interpreters[script_language]) {
1948 if (!can_create)
1949 return nullptr;
1950 m_script_interpreters[script_language] =
1951 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1952 }
1953
1954 return m_script_interpreters[script_language].get();
1955}
1956
1959 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1960 return *m_source_manager_up;
1961}
1962
1963// This function handles events that were broadcast by the process.
1965 using namespace lldb;
1966 const uint32_t event_type =
1968 event_sp);
1969
1970 // if (event_type & eBreakpointEventTypeAdded
1971 // || event_type & eBreakpointEventTypeRemoved
1972 // || event_type & eBreakpointEventTypeEnabled
1973 // || event_type & eBreakpointEventTypeDisabled
1974 // || event_type & eBreakpointEventTypeCommandChanged
1975 // || event_type & eBreakpointEventTypeConditionChanged
1976 // || event_type & eBreakpointEventTypeIgnoreChanged
1977 // || event_type & eBreakpointEventTypeLocationsResolved)
1978 // {
1979 // // Don't do anything about these events, since the breakpoint
1980 // commands already echo these actions.
1981 // }
1982 //
1983 if (event_type & eBreakpointEventTypeLocationsAdded) {
1984 uint32_t num_new_locations =
1986 event_sp);
1987 if (num_new_locations > 0) {
1988 BreakpointSP breakpoint =
1990 if (StreamUP output_up = GetAsyncOutputStream()) {
1991 output_up->Printf("%d location%s added to breakpoint %d\n",
1992 num_new_locations, num_new_locations == 1 ? "" : "s",
1993 breakpoint->GetID());
1994 output_up->Flush();
1995 }
1996 }
1997 }
1998 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1999 // {
2000 // // These locations just get disabled, not sure it is worth spamming
2001 // folks about this on the command line.
2002 // }
2003 // else if (event_type & eBreakpointEventTypeLocationsResolved)
2004 // {
2005 // // This might be an interesting thing to note, but I'm going to
2006 // leave it quiet for now, it just looked noisy.
2007 // }
2008}
2009
2010void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
2011 bool flush_stderr) {
2012 const auto &flush = [&](Stream &stream,
2013 size_t (Process::*get)(char *, size_t, Status &)) {
2014 Status error;
2015 size_t len;
2016 char buffer[1024];
2017 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
2018 stream.Write(buffer, len);
2019 stream.Flush();
2020 };
2021
2022 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
2023 if (flush_stdout)
2025 if (flush_stderr)
2027}
2028
2029// This function handles events that were broadcast by the process.
2031 const uint32_t event_type = event_sp->GetType();
2032 ProcessSP process_sp =
2036
2037 StreamUP output_stream_up = GetAsyncOutputStream();
2038 StreamUP error_stream_up = GetAsyncErrorStream();
2039 const bool gui_enabled = IsForwardingEvents();
2040
2041 if (!gui_enabled) {
2042 bool pop_process_io_handler = false;
2043 assert(process_sp);
2044
2045 bool state_is_stopped = false;
2046 const bool got_state_changed =
2047 (event_type & Process::eBroadcastBitStateChanged) != 0;
2048 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
2049 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
2050 const bool got_structured_data =
2051 (event_type & Process::eBroadcastBitStructuredData) != 0;
2052
2053 if (got_state_changed) {
2054 StateType event_state =
2056 state_is_stopped = StateIsStoppedState(event_state, false);
2057 }
2058
2059 // Display running state changes first before any STDIO
2060 if (got_state_changed && !state_is_stopped) {
2061 // This is a public stop which we are going to announce to the user, so
2062 // we should force the most relevant frame selection here.
2063 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2065 pop_process_io_handler);
2066 }
2067
2068 // Now display STDOUT and STDERR
2069 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
2070 got_stderr || got_state_changed);
2071
2072 // Give structured data events an opportunity to display.
2073 if (got_structured_data) {
2074 StructuredDataPluginSP plugin_sp =
2076 if (plugin_sp) {
2077 auto structured_data_sp =
2079 StreamString content_stream;
2080 Status error =
2081 plugin_sp->GetDescription(structured_data_sp, content_stream);
2082 if (error.Success()) {
2083 if (!content_stream.GetString().empty()) {
2084 // Add newline.
2085 content_stream.PutChar('\n');
2086 content_stream.Flush();
2087
2088 // Print it.
2089 output_stream_up->PutCString(content_stream.GetString());
2090 }
2091 } else {
2092 error_stream_up->Format("Failed to print structured "
2093 "data with plugin {0}: {1}",
2094 plugin_sp->GetPluginName(), error);
2095 }
2096 }
2097 }
2098
2099 // Now display any stopped state changes after any STDIO
2100 if (got_state_changed && state_is_stopped) {
2101 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2103 pop_process_io_handler);
2104 }
2105
2106 output_stream_up->Flush();
2107 error_stream_up->Flush();
2108
2109 if (pop_process_io_handler)
2110 process_sp->PopProcessIOHandler();
2111 }
2112 return process_sp;
2113}
2114
2116 // At present the only thread event we handle is the Frame Changed event, and
2117 // all we do for that is just reprint the thread status for that thread.
2118 const uint32_t event_type = event_sp->GetType();
2119 const bool stop_format = true;
2120 ThreadSP thread_sp;
2121 if (event_type == Thread::eBroadcastBitStackChanged ||
2123 thread_sp = Thread::ThreadEventData::GetThreadFromEvent(event_sp.get());
2124 if (thread_sp) {
2125 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format,
2126 /*show_hidden*/ true);
2127 }
2128 }
2129 return thread_sp;
2130}
2131
2133
2135 m_forward_listener_sp = listener_sp;
2136}
2137
2139 m_forward_listener_sp.reset();
2140}
2141
2142/// Conservative heuristic to detect whether OSC 9;4 progress is supported by
2143/// the current terminal.
2145#if defined(_WIN32)
2146 // On Windows, we assume that the user is using the Windows Terminal.
2147 return true;
2148#else
2149 static std::once_flag g_once_flag;
2150 static bool g_supports_osc_progress = false;
2151
2152 std::call_once(g_once_flag, []() {
2153 // Check TERM_PROGRAM for known supported terminals. This can lead to false
2154 // negatives, for example when using tmux.
2155 if (const char *term_program = std::getenv("TERM_PROGRAM")) {
2156 llvm::StringRef term_program_str(term_program);
2157 if (term_program_str.starts_with("ghostty") ||
2158 term_program_str.starts_with("wezterm")) {
2159 g_supports_osc_progress = true;
2160 return;
2161 }
2162 }
2163
2164 // Check other known environment variables.
2165 std::array<const char *, 3> known_env_vars = {
2166 "ConEmuPID", // https://conemu.github.io/en/ConEmuEnvironment.html
2167 "GHOSTTY_RESOURCES_DIR", // https://ghostty.org/docs/features/shell-integration
2168 "OSC_PROGRESS", // LLDB specific override.
2169 };
2170 for (const char *env_var : known_env_vars) {
2171 if (std::getenv(env_var)) {
2172 g_supports_osc_progress = true;
2173 return;
2174 }
2175 }
2176 });
2177
2178 return g_supports_osc_progress;
2179#endif
2180}
2181
2184 File &file = stream_sp->GetUnlockedFile();
2185 return file.GetIsInteractive() && file.GetIsRealTerminal() &&
2187 }
2188 return false;
2189}
2190
2192// We have trouble with the contol codes on Windows, see
2193// https://github.com/llvm/llvm-project/issues/134846.
2194#ifndef _WIN32
2196#else
2197 return false;
2198#endif
2199}
2200
2201static bool RequiresFollowChildWorkaround(const Process &process) {
2202 // FIXME: https://github.com/llvm/llvm-project/issues/160216
2203 return process.GetFollowForkMode() == eFollowChild;
2204}
2205
2207 ListenerSP listener_sp(GetListener());
2208 llvm::StringRef broadcaster_class_target(Target::GetStaticBroadcasterClass());
2209 llvm::StringRef broadcaster_class_process(
2211 llvm::StringRef broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
2212 BroadcastEventSpec target_event_spec(broadcaster_class_target,
2214
2215 BroadcastEventSpec process_event_spec(
2216 broadcaster_class_process,
2219
2220 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
2223
2224 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2225 target_event_spec);
2226 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2227 process_event_spec);
2228 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2229 thread_event_spec);
2230 listener_sp->StartListeningForEvents(
2235
2236 listener_sp->StartListeningForEvents(
2241
2242 // Let the thread that spawned us know that we have started up and that we
2243 // are now listening to all required events so no events get missed
2245
2246 if (StatuslineSupported()) {
2247 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2248 if (!m_statusline) {
2249 m_statusline.emplace(*this);
2250 m_statusline->Enable(
2251 GetSelectedExecutionContextRef(/*adopt_dummy_target=*/true));
2252 }
2253 }
2254
2255 bool done = false;
2256 while (!done) {
2257 EventSP event_sp;
2258 if (listener_sp->GetEvent(event_sp, std::nullopt)) {
2259 std::optional<ExecutionContextRef> exe_ctx_ref = std::nullopt;
2260 if (event_sp) {
2261 Broadcaster *broadcaster = event_sp->GetBroadcaster();
2262 if (broadcaster) {
2263 uint32_t event_type = event_sp->GetType();
2264 llvm::StringRef broadcaster_class(broadcaster->GetBroadcasterClass());
2265 if (broadcaster_class == broadcaster_class_process) {
2266 if (ProcessSP process_sp = HandleProcessEvent(event_sp)) {
2267 // Don't pass adopt_selected = true if this is a stop for an
2268 // auto-continue event (e.g. an auto-continue breakpoint). We
2269 // would be fetching stale state, since the process resumed since
2270 // this event, and we'd needlessly interrupt the target to do so.
2271 const bool adopt_selected =
2272 process_sp->GetPrivateState() == eStateStopped &&
2274 event_sp.get());
2275 if (!RequiresFollowChildWorkaround(*process_sp))
2276 exe_ctx_ref =
2277 ExecutionContextRef(process_sp.get(), adopt_selected);
2278 }
2279 } else if (broadcaster_class == broadcaster_class_target) {
2281 event_sp.get())) {
2282 HandleBreakpointEvent(event_sp);
2283 }
2284 } else if (broadcaster_class == broadcaster_class_thread) {
2285 if (ThreadSP thread_sp = HandleThreadEvent(event_sp))
2286 if (!RequiresFollowChildWorkaround(*thread_sp->GetProcess()))
2287 exe_ctx_ref = ExecutionContextRef(thread_sp.get(),
2288 /*adopt_selected=*/true);
2289 } else if (broadcaster == m_command_interpreter_up.get()) {
2290 if (event_type &
2292 done = true;
2293 } else if (event_type &
2295 const char *data = static_cast<const char *>(
2296 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2297 if (data && data[0]) {
2298 StreamUP error_up = GetAsyncErrorStream();
2299 error_up->PutCString(data);
2300 error_up->Flush();
2301 }
2302 } else if (event_type & CommandInterpreter::
2303 eBroadcastBitAsynchronousOutputData) {
2304 const char *data = static_cast<const char *>(
2305 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2306 if (data && data[0]) {
2307 StreamUP output_up = GetAsyncOutputStream();
2308 output_up->PutCString(data);
2309 output_up->Flush();
2310 }
2311 }
2312 } else if (broadcaster == &m_broadcaster) {
2313 if (event_type & lldb::eBroadcastBitProgress ||
2315 HandleProgressEvent(event_sp);
2316 else if (event_type & lldb::eBroadcastBitWarning)
2317 HandleDiagnosticEvent(event_sp);
2318 else if (event_type & lldb::eBroadcastBitError)
2319 HandleDiagnosticEvent(event_sp);
2320 }
2321 }
2322
2324 m_forward_listener_sp->AddEvent(event_sp);
2325 }
2326 RedrawStatusline(exe_ctx_ref);
2327 }
2328 }
2329
2330 {
2331 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2332 if (m_statusline)
2333 m_statusline.reset();
2334 }
2335
2336 return {};
2337}
2338
2340 if (!m_event_handler_thread.IsJoinable()) {
2341 // We must synchronize with the DefaultEventHandler() thread to ensure it
2342 // is up and running and listening to events before we return from this
2343 // function. We do this by listening to events for the
2344 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2345 ConstString full_name("lldb.debugger.event-handler");
2346 ListenerSP listener_sp(
2347 Listener::MakeListener(full_name.AsCString(nullptr)));
2348 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
2350
2351 llvm::StringRef thread_name =
2352 full_name.GetLength() < llvm::get_max_thread_name_length()
2353 ? full_name.GetStringRef()
2354 : "dbg.evt-handler";
2355
2356 // Use larger 8MB stack for this thread
2357 llvm::Expected<HostThread> event_handler_thread =
2359 thread_name, [this] { return DefaultEventHandler(); },
2361
2362 if (event_handler_thread) {
2363 m_event_handler_thread = *event_handler_thread;
2364 } else {
2365 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(),
2366 "failed to launch host thread: {0}");
2367 }
2368
2369 // Make sure DefaultEventHandler() is running and listening to events
2370 // before we return from this function. We are only listening for events of
2371 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2372 // event, we just need to wait an infinite amount of time for it (nullptr
2373 // timeout as the first parameter)
2374 lldb::EventSP event_sp;
2375 listener_sp->GetEvent(event_sp, std::nullopt);
2376 }
2377 return m_event_handler_thread.IsJoinable();
2378}
2379
2387
2393
2395 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
2396 if (!data)
2397 return;
2398
2399 // Make a local copy of the incoming progress report that we'll store.
2400 ProgressReport progress_report{data->GetID(), data->GetCompleted(),
2401 data->GetTotal(), data->GetMessage()};
2402
2403 {
2404 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2405
2406 // Do some bookkeeping regardless of whether we're going to display
2407 // progress reports.
2408 auto it = llvm::find_if(m_progress_reports, [&](const auto &report) {
2409 return report.id == progress_report.id;
2410 });
2411 if (it != m_progress_reports.end()) {
2412 const bool complete = data->GetCompleted() == data->GetTotal();
2413 if (complete)
2414 m_progress_reports.erase(it);
2415 else
2416 *it = progress_report;
2417 } else {
2418 m_progress_reports.push_back(progress_report);
2419 }
2420
2421 // Show progress using Operating System Command (OSC) sequences.
2425
2426 // Clear progress if this was the last progress event.
2427 if (m_progress_reports.empty()) {
2428 stream_sp->Lock() << OSC_PROGRESS_REMOVE;
2429 return;
2430 }
2431
2432 const ProgressReport &report = m_progress_reports.back();
2433
2434 // Show indeterminate progress.
2435 if (report.total == UINT64_MAX) {
2436 stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE;
2437 return;
2438 }
2439
2440 // Compute and show the progress value (0-100).
2441 const unsigned value = (report.completed / report.total) * 100;
2442 stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value);
2443 }
2444 }
2445 }
2446}
2447
2448std::optional<Debugger::ProgressReport>
2450 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2451 if (m_progress_reports.empty())
2452 return std::nullopt;
2453 return m_progress_reports.back();
2454}
2455
2457 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
2458 if (!data)
2459 return;
2460
2461 data->Dump(GetAsyncErrorStream().get());
2462}
2463
2465 return m_io_handler_thread.IsJoinable();
2466}
2467
2470 m_io_handler_thread = new_thread;
2471 return old_host;
2472}
2473
2475 if (!m_io_handler_thread.IsJoinable()) {
2476 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
2477 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2478 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2479 if (io_handler_thread) {
2480 m_io_handler_thread = *io_handler_thread;
2481 } else {
2482 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(),
2483 "failed to launch host thread: {0}");
2484 }
2485 }
2486 return m_io_handler_thread.IsJoinable();
2487}
2488
2490 if (m_io_handler_thread.IsJoinable()) {
2491 GetInputFile().Close();
2492 m_io_handler_thread.Join(nullptr);
2493 }
2494}
2495
2503
2505 if (!HasIOHandlerThread())
2506 return false;
2507 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread());
2508}
2509
2511 if (!prefer_dummy) {
2512 if (TargetSP target = m_target_list.GetSelectedTarget())
2513 return *target;
2514 }
2515 return GetDummyTarget();
2516}
2517
2518Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
2519 Status err;
2520 FileSpec repl_executable;
2521
2522 if (language == eLanguageTypeUnknown)
2523 language = GetREPLLanguage();
2524
2525 if (language == eLanguageTypeUnknown) {
2527
2528 if (auto single_lang = repl_languages.GetSingularLanguage()) {
2529 language = *single_lang;
2530 } else if (repl_languages.Empty()) {
2532 "LLDB isn't configured with REPL support for any languages.");
2533 return err;
2534 } else {
2536 "Multiple possible REPL languages. Please specify a language.");
2537 return err;
2538 }
2539 }
2540
2541 Target *const target =
2542 nullptr; // passing in an empty target means the REPL must create one
2543
2544 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2545
2546 if (!err.Success()) {
2547 return err;
2548 }
2549
2550 if (!repl_sp) {
2552 "couldn't find a REPL for %s",
2554 return err;
2555 }
2556
2557 repl_sp->SetCompilerOptions(repl_options);
2558 repl_sp->RunLoop();
2559
2560 return err;
2561}
2562
2563llvm::ThreadPoolInterface &Debugger::GetThreadPool() {
2564 assert(g_thread_pool &&
2565 "Debugger::GetThreadPool called before Debugger::Initialize");
2566 return *g_thread_pool;
2567}
2568
2570 llvm::StringRef name, bool value,
2571 llvm::StringRef description) {
2572 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2573 entry_up->AddBooleanItem("value", value);
2574 entry_up->AddStringItem("description", description);
2575 dict.AddItem(name, std::move(entry_up));
2576}
2577
2579 auto array_up = std::make_unique<StructuredData::Array>();
2580#define LLVM_TARGET(target) \
2581 array_up->AddItem(std::make_unique<StructuredData::String>(#target));
2582#include "llvm/Config/Targets.def"
2583 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2584 entry_up->AddItem("value", std::move(array_up));
2585 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
2586 dict.AddItem("targets", std::move(entry_up));
2587}
2588
2590 auto config_up = std::make_unique<StructuredData::Dictionary>();
2592 *config_up, "xml", XMLDocument::XMLEnabled(),
2593 "A boolean value that indicates if XML support is enabled in LLDB");
2595 *config_up, "curl", LLVM_ENABLE_CURL,
2596 "A boolean value that indicates if CURL support is enabled in LLDB");
2598 *config_up, "curses", LLDB_ENABLE_CURSES,
2599 "A boolean value that indicates if curses support is enabled in LLDB");
2601 *config_up, "editline", LLDB_ENABLE_LIBEDIT,
2602 "A boolean value that indicates if editline support is enabled in LLDB");
2603 AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,
2604 "A boolean value that indicates if editline wide "
2605 "characters support is enabled in LLDB");
2607 *config_up, "zlib", LLVM_ENABLE_ZLIB,
2608 "A boolean value that indicates if zlib support is enabled in LLDB");
2610 *config_up, "lzma", LLDB_ENABLE_LZMA,
2611 "A boolean value that indicates if lzma support is enabled in LLDB");
2613 *config_up, "python", LLDB_ENABLE_PYTHON,
2614 "A boolean value that indicates if python support is enabled in LLDB");
2616 *config_up, "lua", LLDB_ENABLE_LUA,
2617 "A boolean value that indicates if lua support is enabled in LLDB");
2618 AddLLVMTargets(*config_up);
2619 return config_up;
2620}
#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 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:852
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:364
#define LLDB_LOG_OPTION_APPEND
Definition Log.h:42
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
#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
size_t GetLength() const
Get the length in bytes of string value.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
const std::chrono::time_point< std::chrono::system_clock > m_interrupt_time
Definition Debugger.h:521
InterruptionReport(std::string function_name, std::string description)
Definition Debugger.h:503
A class to manage flag bits.
Definition Debugger.h:100
static void AssertCallback(llvm::StringRef message, llvm::StringRef backtrace, llvm::StringRef prompt)
llvm::StringRef GetAutosuggestionAnsiPrefix() const
Definition Debugger.cpp:612
bool SetUseExternalEditor(bool use_external_editor_p)
Definition Debugger.cpp:509
PlatformList m_platform_list
Definition Debugger.h:771
HostThread m_event_handler_thread
Definition Debugger.h:801
FormatEntity::Entry GetDisassemblyFormat() const
Definition Debugger.cpp:371
uint64_t GetDisassemblyLineCount() const
Definition Debugger.cpp:714
lldb::TargetSP GetSelectedTarget()
Definition Debugger.h:199
llvm::StringRef GetDisabledAnsiSuffix() const
Definition Debugger.cpp:593
uint64_t GetTerminalHeight() const
Definition Debugger.cpp:481
lldb::LockableStreamFileSP m_output_stream_sp
Definition Debugger.h:758
bool SetExternalEditor(llvm::StringRef editor)
Definition Debugger.cpp:520
void RequestInterrupt()
Interruption in LLDB:
void ReportInterruption(const InterruptionReport &report)
const std::string m_instance_name
Definition Debugger.h:797
static void Terminate()
Definition Debugger.cpp:801
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:546
bool StartEventHandlerThread()
Manually start the global event handler thread.
bool SetUseSourceCache(bool use_source_cache)
Definition Debugger.cpp:648
static const FileSpecList & GetDefaultSafeAutoLoadPaths()
Definition Debugger.cpp:216
void StopEventHandlerThread()
Manually stop the debugger's default event handler.
static void ReportInfo(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report info events.
void SetAsyncExecution(bool async)
ExecutionContext GetSelectedExecutionContext(bool adopt_dummy_target)
Get the execution context representing the selected entities in the selected target.
HostThread SetIOHandlerThread(HostThread &new_thread)
void CancelForwardEvents(const lldb::ListenerSP &listener_sp)
bool GetPrintDecls() const
Definition Debugger.cpp:743
lldb::FileSP GetInputFileSP()
Definition Debugger.h:155
bool GetHighlightSource() const
Definition Debugger.cpp:663
llvm::StringMap< std::weak_ptr< LogHandler > > m_stream_handlers
Definition Debugger.h:795
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:182
FormatEntity::Entry GetStatuslineFormat() const
Definition Debugger.cpp:569
LoadedPluginsList m_loaded_plugins
Definition Debugger.h:800
bool GetShowInlineDiagnostics() const
Definition Debugger.cpp:772
bool SetTabSize(uint64_t tab_size)
Definition Debugger.cpp:760
void HandleDiagnosticEvent(const lldb::EventSP &event_sp)
static lldb::DebuggerSP GetDebuggerAtIndex(size_t index)
llvm::StringRef GetAutosuggestionAnsiSuffix() const
Definition Debugger.cpp:618
lldb::ListenerSP m_listener_sp
Definition Debugger.h:772
void PushIOHandler(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
std::mutex m_destroy_callback_mutex
Definition Debugger.h:816
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:381
std::optional< ProgressReport > GetCurrentProgressReport() const
llvm::StringRef GetDisabledAnsiPrefix() const
Definition Debugger.cpp:587
bool GetUseExternalEditor() const
Definition Debugger.cpp:503
TerminalState m_terminal_state
Definition Debugger.h:768
lldb::StreamUP GetAsyncErrorStream()
bool GetEscapeNonPrintables() const
Definition Debugger.cpp:726
lldb::TargetSP m_dummy_target_sp
Definition Debugger.h:807
llvm::SmallVector< DestroyCallbackInfo, 2 > m_destroy_callbacks
Definition Debugger.h:828
std::unique_ptr< CommandInterpreter > m_command_interpreter_up
Definition Debugger.h:782
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:830
LockableStreamFile::Mutex m_output_mutex
Definition Debugger.h:760
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
llvm::StringRef GetShowProgressAnsiSuffix() const
Definition Debugger.cpp:557
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:812
bool IsIOHandlerThreadCurrentThread() const
ExecutionContextRef GetSelectedExecutionContextRef(bool adopt_dummy_target)
Like GetSelectedExecutionContext but returns an ExecutionContextRef.
void DispatchClientTelemetry(const lldb_private::StructuredDataImpl &entry)
Definition Debugger.cpp:940
std::mutex m_progress_reports_mutex
Definition Debugger.h:813
lldb::ProcessSP HandleProcessEvent(const lldb::EventSP &event_sp)
lldb::ListenerSP m_forward_listener_sp
Definition Debugger.h:805
std::array< lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown > m_script_interpreters
Definition Debugger.h:786
std::shared_ptr< CallbackLogHandler > m_callback_handler_sp
Definition Debugger.h:796
void SetDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback, void *baton)
DEPRECATED: We used to only support one Destroy callback.
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:158
Broadcaster m_broadcaster
Public Debugger event broadcaster.
Definition Debugger.h:804
static void Initialize(LoadPluginCallbackType load_plugin_callback)
Definition Debugger.cpp:792
static lldb::DebuggerSP FindDebuggerWithInstanceName(llvm::StringRef instance_name)
Definition Debugger.cpp:998
uint64_t GetTerminalWidth() const
Definition Debugger.cpp:459
std::mutex m_interrupt_mutex
Definition Debugger.h:831
std::recursive_mutex m_io_handler_synchronous_mutex
Definition Debugger.h:789
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:808
bool GetAutoOneLineSummaries() const
Definition Debugger.cpp:720
const char * GetIOHandlerCommandPrefix()
std::optional< Statusline > m_statusline
Definition Debugger.h:793
bool GetUseColor() const
Definition Debugger.cpp:525
lldb::BroadcasterManagerSP m_broadcaster_manager_sp
Definition Debugger.h:762
void FlushStatusLine()
Flush cached state (e.g. stale execution context in the statusline).
Status RunREPL(lldb::LanguageType language, const char *repl_options)
bool PopIOHandler(const lldb::IOHandlerSP &reader_sp)
static StructuredData::DictionarySP GetBuildConfiguration()
Get the build configuration as structured data.
bool RemoveDestroyCallback(lldb::callback_token_t token)
Remove the specified callback. Return true if successful.
static LoadPluginCallbackType g_load_plugin_callback
Definition Debugger.h:798
bool GetShowStatusline() const
Definition Debugger.cpp:563
std::recursive_mutex m_script_interpreter_mutex
Definition Debugger.h:784
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:711
void SetPrompt(llvm::StringRef p)
Definition Debugger.cpp:416
llvm::StringRef GetSeparator() const
Definition Debugger.cpp:581
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:386
bool SetTerminalHeight(uint64_t term_height)
Definition Debugger.cpp:487
Broadcaster m_sync_broadcaster
Private debugger synchronization.
Definition Debugger.h:803
bool GetUseSourceCache() const
Definition Debugger.cpp:642
HostThread m_io_handler_thread
Definition Debugger.h:802
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:630
static llvm::StringRef GetStaticBroadcasterClass()
lldb::FileSP m_input_file_sp
Definition Debugger.h:757
bool SetREPLLanguage(lldb::LanguageType repl_lang)
Definition Debugger.cpp:454
bool GetAutoIndent() const
Definition Debugger.cpp:732
llvm::StringRef GetStopShowColumnAnsiSuffix() const
Definition Debugger.cpp:682
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:410
FormatEntity::Entry GetThreadStopFormat() const
Definition Debugger.cpp:432
void SetErrorFile(lldb::FileSP file)
bool GetAutoConfirm() const
Definition Debugger.cpp:365
TargetList m_target_list
Definition Debugger.h:769
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:437
lldb::callback_token_t m_destroy_callback_next_token
Definition Debugger.h:817
std::unique_ptr< SourceManager > m_source_manager_up
Definition Debugger.h:773
static lldb::DebuggerSP CreateInstance(lldb::LogOutputCallback log_callback=nullptr, void *baton=nullptr)
Definition Debugger.cpp:922
lldb::StopShowColumn GetStopShowColumn() const
Definition Debugger.cpp:669
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:749
bool SetScriptLanguage(lldb::ScriptLanguage script_lang)
Definition Debugger.cpp:444
lldb::LockableStreamFileSP m_error_stream_sp
Definition Debugger.h:759
bool SetShowInlineDiagnostics(bool)
Definition Debugger.cpp:778
bool LoadPlugin(const FileSpec &spec, Status &error)
Definition Debugger.cpp:834
void SetOutputFile(lldb::FileSP file)
uint64_t GetStopSourceLineCount(bool before) const
Definition Debugger.cpp:700
bool SetStatuslineFormat(const FormatEntity::Entry &format)
Definition Debugger.cpp:574
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:191
static void Destroy(lldb::DebuggerSP &debugger_sp)
Definition Debugger.cpp:966
SourceManager::SourceFileCache m_source_file_cache
Definition Debugger.h:777
llvm::StringRef GetPromptAnsiPrefix() const
Definition Debugger.cpp:404
lldb::StreamUP GetAsyncOutputStream()
void RedrawStatusline(std::optional< ExecutionContextRef > exe_ctx_ref)
Redraw the statusline if enabled.
void RunIOHandlerSync(const lldb::IOHandlerSP &reader_sp)
Run the given IO handler and block until it's complete.
Broadcaster & GetBroadcaster()
Get the public broadcaster for this debugger.
Definition Debugger.h:107
llvm::StringRef GetStopShowLineMarkerAnsiPrefix() const
Definition Debugger.cpp:688
bool GetShowDontUsePoHint() const
Definition Debugger.cpp:636
uint64_t GetTabSize() const
Definition Debugger.cpp:754
bool GetShowProgress() const
Definition Debugger.cpp:540
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:624
std::mutex m_output_flush_mutex
Definition Debugger.h:752
llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const
Definition Debugger.cpp:694
bool SetSeparator(llvm::StringRef s)
Definition Debugger.cpp:599
bool SetUseColor(bool use_color)
Definition Debugger.cpp:531
std::mutex m_statusline_mutex
Mutex protecting the m_statusline member.
Definition Debugger.h:792
const char * GetIOHandlerHelpPrologue()
Status SetInputString(const char *data)
bool GetUseAutosuggestion() const
Definition Debugger.cpp:606
Target & GetSelectedOrDummyTarget(bool prefer_dummy=false)
IOHandlerStack m_io_handler_stack
Definition Debugger.h:788
llvm::once_flag m_clear_once
Definition Debugger.h:806
static void SettingsTerminate()
Definition Debugger.cpp:832
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:449
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:465
Debugger(lldb::LogOutputCallback m_log_callback, void *baton)
llvm::StringRef GetExternalEditor() const
Definition Debugger.cpp:514
static size_t GetNumDebuggers()
FormatEntity::Entry GetThreadFormat() const
Definition Debugger.cpp:427
uint32_t m_interrupt_requested
Tracks interrupt requests.
Definition Debugger.h:830
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition Debugger.cpp:765
bool GetMarkHiddenFrames() const
Definition Debugger.cpp:657
lldb::thread_result_t DefaultEventHandler()
void PrintAsync(const char *s, size_t len, bool is_stdout)
lldb::LockableStreamFileSP GetErrorStreamSP()
Definition Debugger.h:712
llvm::StringRef GetPrompt() const
Definition Debugger.cpp:398
bool GetNotifyVoid() const
Definition Debugger.cpp:392
llvm::StringRef GetShowProgressAnsiPrefix() const
Definition Debugger.cpp:551
void AdoptTopIOHandlerFilesIfInvalid(lldb::FileSP &in, lldb::LockableStreamFileSP &out, lldb::LockableStreamFileSP &err)
FormatEntity::Entry GetFrameFormat() const
Definition Debugger.cpp:376
lldb::StopDisassemblyType GetStopDisassemblyDisplay() const
Definition Debugger.cpp:707
llvm::StringRef GetTopIOHandlerControlSequence(char ch)
void FlushProcessOutput(Process &process, bool flush_stdout, bool flush_stderr)
Force flushing the process's pending stdout and stderr to the debugger's asynchronous stdout and stde...
void CancelInterruptRequest()
Decrement the "interrupt requested" counter.
static void ReportDiagnosticImpl(lldb::Severity severity, std::string message, std::optional< lldb::user_id_t > debugger_id, std::once_flag *once)
std::vector< lldb::DebuggerSP > DebuggerList
Definition Debugger.h:102
bool SetAutoIndent(bool b)
Definition Debugger.cpp:738
friend class CommandInterpreter
Definition Debugger.h:658
llvm::StringRef GetStopShowColumnAnsiPrefix() const
Definition Debugger.cpp:676
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.
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:526
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:208
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:138
static PlatformProperties & GetGlobalPlatformProperties()
Definition Platform.cpp:144
static lldb::ScriptInterpreterSP GetScriptInterpreterForLanguage(lldb::ScriptLanguage script_lang, Debugger &debugger)
static void DebuggerInitialize(Debugger &debugger)
FollowForkMode GetFollowForkMode() const
Definition Process.cpp:376
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4599
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4583
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4591
A plug-in interface definition class for debugging a process.
Definition Process.h:355
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:737
static llvm::StringRef GetStaticBroadcasterClass()
Definition Process.cpp:427
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4786
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4767
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:1249
static void SettingsTerminate()
Definition Target.cpp:2784
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:171
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3283
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2794
@ eBroadcastBitBreakpointChanged
Definition Target.h:585
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:327
LoadScriptFromSymFile
Definition Target.h:57
@ eLoadScriptFromSymFileTrue
Definition Target.h:58
@ eLoadScriptFromSymFileFalse
Definition Target.h:59
@ eLoadScriptFromSymFileWarn
Definition Target.h:60
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.
@ eStateStopped
Process or thread is stopped and can be examined.
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::StructuredDataPlugin > StructuredDataPluginSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
StopDisassemblyType
Used to determine when to show disassembly.
@ eStopDisassemblyTypeNever
@ eStopDisassemblyTypeNoSource
@ eStopDisassemblyTypeAlways
@ eStopDisassemblyTypeNoDebugInfo
@ eStopShowColumnAnsi
@ eStopShowColumnCaret
@ eStopShowColumnNone
@ eStopShowColumnAnsiOrCaret
std::shared_ptr< lldb_private::Event > EventSP
std::shared_ptr< lldb_private::Listener > ListenerSP
int32_t callback_token_t
Definition lldb-types.h:81
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
void(* LogOutputCallback)(const char *, void *baton)
Definition lldb-types.h:73
std::shared_ptr< lldb_private::Target > TargetSP
std::unique_ptr< lldb_private::Stream > StreamUP
std::shared_ptr< lldb_private::File > FileSP
std::shared_ptr< lldb_private::REPL > REPLSP
lldb_private::DebuggerDestroyCallback callback
Definition Debugger.h:825
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