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 return SetTerminalDimensions(term_width, GetTerminalHeight());
467}
468
470 const uint32_t idx = ePropertyTerminalHeight;
472 idx, g_debugger_properties[idx].default_uint_value);
473}
474
475bool Debugger::SetTerminalHeight(uint64_t term_height) {
476 return SetTerminalDimensions(GetTerminalWidth(), term_height);
477}
478
479bool Debugger::SetTerminalDimensions(uint64_t term_width,
480 uint64_t term_height) {
481 // Set both properties before notifying, so observers never recompute from a
482 // mix of fresh and stale dimensions.
483 const bool width_success =
484 SetPropertyAtIndex(ePropertyTerminalWidth, term_width);
485 const bool height_success =
486 SetPropertyAtIndex(ePropertyTerminalHeight, term_height);
487
488 if (auto handler_sp = m_io_handler_stack.Top())
489 handler_sp->TerminalSizeChanged();
490
491 {
492 std::lock_guard<std::mutex> guard(m_statusline_mutex);
493 if (m_statusline)
494 m_statusline->TerminalSizeChanged();
495 }
496
497 return width_success && height_success;
498}
499
501 const uint32_t idx = ePropertyUseExternalEditor;
503 idx, g_debugger_properties[idx].default_uint_value != 0);
504}
505
507 const uint32_t idx = ePropertyUseExternalEditor;
508 return SetPropertyAtIndex(idx, b);
509}
510
511llvm::StringRef Debugger::GetExternalEditor() const {
512 const uint32_t idx = ePropertyExternalEditor;
514 idx, g_debugger_properties[idx].default_cstr_value);
515}
516
517bool Debugger::SetExternalEditor(llvm::StringRef editor) {
518 const uint32_t idx = ePropertyExternalEditor;
519 return SetPropertyAtIndex(idx, editor);
520}
521
523 const uint32_t idx = ePropertyUseColor;
525 idx, g_debugger_properties[idx].default_uint_value != 0);
526}
527
529 const uint32_t idx = ePropertyUseColor;
530 bool ret = SetPropertyAtIndex(idx, b);
531
534 return ret;
535}
536
538 const uint32_t idx = ePropertyShowProgress;
540 idx, g_debugger_properties[idx].default_uint_value != 0);
541}
542
543bool Debugger::SetShowProgress(bool show_progress) {
544 const uint32_t idx = ePropertyShowProgress;
545 return SetPropertyAtIndex(idx, show_progress);
546}
547
548llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const {
549 const uint32_t idx = ePropertyShowProgressAnsiPrefix;
551 idx, g_debugger_properties[idx].default_cstr_value);
552}
553
554llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const {
555 const uint32_t idx = ePropertyShowProgressAnsiSuffix;
557 idx, g_debugger_properties[idx].default_cstr_value);
558}
559
561 const uint32_t idx = ePropertyShowStatusline;
563 idx, g_debugger_properties[idx].default_uint_value != 0);
564}
565
567 constexpr uint32_t idx = ePropertyStatuslineFormat;
569}
570
572 constexpr uint32_t idx = ePropertyStatuslineFormat;
573 bool ret = SetPropertyAtIndex(idx, format);
574 RedrawStatusline(std::nullopt);
575 return ret;
576}
577
578llvm::StringRef Debugger::GetSeparator() const {
579 constexpr uint32_t idx = ePropertySeparator;
581 idx, g_debugger_properties[idx].default_cstr_value);
582}
583
584llvm::StringRef Debugger::GetDisabledAnsiPrefix() const {
585 const uint32_t idx = ePropertyShowDisabledAnsiPrefix;
587 idx, g_debugger_properties[idx].default_cstr_value);
588}
589
590llvm::StringRef Debugger::GetDisabledAnsiSuffix() const {
591 const uint32_t idx = ePropertyShowDisabledAnsiSuffix;
593 idx, g_debugger_properties[idx].default_cstr_value);
594}
595
596bool Debugger::SetSeparator(llvm::StringRef s) {
597 constexpr uint32_t idx = ePropertySeparator;
598 bool ret = SetPropertyAtIndex(idx, s);
599 RedrawStatusline(std::nullopt);
600 return ret;
601}
602
604 const uint32_t idx = ePropertyShowAutosuggestion;
606 idx, g_debugger_properties[idx].default_uint_value != 0);
607}
608
610 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix;
612 idx, g_debugger_properties[idx].default_cstr_value);
613}
614
616 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix;
618 idx, g_debugger_properties[idx].default_cstr_value);
619}
620
621llvm::StringRef Debugger::GetRegexMatchAnsiPrefix() const {
622 const uint32_t idx = ePropertyShowRegexMatchAnsiPrefix;
624 idx, g_debugger_properties[idx].default_cstr_value);
625}
626
627llvm::StringRef Debugger::GetRegexMatchAnsiSuffix() const {
628 const uint32_t idx = ePropertyShowRegexMatchAnsiSuffix;
630 idx, g_debugger_properties[idx].default_cstr_value);
631}
632
634 const uint32_t idx = ePropertyShowDontUsePoHint;
636 idx, g_debugger_properties[idx].default_uint_value != 0);
637}
638
640 const uint32_t idx = ePropertyUseSourceCache;
642 idx, g_debugger_properties[idx].default_uint_value != 0);
643}
644
646 const uint32_t idx = ePropertyUseSourceCache;
647 bool ret = SetPropertyAtIndex(idx, b);
648 if (!ret) {
649 m_source_file_cache.Clear();
650 }
651 return ret;
652}
653
655 const uint32_t idx = ePropertyMarkHiddenFrames;
657 idx, g_debugger_properties[idx].default_uint_value != 0);
658}
659
661 const uint32_t idx = ePropertyHighlightSource;
663 idx, g_debugger_properties[idx].default_uint_value != 0);
664}
665
667 const uint32_t idx = ePropertyStopShowColumn;
669 idx, static_cast<lldb::StopShowColumn>(
670 g_debugger_properties[idx].default_uint_value));
671}
672
674 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
676 idx, g_debugger_properties[idx].default_cstr_value);
677}
678
680 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
682 idx, g_debugger_properties[idx].default_cstr_value);
683}
684
686 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
688 idx, g_debugger_properties[idx].default_cstr_value);
689}
690
692 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
694 idx, g_debugger_properties[idx].default_cstr_value);
695}
696
697uint64_t Debugger::GetStopSourceLineCount(bool before) const {
698 const uint32_t idx =
699 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
701 idx, g_debugger_properties[idx].default_uint_value);
702}
703
705 const uint32_t idx = ePropertyStopDisassemblyDisplay;
707 idx, static_cast<lldb::StopDisassemblyType>(
708 g_debugger_properties[idx].default_uint_value));
709}
710
712 const uint32_t idx = ePropertyStopDisassemblyCount;
714 idx, g_debugger_properties[idx].default_uint_value);
715}
716
718 const uint32_t idx = ePropertyAutoOneLineSummaries;
720 idx, g_debugger_properties[idx].default_uint_value != 0);
721}
722
724 const uint32_t idx = ePropertyEscapeNonPrintables;
726 idx, g_debugger_properties[idx].default_uint_value != 0);
727}
728
730 const uint32_t idx = ePropertyAutoIndent;
732 idx, g_debugger_properties[idx].default_uint_value != 0);
733}
734
736 const uint32_t idx = ePropertyAutoIndent;
737 return SetPropertyAtIndex(idx, b);
738}
739
741 const uint32_t idx = ePropertyPrintDecls;
743 idx, g_debugger_properties[idx].default_uint_value != 0);
744}
745
747 const uint32_t idx = ePropertyPrintDecls;
748 return SetPropertyAtIndex(idx, b);
749}
750
751uint64_t Debugger::GetTabSize() const {
752 const uint32_t idx = ePropertyTabSize;
754 idx, g_debugger_properties[idx].default_uint_value);
755}
756
757bool Debugger::SetTabSize(uint64_t tab_size) {
758 const uint32_t idx = ePropertyTabSize;
759 return SetPropertyAtIndex(idx, tab_size);
760}
761
763 const uint32_t idx = ePropertyDWIMPrintVerbosity;
765 idx, static_cast<lldb::DWIMPrintVerbosity>(
766 g_debugger_properties[idx].default_uint_value != 0));
767}
768
770 const uint32_t idx = ePropertyShowInlineDiagnostics;
772 idx, g_debugger_properties[idx].default_uint_value);
773}
774
776 const uint32_t idx = ePropertyShowInlineDiagnostics;
777 return SetPropertyAtIndex(idx, b);
778}
779
780#pragma mark Debugger
781
782// const DebuggerPropertiesSP &
783// Debugger::GetSettings() const
784//{
785// return m_properties_sp;
786//}
787//
788
790 assert(g_debugger_list_ptr == nullptr &&
791 "Debugger::Initialize called more than once!");
792 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
794 g_thread_pool = new llvm::DefaultThreadPool(llvm::optimal_concurrency());
795 g_load_plugin_callback = load_plugin_callback;
796}
797
799 assert(g_debugger_list_ptr &&
800 "Debugger::Terminate called without a matching Debugger::Initialize!");
801
802 {
803 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
805 for (const auto &debugger : *g_debugger_list_ptr)
806 debugger->HandleDestroyCallback();
807 }
808
809 if (g_thread_pool) {
810 // The destructor will wait for all the threads to complete.
811 delete g_thread_pool;
812 }
813
814 {
815 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
817 for (const DebuggerSP &debugger : *g_debugger_list_ptr)
818 debugger->Clear();
819 g_debugger_list_ptr->clear();
820
821 delete g_debugger_list_ptr;
822 g_debugger_list_ptr = nullptr;
823 }
824 }
825}
826
828
830
833 llvm::sys::DynamicLibrary dynlib =
834 g_load_plugin_callback(shared_from_this(), spec, error);
835 if (dynlib.isValid()) {
836 m_loaded_plugins.push_back(dynlib);
837 return true;
838 }
839 } else {
840 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
841 // if the public API layer isn't available (code is linking against all of
842 // the internal LLDB static libraries), then we can't load plugins
843 error = Status::FromErrorString("Public API layer is not available");
844 }
845 return false;
846}
847
849LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
850 llvm::StringRef path) {
852
853 static constexpr llvm::StringLiteral g_dylibext(".dylib");
854 static constexpr llvm::StringLiteral g_solibext(".so");
855
856 if (!baton)
858
859 Debugger *debugger = (Debugger *)baton;
860
861 namespace fs = llvm::sys::fs;
862 // If we have a regular file, a symbolic link or unknown file type, try and
863 // process the file. We must handle unknown as sometimes the directory
864 // enumeration might be enumerating a file system that doesn't have correct
865 // file type information.
866 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
867 ft == fs::file_type::type_unknown) {
868 FileSpec plugin_file_spec(path);
869 FileSystem::Instance().Resolve(plugin_file_spec);
870
871 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
872 plugin_file_spec.GetFileNameExtension() != g_solibext) {
874 }
875
876 Status plugin_load_error;
877 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
878
880 } else if (ft == fs::file_type::directory_file ||
881 ft == fs::file_type::symlink_file ||
882 ft == fs::file_type::type_unknown) {
883 // Try and recurse into anything that a directory or symbolic link. We must
884 // also do this for unknown as sometimes the directory enumeration might be
885 // enumerating a file system that doesn't have correct file type
886 // information.
888 }
889
891}
892
894 const bool find_directories = true;
895 const bool find_files = true;
896 const bool find_other = true;
897 char dir_path[PATH_MAX];
898 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
899 if (FileSystem::Instance().Exists(dir_spec) &&
900 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
901 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
902 find_files, find_other,
903 LoadPluginCallback, this);
904 }
905 }
906
907 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
908 if (FileSystem::Instance().Exists(dir_spec) &&
909 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
910 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
911 find_files, find_other,
912 LoadPluginCallback, this);
913 }
914 }
915
917}
918
920 void *baton) {
923 helper([](lldb_private::telemetry::DebuggerInfo *entry) {
925 });
926 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
927 helper.SetDebugger(debugger_sp.get());
928 {
929 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
931 g_debugger_list_ptr->push_back(debugger_sp);
932 }
933 debugger_sp->InstanceInitialize();
934 return debugger_sp;
935}
936
942
944 const lldb::user_id_t user_id = GetID();
945 // Invoke and remove all the callbacks in an FIFO order. Callbacks which are
946 // added during this loop will be appended, invoked and then removed last.
947 // Callbacks which are removed during this loop will not be invoked.
948 while (true) {
949 DestroyCallbackInfo callback_info;
950 {
951 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
952 if (m_destroy_callbacks.empty())
953 break;
954 // Pop the first item in the list
955 callback_info = m_destroy_callbacks.front();
957 }
958 // Call the destroy callback with user id and baton
959 callback_info.callback(user_id, callback_info.baton);
960 }
961}
962
963void Debugger::Destroy(DebuggerSP &debugger_sp) {
964 if (!debugger_sp)
965 return;
966
967 debugger_sp->HandleDestroyCallback();
968 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
969
970 if (cmd_interpreter.GetSaveSessionOnQuit()) {
971 CommandReturnObject result(debugger_sp->GetUseColor());
972 cmd_interpreter.SaveTranscript(result);
973 if (result.Succeeded())
974 (*debugger_sp->GetAsyncOutputStream())
975 << result.GetOutputString() << '\n';
976 else
977 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorString() << '\n';
978 }
979
980 debugger_sp->Clear();
981
982 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
984 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
985 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
986 if ((*pos).get() == debugger_sp.get()) {
987 g_debugger_list_ptr->erase(pos);
988 return;
989 }
990 }
991 }
992}
993
995Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) {
996 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
998 return nullptr;
999
1000 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1001 if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name)
1002 return debugger_sp;
1003 }
1004
1005 return nullptr;
1006}
1007
1009 static constexpr llvm::StringLiteral class_name("lldb.debugger");
1010 return class_name;
1011}
1012
1014 : UserID(g_unique_id++),
1015 Properties(std::make_shared<OptionValueProperties>()),
1016 m_input_file_sp(std::make_shared<NativeFile>(
1017 stdin, File::eOpenOptionReadOnly, NativeFile::Unowned)),
1018 m_output_stream_sp(std::make_shared<LockableStreamFile>(
1019 stdout, NativeFile::Unowned, m_output_mutex)),
1020 m_error_stream_sp(std::make_shared<LockableStreamFile>(
1021 stderr, NativeFile::Unowned, m_output_mutex)),
1022 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
1024 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
1027 std::make_unique<CommandInterpreter>(*this, false)),
1029 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()),
1031 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
1035 // Initialize the debugger properties as early as possible as other parts of
1036 // LLDB will start querying them during construction.
1037 m_collection_sp->Initialize(g_debugger_properties_def);
1038 m_collection_sp->AppendProperty(
1039 "target", "Settings specify to debugging targets.", true,
1041 m_collection_sp->AppendProperty(
1042 "platform", "Platform settings.", true,
1044 m_collection_sp->AppendProperty(
1045 "symbols", "Symbol lookup and cache settings.", true,
1047 m_collection_sp->AppendProperty(
1048 LanguageProperties::GetSettingName(), "Language settings.", true,
1051 m_collection_sp->AppendProperty(
1052 "interpreter",
1053 "Settings specify to the debugger's command interpreter.", true,
1054 m_command_interpreter_up->GetValueProperties());
1055 }
1056#ifndef NDEBUG
1057 m_collection_sp->AppendProperty(
1058 "testing", "Testing-only settings.", /*is_global=*/true,
1060#endif
1061
1062 if (log_callback)
1064 std::make_shared<CallbackLogHandler>(log_callback, baton);
1065 m_command_interpreter_up->Initialize();
1066 // Always add our default platform to the platform list
1067 PlatformSP default_platform_sp(Platform::GetHostPlatform());
1068 assert(default_platform_sp);
1069 m_platform_list.Append(default_platform_sp, true);
1070
1071 // Create the dummy target.
1072 {
1074 if (!arch.IsValid())
1075 arch = HostInfo::GetArchitecture();
1076 assert(arch.IsValid() && "No valid default or host archspec");
1077 const bool is_dummy_target = true;
1078 m_dummy_target_sp.reset(
1079 new Target(*this, arch, default_platform_sp, is_dummy_target));
1080 }
1081 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
1082
1083 OptionValueUInt64 *term_width =
1084 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1085 ePropertyTerminalWidth);
1086 term_width->SetMinimumValue(10);
1087
1088 OptionValueUInt64 *term_height =
1089 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1090 ePropertyTerminalHeight);
1091 term_height->SetMinimumValue(10);
1092
1093 // Turn off use-color if this is a dumb terminal.
1094 const char *term = getenv("TERM");
1095 auto disable_color = [&]() {
1096 SetUseColor(false);
1097 SetSeparator("| ");
1098 };
1099
1100 if (term && !strcmp(term, "dumb"))
1101 disable_color();
1102 // Turn off use-color if we don't write to a terminal with color support.
1103 if (!GetOutputFileSP()->GetIsTerminalWithColors())
1104 disable_color();
1105
1106 if (Diagnostics::Enabled()) {
1108 [this](const FileSpec &dir) -> llvm::Error {
1109 for (auto &entry : m_stream_handlers) {
1110 llvm::StringRef log_path = entry.first();
1111 llvm::StringRef file_name = llvm::sys::path::filename(log_path);
1112 FileSpec destination = dir.CopyByAppendingPathComponent(file_name);
1113 std::error_code ec =
1114 llvm::sys::fs::copy_file(log_path, destination.GetPath());
1115 if (ec)
1116 return llvm::errorCodeToError(ec);
1117 }
1118 return llvm::Error::success();
1119 });
1120 }
1121
1122#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
1123 // Enabling use of ANSI color codes because LLDB is using them to highlight
1124 // text.
1125 llvm::sys::Process::UseANSIEscapeCodes(true);
1126#endif
1127}
1128
1130
1132 // Make sure we call this function only once. With the C++ global destructor
1133 // chain having a list of debuggers and with code that can be running on
1134 // other threads, we need to ensure this doesn't happen multiple times.
1135 //
1136 // The following functions call Debugger::Clear():
1137 // Debugger::~Debugger();
1138 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
1139 // static void Debugger::Terminate();
1140 llvm::call_once(m_clear_once, [this]() {
1143 assert(this == info->debugger);
1144 (void)this;
1145 info->is_exit_entry = true;
1146 },
1147 this);
1151 m_listener_sp->Clear();
1152 for (TargetSP target_sp : m_target_list.Targets()) {
1153 if (target_sp) {
1154 if (ProcessSP process_sp = target_sp->GetProcessSP())
1155 process_sp->Finalize(false /* not destructing */);
1156 target_sp->Destroy();
1157 }
1158 }
1159 m_broadcaster_manager_sp->Clear();
1160
1161 // Close the input file _before_ we close the input read communications
1162 // class as it does NOT own the input file, our m_input_file does.
1163 m_terminal_state.Clear();
1164 GetInputFile().Close();
1165
1166 m_command_interpreter_up->Clear();
1167
1170 });
1171}
1172
1174 return !m_command_interpreter_up->GetSynchronous();
1175}
1176
1177void Debugger::SetAsyncExecution(bool async_execution) {
1178 m_command_interpreter_up->SetSynchronous(!async_execution);
1179}
1180
1181static inline int OpenPipe(int fds[2], std::size_t size) {
1182#ifdef _WIN32
1183 return _pipe(fds, size, O_BINARY);
1184#else
1185 (void)size;
1186 return pipe(fds);
1187#endif
1188}
1189
1191 Status result;
1192 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
1193 int fds[2] = {-1, -1};
1194
1195 if (data == nullptr) {
1196 result = Status::FromErrorString("String data is null");
1197 return result;
1198 }
1199
1200 size_t size = strlen(data);
1201 if (size == 0) {
1202 result = Status::FromErrorString("String data is empty");
1203 return result;
1204 }
1205
1206 if (OpenPipe(fds, size) != 0) {
1207 result = Status::FromErrorString(
1208 "can't create pipe file descriptors for LLDB commands");
1209 return result;
1210 }
1211
1212 int r = write(fds[WRITE], data, size);
1213 (void)r;
1214 // Close the write end of the pipe, so that the command interpreter will exit
1215 // when it consumes all the data.
1216 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
1217
1218 // Open the read file descriptor as a FILE * that we can return as an input
1219 // handle.
1220 FILE *commands_file = fdopen(fds[READ], "rb");
1221 if (commands_file == nullptr) {
1223 "fdopen(%i, \"rb\") failed (errno = %i) "
1224 "when trying to open LLDB commands pipe",
1225 fds[READ], errno);
1226 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
1227 return result;
1228 }
1229
1230 SetInputFile((FileSP)std::make_shared<NativeFile>(
1231 commands_file, File::eOpenOptionReadOnly, true));
1232 return result;
1233}
1234
1236 assert(file_sp && file_sp->IsValid());
1237 m_input_file_sp = std::move(file_sp);
1238 // Save away the terminal state if that is relevant, so that we can restore
1239 // it in RestoreInputState.
1241}
1242
1244 assert(file_sp && file_sp->IsValid());
1246 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1247}
1248
1250 assert(file_sp && file_sp->IsValid());
1252 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1253}
1254
1256 {
1257 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1258 if (m_statusline)
1259 m_statusline->Disable();
1260 }
1261 int fd = GetInputFile().GetDescriptor();
1262 if (fd != File::kInvalidDescriptor)
1263 m_terminal_state.Save(fd, true);
1264}
1265
1267 m_terminal_state.Restore();
1268 {
1269 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1270 if (m_statusline)
1271 m_statusline->Enable(
1272 GetSelectedExecutionContext(/*adopt_dummy_target=*/true));
1273 }
1274}
1275
1277 std::optional<ExecutionContextRef> exe_ctx_ref) {
1278 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1279
1280 if (!m_statusline)
1281 return;
1282
1283 m_statusline->Redraw(exe_ctx_ref);
1284}
1285
1287 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1288
1289 if (!m_statusline)
1290 return;
1291
1292 m_statusline->ClearExecutionContext();
1293}
1294
1297 return ExecutionContext(GetSelectedExecutionContextRef(adopt_dummy_target));
1298}
1299
1302 if (TargetSP selected_target_sp = m_target_list.GetSelectedTarget())
1303 return ExecutionContextRef(selected_target_sp.get(),
1304 /*adopt_selected=*/true);
1305
1306 if (adopt_dummy_target)
1308 /*adopt_selected=*/false);
1309
1310 return ExecutionContextRef();
1311}
1312
1314 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1315 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1316 if (reader_sp)
1317 reader_sp->Interrupt();
1318}
1319
1321 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1322 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1323 if (reader_sp)
1324 reader_sp->GotEOF();
1325}
1326
1328 // The bottom input reader should be the main debugger input reader. We do
1329 // not want to close that one here.
1330 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1331 while (m_io_handler_stack.GetSize() > 1) {
1332 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1333 if (reader_sp)
1334 PopIOHandler(reader_sp);
1335 }
1336}
1337
1339 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1340 while (true) {
1341 if (!reader_sp)
1342 break;
1343
1344 reader_sp->Run();
1345 {
1346 std::lock_guard<std::recursive_mutex> guard(
1348
1349 // Remove all input readers that are done from the top of the stack
1350 while (true) {
1351 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1352 if (top_reader_sp && top_reader_sp->GetIsDone())
1353 PopIOHandler(top_reader_sp);
1354 else
1355 break;
1356 }
1357 reader_sp = m_io_handler_stack.Top();
1358 }
1359 }
1361}
1362
1364 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1365
1366 PushIOHandler(reader_sp);
1367 IOHandlerSP top_reader_sp = reader_sp;
1368
1369 while (top_reader_sp) {
1370 top_reader_sp->Run();
1371
1372 // Don't unwind past the starting point.
1373 if (top_reader_sp.get() == reader_sp.get()) {
1374 if (PopIOHandler(reader_sp))
1375 break;
1376 }
1377
1378 // If we pushed new IO handlers, pop them if they're done or restart the
1379 // loop to run them if they're not.
1380 while (true) {
1381 top_reader_sp = m_io_handler_stack.Top();
1382 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1383 PopIOHandler(top_reader_sp);
1384 // Don't unwind past the starting point.
1385 if (top_reader_sp.get() == reader_sp.get())
1386 return;
1387 } else {
1388 break;
1389 }
1390 }
1391 }
1392}
1393
1395 return m_io_handler_stack.IsTop(reader_sp);
1396}
1397
1399 IOHandler::Type second_top_type) {
1400 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1401}
1402
1403void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1404 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1405 if (!printed) {
1406 LockableStreamFileSP stream_sp =
1408 LockedStreamFile locked_stream = stream_sp->Lock();
1409 locked_stream.Write(s, len);
1410 }
1411}
1412
1414 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1415}
1416
1418 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1419}
1420
1422 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1423}
1424
1426 return PopIOHandler(reader_sp);
1427}
1428
1430 bool cancel_top_handler) {
1431 PushIOHandler(reader_sp, cancel_top_handler);
1432}
1433
1436 LockableStreamFileSP &err) {
1437 // Before an IOHandler runs, it must have in/out/err streams. This function
1438 // is called when one ore more of the streams are nullptr. We use the top
1439 // input reader's in/out/err streams, or fall back to the debugger file
1440 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1441
1442 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1443 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1444 // If no STDIN has been set, then set it appropriately
1445 if (!in || !in->IsValid()) {
1446 if (top_reader_sp)
1447 in = top_reader_sp->GetInputFileSP();
1448 else
1449 in = GetInputFileSP();
1450 // If there is nothing, use stdin
1451 if (!in)
1452 in = std::make_shared<NativeFile>(stdin, File::eOpenOptionReadOnly,
1454 }
1455 // If no STDOUT has been set, then set it appropriately
1456 if (!out || !out->GetUnlockedFile().IsValid()) {
1457 if (top_reader_sp)
1458 out = top_reader_sp->GetOutputStreamFileSP();
1459 else
1460 out = GetOutputStreamSP();
1461 // If there is nothing, use stdout
1462 if (!out)
1463 out = std::make_shared<LockableStreamFile>(stdout, NativeFile::Unowned,
1465 }
1466 // If no STDERR has been set, then set it appropriately
1467 if (!err || !err->GetUnlockedFile().IsValid()) {
1468 if (top_reader_sp)
1469 err = top_reader_sp->GetErrorStreamFileSP();
1470 else
1471 err = GetErrorStreamSP();
1472 // If there is nothing, use stderr
1473 if (!err)
1474 err = std::make_shared<LockableStreamFile>(stderr, NativeFile::Unowned,
1476 }
1477}
1478
1480 bool cancel_top_handler) {
1481 if (!reader_sp)
1482 return;
1483
1484 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1485
1486 // Get the current top input reader...
1487 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1488
1489 // Don't push the same IO handler twice...
1490 if (reader_sp == top_reader_sp)
1491 return;
1492
1493 // Push our new input reader
1494 m_io_handler_stack.Push(reader_sp);
1495 reader_sp->Activate();
1496
1497 // Interrupt the top input reader to it will exit its Run() function and let
1498 // this new input reader take over
1499 if (top_reader_sp) {
1500 top_reader_sp->Deactivate();
1501 if (cancel_top_handler)
1502 top_reader_sp->Cancel();
1503 }
1504}
1505
1506bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1507 if (!pop_reader_sp)
1508 return false;
1509
1510 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1511
1512 // The reader on the stop of the stack is done, so let the next read on the
1513 // stack refresh its prompt and if there is one...
1514 if (m_io_handler_stack.IsEmpty())
1515 return false;
1516
1517 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1518
1519 if (pop_reader_sp != reader_sp)
1520 return false;
1521
1522 reader_sp->Deactivate();
1523 reader_sp->Cancel();
1524 m_io_handler_stack.Pop();
1525
1526 reader_sp = m_io_handler_stack.Top();
1527 if (reader_sp)
1528 reader_sp->Activate();
1529
1530 return true;
1531}
1532
1534 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1535 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1536 if (reader_sp)
1537 reader_sp->Refresh();
1538}
1539
1541 return std::make_unique<StreamAsynchronousIO>(*this,
1543}
1544
1546 return std::make_unique<StreamAsynchronousIO>(*this,
1548}
1549
1551 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1553}
1554
1556 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1557 if (m_interrupt_requested > 0)
1559}
1560
1562 // This is the one we should call internally. This will return true either
1563 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1564 // or if we are on the IOHandler thread and there's a CommandInterpreter
1565 // interrupt.
1567 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1568 return m_interrupt_requested != 0;
1569 }
1571}
1572
1574 std::string function_name, const llvm::formatv_object_base &payload)
1575 : m_function_name(std::move(function_name)),
1576 m_interrupt_time(std::chrono::system_clock::now()),
1577 m_thread_id(llvm::get_threadid()) {
1578 llvm::raw_string_ostream desc(m_description);
1579 desc << payload << "\n";
1580}
1581
1583 // For now, just log the description:
1584 Log *log = GetLog(LLDBLog::Host);
1585 LLDB_LOG(log, "Interruption: {0}", report.m_description);
1586}
1587
1589 DebuggerList result;
1590 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1591 if (g_debugger_list_ptr) {
1592 for (auto debugger_sp : *g_debugger_list_ptr) {
1593 if (debugger_sp->InterruptRequested())
1594 result.push_back(debugger_sp);
1595 }
1596 }
1597 return result;
1598}
1599
1601 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1603 return 0;
1604
1605 return g_debugger_list_ptr->size();
1606}
1607
1609 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1611 return nullptr;
1612
1613 if (index < g_debugger_list_ptr->size())
1614 return g_debugger_list_ptr->at(index);
1615
1616 return nullptr;
1617}
1618
1620 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1622 return nullptr;
1623
1624 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
1625 if (debugger_sp->GetID() == id)
1626 return debugger_sp;
1627 }
1628
1629 return nullptr;
1630}
1631
1633 const SymbolContext *sc,
1634 const SymbolContext *prev_sc,
1635 const ExecutionContext *exe_ctx,
1636 const Address *addr, Stream &s) {
1637 FormatEntity::Entry format_entry;
1638
1639 if (format == nullptr) {
1640 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) {
1641 format_entry =
1643 format = &format_entry;
1644 }
1645 if (format == nullptr) {
1646 FormatEntity::Parse("${addr}: ", format_entry);
1647 format = &format_entry;
1648 }
1649 }
1650 bool function_changed = false;
1651 bool initial_function = false;
1652 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1653 if (sc && (sc->function || sc->symbol)) {
1654 if (prev_sc->symbol && sc->symbol) {
1655 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1656 prev_sc->symbol->GetType())) {
1657 function_changed = true;
1658 }
1659 } else if (prev_sc->function && sc->function) {
1660 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1661 function_changed = true;
1662 }
1663 }
1664 }
1665 }
1666 // The first context on a list of instructions will have a prev_sc that has
1667 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1668 // would return false. But we do get a prev_sc pointer.
1669 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1670 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1671 initial_function = true;
1672 }
1673 return FormatEntity::Formatter(sc, exe_ctx, addr, function_changed,
1674 initial_function)
1675 .Format(*format, s);
1676}
1677
1678void Debugger::AssertCallback(llvm::StringRef message,
1679 llvm::StringRef backtrace,
1680 llvm::StringRef prompt) {
1681 Debugger::ReportError(llvm::formatv("{0}\n{1}{2}\n{3}", message, backtrace,
1682 GetVersion(), prompt)
1683 .str());
1684}
1685
1687 void *baton) {
1688 // For simplicity's sake, I am not going to deal with how to close down any
1689 // open logging streams, I just redirect everything from here on out to the
1690 // callback.
1692 std::make_shared<CallbackLogHandler>(log_callback, baton);
1693}
1694
1696 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1697 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1698 m_destroy_callbacks.clear();
1700 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1701}
1702
1704 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1705 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1707 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1708 return token;
1709}
1710
1712 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1713 for (auto it = m_destroy_callbacks.begin(); it != m_destroy_callbacks.end();
1714 ++it) {
1715 if (it->token == token) {
1716 m_destroy_callbacks.erase(it);
1717 return true;
1718 }
1719 }
1720 return false;
1721}
1722
1723static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1724 std::string title, std::string details,
1725 uint64_t completed, uint64_t total,
1726 bool is_debugger_specific,
1727 uint32_t progress_broadcast_bit) {
1728 // Only deliver progress events if we have any progress listeners.
1729 if (!debugger.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit))
1730 return;
1731
1732 EventSP event_sp(new Event(
1733 progress_broadcast_bit,
1734 new ProgressEventData(progress_id, std::move(title), std::move(details),
1735 completed, total, is_debugger_specific)));
1736 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1737}
1738
1739void Debugger::ReportProgress(uint64_t progress_id, std::string title,
1740 std::string details, uint64_t completed,
1741 uint64_t total,
1742 std::optional<lldb::user_id_t> debugger_id,
1743 uint32_t progress_broadcast_bit) {
1744 // Check if this progress is for a specific debugger.
1745 if (debugger_id) {
1746 // It is debugger specific, grab it and deliver the event if the debugger
1747 // still exists.
1748 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1749 if (debugger_sp)
1750 PrivateReportProgress(*debugger_sp, progress_id, std::move(title),
1751 std::move(details), completed, total,
1752 /*is_debugger_specific*/ true,
1753 progress_broadcast_bit);
1754 return;
1755 }
1756 // The progress event is not debugger specific, iterate over all debuggers
1757 // and deliver a progress event to each one.
1758 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1759 if (g_debugger_list_ptr) {
1760 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1761 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1762 PrivateReportProgress(*(*pos), progress_id, title, details, completed,
1763 total, /*is_debugger_specific*/ false,
1764 progress_broadcast_bit);
1765 }
1766}
1767
1768static void PrivateReportDiagnostic(Debugger &debugger, Severity severity,
1769 std::string message,
1770 bool debugger_specific) {
1771 uint32_t event_type = 0;
1772 switch (severity) {
1773 case eSeverityInfo:
1774 assert(false && "eSeverityInfo should not be broadcast");
1775 return;
1776 case eSeverityWarning:
1777 event_type = lldb::eBroadcastBitWarning;
1778 break;
1779 case eSeverityError:
1780 event_type = lldb::eBroadcastBitError;
1781 break;
1782 }
1783
1784 Broadcaster &broadcaster = debugger.GetBroadcaster();
1785 if (!broadcaster.EventTypeHasListeners(event_type)) {
1786 // Diagnostics are too important to drop. If nobody is listening, print the
1787 // diagnostic directly to the debugger's error stream.
1788 DiagnosticEventData event_data(severity, std::move(message),
1789 debugger_specific);
1790 event_data.Dump(debugger.GetAsyncErrorStream().get());
1791 return;
1792 }
1793 EventSP event_sp = std::make_shared<Event>(
1794 event_type,
1795 new DiagnosticEventData(severity, std::move(message), debugger_specific));
1796 broadcaster.BroadcastEvent(event_sp);
1797}
1798
1799void Debugger::ReportDiagnosticImpl(Severity severity, std::string message,
1800 std::optional<lldb::user_id_t> debugger_id,
1801 std::once_flag *once) {
1802 auto ReportDiagnosticLambda = [&]() {
1803 // Always log diagnostics to the system log.
1804 Host::SystemLog(severity, message);
1805
1806 // The diagnostic subsystem is optional but we still want to broadcast
1807 // events when it's disabled.
1809 Diagnostics::Instance().Report(message);
1810
1811 // We don't broadcast info events.
1812 if (severity == lldb::eSeverityInfo)
1813 return;
1814
1815 // Check if this diagnostic is for a specific debugger.
1816 if (debugger_id) {
1817 // It is debugger specific, grab it and deliver the event if the debugger
1818 // still exists.
1819 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1820 if (debugger_sp)
1821 PrivateReportDiagnostic(*debugger_sp, severity, std::move(message),
1822 true);
1823 return;
1824 }
1825 // The diagnostic event is not debugger specific, iterate over all debuggers
1826 // and deliver a diagnostic event to each one.
1827 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1828 if (g_debugger_list_ptr) {
1829 for (const auto &debugger : *g_debugger_list_ptr)
1830 PrivateReportDiagnostic(*debugger, severity, message, false);
1831 }
1832 };
1833
1834 if (once)
1835 std::call_once(*once, ReportDiagnosticLambda);
1836 else
1837 ReportDiagnosticLambda();
1838}
1839
1840void Debugger::ReportWarning(std::string message,
1841 std::optional<lldb::user_id_t> debugger_id,
1842 std::once_flag *once) {
1843 ReportDiagnosticImpl(eSeverityWarning, std::move(message), debugger_id, once);
1844}
1845
1846void Debugger::ReportError(std::string message,
1847 std::optional<lldb::user_id_t> debugger_id,
1848 std::once_flag *once) {
1849 ReportDiagnosticImpl(eSeverityError, std::move(message), debugger_id, once);
1850}
1851
1852void Debugger::ReportInfo(std::string message,
1853 std::optional<lldb::user_id_t> debugger_id,
1854 std::once_flag *once) {
1855 ReportDiagnosticImpl(eSeverityInfo, std::move(message), debugger_id, once);
1856}
1857
1859 std::lock_guard<std::mutex> guard(GetDebuggerListMutex());
1861 return;
1862
1863 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1864 EventSP event_sp = std::make_shared<Event>(
1866 new SymbolChangeEventData(debugger_sp, module_spec));
1867 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1868 }
1869}
1870
1871static std::shared_ptr<LogHandler>
1872CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1873 size_t buffer_size) {
1874 switch (log_handler_kind) {
1875 case eLogHandlerStream:
1876 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1878 return std::make_shared<RotatingLogHandler>(buffer_size);
1879 case eLogHandlerSystem:
1880 return std::make_shared<SystemLogHandler>();
1882 return {};
1883 }
1884 return {};
1885}
1886
1887bool Debugger::EnableLog(llvm::StringRef channel,
1888 llvm::ArrayRef<const char *> categories,
1889 llvm::StringRef log_file, uint32_t log_options,
1890 size_t buffer_size, LogHandlerKind log_handler_kind,
1891 llvm::raw_ostream &error_stream) {
1892
1893 std::shared_ptr<LogHandler> log_handler_sp;
1895 log_handler_sp = m_callback_handler_sp;
1896 // For now when using the callback mode you always get thread & timestamp.
1897 log_options |=
1899 } else if (log_file.empty()) {
1900 log_handler_sp =
1901 CreateLogHandler(log_handler_kind, GetOutputFileSP()->GetDescriptor(),
1902 /*should_close=*/false, buffer_size);
1903 } else {
1904 auto pos = m_stream_handlers.find(log_file);
1905 if (pos != m_stream_handlers.end())
1906 log_handler_sp = pos->second.lock();
1907 if (!log_handler_sp) {
1908 File::OpenOptions flags =
1910 if (log_options & LLDB_LOG_OPTION_APPEND)
1911 flags |= File::eOpenOptionAppend;
1912 else
1914 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1915 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1916 if (!file) {
1917 error_stream << "Unable to open log file '" << log_file
1918 << "': " << llvm::toString(file.takeError()) << "\n";
1919 return false;
1920 }
1921
1922 log_handler_sp =
1923 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1924 /*should_close=*/true, buffer_size);
1925 m_stream_handlers[log_file] = log_handler_sp;
1926 }
1927 }
1928 assert(log_handler_sp);
1929
1930 if (log_options == 0)
1932
1933 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories,
1934 error_stream);
1935}
1936
1939 std::optional<lldb::ScriptLanguage> language) {
1940 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1941 lldb::ScriptLanguage script_language =
1942 language ? *language : GetScriptLanguage();
1943
1944 if (!m_script_interpreters[script_language]) {
1945 if (!can_create)
1946 return nullptr;
1947 m_script_interpreters[script_language] =
1948 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1949 }
1950
1951 return m_script_interpreters[script_language].get();
1952}
1953
1956 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1957 return *m_source_manager_up;
1958}
1959
1960// This function handles events that were broadcast by the process.
1962 using namespace lldb;
1963 const uint32_t event_type =
1965 event_sp);
1966
1967 // if (event_type & eBreakpointEventTypeAdded
1968 // || event_type & eBreakpointEventTypeRemoved
1969 // || event_type & eBreakpointEventTypeEnabled
1970 // || event_type & eBreakpointEventTypeDisabled
1971 // || event_type & eBreakpointEventTypeCommandChanged
1972 // || event_type & eBreakpointEventTypeConditionChanged
1973 // || event_type & eBreakpointEventTypeIgnoreChanged
1974 // || event_type & eBreakpointEventTypeLocationsResolved)
1975 // {
1976 // // Don't do anything about these events, since the breakpoint
1977 // commands already echo these actions.
1978 // }
1979 //
1980 if (event_type & eBreakpointEventTypeLocationsAdded) {
1981 uint32_t num_new_locations =
1983 event_sp);
1984 if (num_new_locations > 0) {
1985 BreakpointSP breakpoint =
1987 if (StreamUP output_up = GetAsyncOutputStream()) {
1988 output_up->Printf("%d location%s added to breakpoint %d\n",
1989 num_new_locations, num_new_locations == 1 ? "" : "s",
1990 breakpoint->GetID());
1991 output_up->Flush();
1992 }
1993 }
1994 }
1995 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1996 // {
1997 // // These locations just get disabled, not sure it is worth spamming
1998 // folks about this on the command line.
1999 // }
2000 // else if (event_type & eBreakpointEventTypeLocationsResolved)
2001 // {
2002 // // This might be an interesting thing to note, but I'm going to
2003 // leave it quiet for now, it just looked noisy.
2004 // }
2005}
2006
2007void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
2008 bool flush_stderr) {
2009 const auto &flush = [&](Stream &stream,
2010 size_t (Process::*get)(char *, size_t, Status &)) {
2011 Status error;
2012 size_t len;
2013 char buffer[1024];
2014 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
2015 stream.Write(buffer, len);
2016 stream.Flush();
2017 };
2018
2019 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
2020 if (flush_stdout)
2022 if (flush_stderr)
2024}
2025
2026// This function handles events that were broadcast by the process.
2028 const uint32_t event_type = event_sp->GetType();
2029 ProcessSP process_sp =
2033
2034 StreamUP output_stream_up = GetAsyncOutputStream();
2035 StreamUP error_stream_up = GetAsyncErrorStream();
2036 const bool gui_enabled = IsForwardingEvents();
2037
2038 if (!gui_enabled) {
2039 bool pop_process_io_handler = false;
2040 assert(process_sp);
2041
2042 bool state_is_stopped = false;
2043 const bool got_state_changed =
2044 (event_type & Process::eBroadcastBitStateChanged) != 0;
2045 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
2046 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
2047 const bool got_structured_data =
2048 (event_type & Process::eBroadcastBitStructuredData) != 0;
2049
2050 if (got_state_changed) {
2051 StateType event_state =
2053 state_is_stopped = StateIsStoppedState(event_state, false);
2054 }
2055
2056 // Display running state changes first before any STDIO
2057 if (got_state_changed && !state_is_stopped) {
2058 // This is a public stop which we are going to announce to the user, so
2059 // we should force the most relevant frame selection here.
2060 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2062 pop_process_io_handler);
2063 }
2064
2065 // Now display STDOUT and STDERR
2066 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
2067 got_stderr || got_state_changed);
2068
2069 // Give structured data events an opportunity to display.
2070 if (got_structured_data) {
2071 StructuredDataPluginSP plugin_sp =
2073 if (plugin_sp) {
2074 auto structured_data_sp =
2076 StreamString content_stream;
2077 Status error =
2078 plugin_sp->GetDescription(structured_data_sp, content_stream);
2079 if (error.Success()) {
2080 if (!content_stream.GetString().empty()) {
2081 // Add newline.
2082 content_stream.PutChar('\n');
2083 content_stream.Flush();
2084
2085 // Print it.
2086 output_stream_up->PutCString(content_stream.GetString());
2087 }
2088 } else {
2089 error_stream_up->Format("Failed to print structured "
2090 "data with plugin {0}: {1}",
2091 plugin_sp->GetPluginName(), error);
2092 }
2093 }
2094 }
2095
2096 // Now display any stopped state changes after any STDIO
2097 if (got_state_changed && state_is_stopped) {
2098 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2100 pop_process_io_handler);
2101 }
2102
2103 output_stream_up->Flush();
2104 error_stream_up->Flush();
2105
2106 if (pop_process_io_handler)
2107 process_sp->PopProcessIOHandler();
2108 }
2109 return process_sp;
2110}
2111
2113 // At present the only thread event we handle is the Frame Changed event, and
2114 // all we do for that is just reprint the thread status for that thread.
2115 const uint32_t event_type = event_sp->GetType();
2116 const bool stop_format = true;
2117 ThreadSP thread_sp;
2118 if (event_type == Thread::eBroadcastBitStackChanged ||
2120 thread_sp = Thread::ThreadEventData::GetThreadFromEvent(event_sp.get());
2121 if (thread_sp) {
2122 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format,
2123 /*show_hidden*/ true);
2124 }
2125 }
2126 return thread_sp;
2127}
2128
2130
2132 m_forward_listener_sp = listener_sp;
2133}
2134
2136 m_forward_listener_sp.reset();
2137}
2138
2139/// Conservative heuristic to detect whether OSC 9;4 progress is supported by
2140/// the current terminal.
2142#if defined(_WIN32)
2143 // On Windows, we assume that the user is using the Windows Terminal.
2144 return true;
2145#else
2146 static std::once_flag g_once_flag;
2147 static bool g_supports_osc_progress = false;
2148
2149 std::call_once(g_once_flag, []() {
2150 // Check TERM_PROGRAM for known supported terminals. This can lead to false
2151 // negatives, for example when using tmux.
2152 if (const char *term_program = std::getenv("TERM_PROGRAM")) {
2153 llvm::StringRef term_program_str(term_program);
2154 if (term_program_str.starts_with("ghostty") ||
2155 term_program_str.starts_with("wezterm")) {
2156 g_supports_osc_progress = true;
2157 return;
2158 }
2159 }
2160
2161 // Check other known environment variables.
2162 std::array<const char *, 3> known_env_vars = {
2163 "ConEmuPID", // https://conemu.github.io/en/ConEmuEnvironment.html
2164 "GHOSTTY_RESOURCES_DIR", // https://ghostty.org/docs/features/shell-integration
2165 "OSC_PROGRESS", // LLDB specific override.
2166 };
2167 for (const char *env_var : known_env_vars) {
2168 if (std::getenv(env_var)) {
2169 g_supports_osc_progress = true;
2170 return;
2171 }
2172 }
2173 });
2174
2175 return g_supports_osc_progress;
2176#endif
2177}
2178
2181 File &file = stream_sp->GetUnlockedFile();
2182 return file.GetIsInteractive() && file.GetIsRealTerminal() &&
2184 }
2185 return false;
2186}
2187
2189// We have trouble with the contol codes on Windows, see
2190// https://github.com/llvm/llvm-project/issues/134846.
2191#ifndef _WIN32
2193#else
2194 return false;
2195#endif
2196}
2197
2198static bool RequiresFollowChildWorkaround(const Process &process) {
2199 // FIXME: https://github.com/llvm/llvm-project/issues/160216
2200 return process.GetFollowForkMode() == eFollowChild;
2201}
2202
2204 ListenerSP listener_sp(GetListener());
2205 llvm::StringRef broadcaster_class_target(Target::GetStaticBroadcasterClass());
2206 llvm::StringRef broadcaster_class_process(
2208 llvm::StringRef broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
2209 BroadcastEventSpec target_event_spec(broadcaster_class_target,
2211
2212 BroadcastEventSpec process_event_spec(
2213 broadcaster_class_process,
2216
2217 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
2220
2221 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2222 target_event_spec);
2223 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2224 process_event_spec);
2225 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2226 thread_event_spec);
2227 listener_sp->StartListeningForEvents(
2232
2233 listener_sp->StartListeningForEvents(
2238
2239 // Let the thread that spawned us know that we have started up and that we
2240 // are now listening to all required events so no events get missed
2242
2243 if (StatuslineSupported()) {
2244 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2245 if (!m_statusline) {
2246 m_statusline.emplace(*this);
2247 m_statusline->Enable(
2248 GetSelectedExecutionContextRef(/*adopt_dummy_target=*/true));
2249 }
2250 }
2251
2252 bool done = false;
2253 while (!done) {
2254 EventSP event_sp;
2255 if (listener_sp->GetEvent(event_sp, std::nullopt)) {
2256 std::optional<ExecutionContextRef> exe_ctx_ref = std::nullopt;
2257 if (event_sp) {
2258 Broadcaster *broadcaster = event_sp->GetBroadcaster();
2259 if (broadcaster) {
2260 uint32_t event_type = event_sp->GetType();
2261 llvm::StringRef broadcaster_class(broadcaster->GetBroadcasterClass());
2262 if (broadcaster_class == broadcaster_class_process) {
2263 if (ProcessSP process_sp = HandleProcessEvent(event_sp)) {
2264 // Don't pass adopt_selected = true if this is a stop for an
2265 // auto-continue event (e.g. an auto-continue breakpoint). We
2266 // would be fetching stale state, since the process resumed since
2267 // this event, and we'd needlessly interrupt the target to do so.
2268 const bool adopt_selected =
2269 process_sp->GetPrivateState() == eStateStopped &&
2271 event_sp.get());
2272 if (!RequiresFollowChildWorkaround(*process_sp))
2273 exe_ctx_ref =
2274 ExecutionContextRef(process_sp.get(), adopt_selected);
2275 }
2276 } else if (broadcaster_class == broadcaster_class_target) {
2278 event_sp.get())) {
2279 HandleBreakpointEvent(event_sp);
2280 }
2281 } else if (broadcaster_class == broadcaster_class_thread) {
2282 if (ThreadSP thread_sp = HandleThreadEvent(event_sp))
2283 if (!RequiresFollowChildWorkaround(*thread_sp->GetProcess()))
2284 exe_ctx_ref = ExecutionContextRef(thread_sp.get(),
2285 /*adopt_selected=*/true);
2286 } else if (broadcaster == m_command_interpreter_up.get()) {
2287 if (event_type &
2289 done = true;
2290 } else if (event_type &
2292 const char *data = static_cast<const char *>(
2293 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2294 if (data && data[0]) {
2295 StreamUP error_up = GetAsyncErrorStream();
2296 error_up->PutCString(data);
2297 error_up->Flush();
2298 }
2299 } else if (event_type & CommandInterpreter::
2300 eBroadcastBitAsynchronousOutputData) {
2301 const char *data = static_cast<const char *>(
2302 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2303 if (data && data[0]) {
2304 StreamUP output_up = GetAsyncOutputStream();
2305 output_up->PutCString(data);
2306 output_up->Flush();
2307 }
2308 }
2309 } else if (broadcaster == &m_broadcaster) {
2310 if (event_type & lldb::eBroadcastBitProgress ||
2312 HandleProgressEvent(event_sp);
2313 else if (event_type & lldb::eBroadcastBitWarning)
2314 HandleDiagnosticEvent(event_sp);
2315 else if (event_type & lldb::eBroadcastBitError)
2316 HandleDiagnosticEvent(event_sp);
2317 }
2318 }
2319
2321 m_forward_listener_sp->AddEvent(event_sp);
2322 }
2323 RedrawStatusline(exe_ctx_ref);
2324 }
2325 }
2326
2327 {
2328 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2329 if (m_statusline)
2330 m_statusline.reset();
2331 }
2332
2333 return {};
2334}
2335
2337 if (!m_event_handler_thread.IsJoinable()) {
2338 // We must synchronize with the DefaultEventHandler() thread to ensure it
2339 // is up and running and listening to events before we return from this
2340 // function. We do this by listening to events for the
2341 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2342 ConstString full_name("lldb.debugger.event-handler");
2343 ListenerSP listener_sp(
2344 Listener::MakeListener(full_name.AsCString(nullptr)));
2345 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
2347
2348 llvm::StringRef thread_name =
2349 full_name.GetLength() < llvm::get_max_thread_name_length()
2350 ? full_name.GetStringRef()
2351 : "dbg.evt-handler";
2352
2353 // Use larger 8MB stack for this thread
2354 llvm::Expected<HostThread> event_handler_thread =
2356 thread_name, [this] { return DefaultEventHandler(); },
2358
2359 if (event_handler_thread) {
2360 m_event_handler_thread = *event_handler_thread;
2361 } else {
2362 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(),
2363 "failed to launch host thread: {0}");
2364 }
2365
2366 // Make sure DefaultEventHandler() is running and listening to events
2367 // before we return from this function. We are only listening for events of
2368 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2369 // event, we just need to wait an infinite amount of time for it (nullptr
2370 // timeout as the first parameter)
2371 lldb::EventSP event_sp;
2372 listener_sp->GetEvent(event_sp, std::nullopt);
2373 }
2374 return m_event_handler_thread.IsJoinable();
2375}
2376
2384
2390
2392 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
2393 if (!data)
2394 return;
2395
2396 // Make a local copy of the incoming progress report that we'll store.
2397 ProgressReport progress_report{data->GetID(), data->GetCompleted(),
2398 data->GetTotal(), data->GetMessage()};
2399
2400 {
2401 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2402
2403 // Do some bookkeeping regardless of whether we're going to display
2404 // progress reports.
2405 auto it = llvm::find_if(m_progress_reports, [&](const auto &report) {
2406 return report.id == progress_report.id;
2407 });
2408 if (it != m_progress_reports.end()) {
2409 const bool complete = data->GetCompleted() == data->GetTotal();
2410 if (complete)
2411 m_progress_reports.erase(it);
2412 else
2413 *it = progress_report;
2414 } else {
2415 m_progress_reports.push_back(progress_report);
2416 }
2417
2418 // Show progress using Operating System Command (OSC) sequences.
2422
2423 // Clear progress if this was the last progress event.
2424 if (m_progress_reports.empty()) {
2425 stream_sp->Lock() << OSC_PROGRESS_REMOVE;
2426 return;
2427 }
2428
2429 const ProgressReport &report = m_progress_reports.back();
2430
2431 // Show indeterminate progress.
2432 if (report.total == UINT64_MAX) {
2433 stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE;
2434 return;
2435 }
2436
2437 // Compute and show the progress value (0-100).
2438 const unsigned value = (report.completed / report.total) * 100;
2439 stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value);
2440 }
2441 }
2442 }
2443}
2444
2445std::optional<Debugger::ProgressReport>
2447 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2448 if (m_progress_reports.empty())
2449 return std::nullopt;
2450 return m_progress_reports.back();
2451}
2452
2454 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
2455 if (!data)
2456 return;
2457
2458 data->Dump(GetAsyncErrorStream().get());
2459}
2460
2462 return m_io_handler_thread.IsJoinable();
2463}
2464
2467 m_io_handler_thread = new_thread;
2468 return old_host;
2469}
2470
2472 if (!m_io_handler_thread.IsJoinable()) {
2473 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
2474 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2475 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2476 if (io_handler_thread) {
2477 m_io_handler_thread = *io_handler_thread;
2478 } else {
2479 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(),
2480 "failed to launch host thread: {0}");
2481 }
2482 }
2483 return m_io_handler_thread.IsJoinable();
2484}
2485
2487 if (m_io_handler_thread.IsJoinable()) {
2488 GetInputFile().Close();
2489 m_io_handler_thread.Join(nullptr);
2490 }
2491}
2492
2500
2502 if (!HasIOHandlerThread())
2503 return false;
2504 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread());
2505}
2506
2508 if (!prefer_dummy) {
2509 if (TargetSP target = m_target_list.GetSelectedTarget())
2510 return *target;
2511 }
2512 return GetDummyTarget();
2513}
2514
2515Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
2516 Status err;
2517 FileSpec repl_executable;
2518
2519 if (language == eLanguageTypeUnknown)
2520 language = GetREPLLanguage();
2521
2522 if (language == eLanguageTypeUnknown) {
2524
2525 if (auto single_lang = repl_languages.GetSingularLanguage()) {
2526 language = *single_lang;
2527 } else if (repl_languages.Empty()) {
2529 "LLDB isn't configured with REPL support for any languages.");
2530 return err;
2531 } else {
2533 "Multiple possible REPL languages. Please specify a language.");
2534 return err;
2535 }
2536 }
2537
2538 Target *const target =
2539 nullptr; // passing in an empty target means the REPL must create one
2540
2541 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2542
2543 if (!err.Success()) {
2544 return err;
2545 }
2546
2547 if (!repl_sp) {
2549 "couldn't find a REPL for %s",
2551 return err;
2552 }
2553
2554 repl_sp->SetCompilerOptions(repl_options);
2555 repl_sp->RunLoop();
2556
2557 return err;
2558}
2559
2560llvm::ThreadPoolInterface &Debugger::GetThreadPool() {
2561 assert(g_thread_pool &&
2562 "Debugger::GetThreadPool called before Debugger::Initialize");
2563 return *g_thread_pool;
2564}
2565
2567 llvm::StringRef name, bool value,
2568 llvm::StringRef description) {
2569 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2570 entry_up->AddBooleanItem("value", value);
2571 entry_up->AddStringItem("description", description);
2572 dict.AddItem(name, std::move(entry_up));
2573}
2574
2576 auto array_up = std::make_unique<StructuredData::Array>();
2577#define LLVM_TARGET(target) \
2578 array_up->AddItem(std::make_unique<StructuredData::String>(#target));
2579#include "llvm/Config/Targets.def"
2580 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2581 entry_up->AddItem("value", std::move(array_up));
2582 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
2583 dict.AddItem("targets", std::move(entry_up));
2584}
2585
2587 auto config_up = std::make_unique<StructuredData::Dictionary>();
2589 *config_up, "xml", XMLDocument::XMLEnabled(),
2590 "A boolean value that indicates if XML support is enabled in LLDB");
2592 *config_up, "curl", LLVM_ENABLE_CURL,
2593 "A boolean value that indicates if CURL support is enabled in LLDB");
2595 *config_up, "curses", LLDB_ENABLE_CURSES,
2596 "A boolean value that indicates if curses support is enabled in LLDB");
2598 *config_up, "editline", LLDB_ENABLE_LIBEDIT,
2599 "A boolean value that indicates if editline support is enabled in LLDB");
2600 AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,
2601 "A boolean value that indicates if editline wide "
2602 "characters support is enabled in LLDB");
2604 *config_up, "zlib", LLVM_ENABLE_ZLIB,
2605 "A boolean value that indicates if zlib support is enabled in LLDB");
2607 *config_up, "lzma", LLDB_ENABLE_LZMA,
2608 "A boolean value that indicates if lzma support is enabled in LLDB");
2610 *config_up, "python", LLDB_ENABLE_PYTHON,
2611 "A boolean value that indicates if python support is enabled in LLDB");
2613 *config_up, "lua", LLDB_ENABLE_LUA,
2614 "A boolean value that indicates if lua support is enabled in LLDB");
2615 AddLLVMTargets(*config_up);
2616 return config_up;
2617}
#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:849
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:370
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:609
bool SetUseExternalEditor(bool use_external_editor_p)
Definition Debugger.cpp:506
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:711
llvm::StringRef GetDisabledAnsiSuffix() const
Definition Debugger.cpp:590
uint64_t GetTerminalHeight() const
Definition Debugger.cpp:469
lldb::LockableStreamFileSP m_output_stream_sp
Definition Debugger.h:758
bool SetExternalEditor(llvm::StringRef editor)
Definition Debugger.cpp:517
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:798
lldb::ThreadSP HandleThreadEvent(const lldb::EventSP &event_sp)
void HandleProgressEvent(const lldb::EventSP &event_sp)
SourceManager & GetSourceManager()
bool SetTerminalDimensions(uint64_t term_width, uint64_t term_height)
Set the terminal width and height together, so observers are notified once with both dimensions curre...
Definition Debugger.cpp:479
bool SetShowProgress(bool show_progress)
Definition Debugger.cpp:543
bool StartEventHandlerThread()
Manually start the global event handler thread.
bool SetUseSourceCache(bool use_source_cache)
Definition Debugger.cpp:645
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:740
lldb::FileSP GetInputFileSP()
Definition Debugger.h:155
bool GetHighlightSource() const
Definition Debugger.cpp:660
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:566
LoadedPluginsList m_loaded_plugins
Definition Debugger.h:800
bool GetShowInlineDiagnostics() const
Definition Debugger.cpp:769
bool SetTabSize(uint64_t tab_size)
Definition Debugger.cpp:757
void HandleDiagnosticEvent(const lldb::EventSP &event_sp)
static lldb::DebuggerSP GetDebuggerAtIndex(size_t index)
llvm::StringRef GetAutosuggestionAnsiSuffix() const
Definition Debugger.cpp:615
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:584
bool GetUseExternalEditor() const
Definition Debugger.cpp:500
TerminalState m_terminal_state
Definition Debugger.h:768
lldb::StreamUP GetAsyncErrorStream()
bool GetEscapeNonPrintables() const
Definition Debugger.cpp:723
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:827
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:554
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:937
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:789
static lldb::DebuggerSP FindDebuggerWithInstanceName(llvm::StringRef instance_name)
Definition Debugger.cpp:995
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:717
const char * GetIOHandlerCommandPrefix()
std::optional< Statusline > m_statusline
Definition Debugger.h:793
bool GetUseColor() const
Definition Debugger.cpp:522
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:560
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:578
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:475
Broadcaster m_sync_broadcaster
Private debugger synchronization.
Definition Debugger.h:803
bool GetUseSourceCache() const
Definition Debugger.cpp:639
HostThread m_io_handler_thread
Definition Debugger.h:802
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:627
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:729
llvm::StringRef GetStopShowColumnAnsiSuffix() const
Definition Debugger.cpp:679
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:919
lldb::StopShowColumn GetStopShowColumn() const
Definition Debugger.cpp:666
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:746
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:775
bool LoadPlugin(const FileSpec &spec, Status &error)
Definition Debugger.cpp:831
void SetOutputFile(lldb::FileSP file)
uint64_t GetStopSourceLineCount(bool before) const
Definition Debugger.cpp:697
bool SetStatuslineFormat(const FormatEntity::Entry &format)
Definition Debugger.cpp:571
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:963
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:685
bool GetShowDontUsePoHint() const
Definition Debugger.cpp:633
uint64_t GetTabSize() const
Definition Debugger.cpp:751
bool GetShowProgress() const
Definition Debugger.cpp:537
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:621
std::mutex m_output_flush_mutex
Definition Debugger.h:752
llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const
Definition Debugger.cpp:691
bool SetSeparator(llvm::StringRef s)
Definition Debugger.cpp:596
bool SetUseColor(bool use_color)
Definition Debugger.cpp:528
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:603
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:829
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:511
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:762
bool GetMarkHiddenFrames() const
Definition Debugger.cpp:654
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:548
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:704
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:735
friend class CommandInterpreter
Definition Debugger.h:658
llvm::StringRef GetStopShowColumnAnsiPrefix() const
Definition Debugger.cpp:673
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:411
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:364
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:396
void EnumerateDirectory(llvm::Twine path, bool find_directories, bool find_files, bool find_other, EnumerateDirectoryCallbackType callback, void *callback_baton)
@ eEnumerateDirectoryResultEnter
Recurse into the current entry if it is a directory or symlink, or next if not.
Definition FileSystem.h:185
@ eEnumerateDirectoryResultNext
Enumerate next entry in the current directory.
Definition FileSystem.h:182
@ eEnumerateDirectoryResultQuit
Stop directory enumerations at any level.
Definition FileSystem.h:187
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
An abstract base class for files.
Definition FileBase.h:34
bool GetIsRealTerminal()
Return true if this file from a real terminal.
Definition File.cpp:168
static int kInvalidDescriptor
Definition FileBase.h:36
virtual int GetDescriptor() const
Get underlying OS file descriptor for this file, or kInvalidDescriptor.
Definition File.cpp:119
bool GetIsTerminalWithColors()
Return true if this file is a terminal which supports colors.
Definition File.cpp:174
Status Close() override
Flush any buffers and release any resources owned by the file.
Definition File.cpp:108
bool GetIsInteractive()
Return true if this file is interactive.
Definition File.cpp:162
bool Format(const Entry &entry, Stream &s, ValueObject *valobj=nullptr)
const Mangled & GetMangled() const
Definition Function.h:510
static void SystemLog(lldb::Severity severity, llvm::StringRef message)
Emit the given message to the operating system log.
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
static llvm::StringRef GetSettingName()
Definition Language.cpp:45
static LanguageSet GetLanguagesSupportingREPLs()
Definition Language.cpp:475
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:305
static LanguageProperties & GetGlobalLanguageProperties()
Definition Language.cpp:40
static lldb::ListenerSP MakeListener(const char *name)
Definition Listener.cpp: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:139
static PlatformProperties & GetGlobalPlatformProperties()
Definition Platform.cpp:145
static lldb::ScriptInterpreterSP GetScriptInterpreterForLanguage(lldb::ScriptLanguage script_lang, Debugger &debugger)
static void DebuggerInitialize(Debugger &debugger)
FollowForkMode GetFollowForkMode() const
Definition Process.cpp:396
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4753
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4737
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4745
A plug-in interface definition class for debugging a process.
Definition Process.h:357
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:757
static llvm::StringRef GetStaticBroadcasterClass()
Definition Process.cpp:447
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4940
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4921
static const ProgressEventData * GetEventDataFromEvent(const Event *event_ptr)
lldb::OptionValuePropertiesSP m_collection_sp
virtual Status SetPropertyValue(const ExecutionContext *exe_ctx, VarSetOperationType op, llvm::StringRef property_path, llvm::StringRef value)
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
lldb::OptionValuePropertiesSP GetValueProperties() const
static lldb::REPLSP Create(Status &Status, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options)
Get a REPL with an existing target (or, failing that, a debugger to use), and (optional) extra argume...
Definition REPL.cpp:38
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Success() const
Test for success condition.
Definition Status.cpp:303
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition Stream.h:111
size_t PutChar(char ch)
Definition Stream.cpp:131
virtual void Flush()=0
Flush the stream.
void AddItem(llvm::StringRef key, ObjectSP value_sp)
std::shared_ptr< Dictionary > DictionarySP
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Symbol * symbol
The Symbol for a given query.
bool Compare(ConstString name, lldb::SymbolType type) const
Definition Symbol.cpp:386
ConstString GetName() const
Definition Symbol.cpp:511
lldb::SymbolType GetType() const
Definition Symbol.h:169
Debugger & GetDebugger() const
Definition Target.h:1324
static void SettingsTerminate()
Definition Target.cpp:2855
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:175
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3413
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2865
@ eBroadcastBitBreakpointChanged
Definition Target.h:587
static void SettingsInitialize()
Definition Target.cpp:2853
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
static lldb::ThreadSP GetThreadFromEvent(const Event *event_ptr)
Definition Thread.cpp:189
@ eBroadcastBitThreadSelected
Definition Thread.h:81
static llvm::StringRef GetStaticBroadcasterClass()
Definition Thread.cpp:221
static bool XMLEnabled()
Definition XML.cpp:83
virtual void DispatchClientTelemetry(const lldb_private::StructuredDataImpl &entry, Debugger *debugger)
static TelemetryManager * GetInstance()
#define UINT64_MAX
@ SelectMostRelevantFrame
#define LLDB_INVALID_HOST_THREAD
Definition lldb-types.h:69
Status Parse(const llvm::StringRef &format, Entry &entry)
std::string FormatAnsiTerminalCodes(llvm::StringRef format, bool do_color=true)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
LoadScriptFromSymFile
Definition Target.h:59
@ eLoadScriptFromSymFileTrue
Definition Target.h:60
@ eLoadScriptFromSymFileFalse
Definition Target.h:61
@ eLoadScriptFromSymFileWarn
Definition Target.h:62
const char * GetVersion()
Retrieves a string representing the complete LLDB version, which includes the lldb version number,...
Definition Version.cpp:38
void(* DebuggerDestroyCallback)(lldb::user_id_t debugger_id, void *baton)
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
NativeFilePosix NativeFile
Definition File.h:29
llvm::sys::DynamicLibrary(* LoadPluginCallbackType)(const lldb::DebuggerSP &debugger_sp, const FileSpec &spec, Status &error)
VarSetOperationType
Settable state variable types.
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