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