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
108#pragma mark Static Functions
109
110static std::recursive_mutex *g_debugger_list_mutex_ptr =
111 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
113 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
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);
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}
616 const uint32_t idx = ePropertyHighlightSource;
618 idx, g_debugger_properties[idx].default_uint_value != 0);
619}
620
622 const uint32_t idx = ePropertyStopShowColumn;
624 idx, static_cast<lldb::StopShowColumn>(
625 g_debugger_properties[idx].default_uint_value));
626}
627
629 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
631 idx, g_debugger_properties[idx].default_cstr_value);
632}
633
635 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
637 idx, g_debugger_properties[idx].default_cstr_value);
638}
639
641 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
643 idx, g_debugger_properties[idx].default_cstr_value);
644}
645
647 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
649 idx, g_debugger_properties[idx].default_cstr_value);
650}
651
652uint64_t Debugger::GetStopSourceLineCount(bool before) const {
653 const uint32_t idx =
654 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
656 idx, g_debugger_properties[idx].default_uint_value);
657}
658
660 const uint32_t idx = ePropertyStopDisassemblyDisplay;
662 idx, static_cast<lldb::StopDisassemblyType>(
663 g_debugger_properties[idx].default_uint_value));
664}
665
667 const uint32_t idx = ePropertyStopDisassemblyCount;
669 idx, g_debugger_properties[idx].default_uint_value);
670}
671
673 const uint32_t idx = ePropertyAutoOneLineSummaries;
675 idx, g_debugger_properties[idx].default_uint_value != 0);
676}
677
679 const uint32_t idx = ePropertyEscapeNonPrintables;
681 idx, g_debugger_properties[idx].default_uint_value != 0);
682}
683
685 const uint32_t idx = ePropertyAutoIndent;
687 idx, g_debugger_properties[idx].default_uint_value != 0);
688}
689
691 const uint32_t idx = ePropertyAutoIndent;
692 return SetPropertyAtIndex(idx, b);
693}
694
696 const uint32_t idx = ePropertyPrintDecls;
698 idx, g_debugger_properties[idx].default_uint_value != 0);
699}
700
702 const uint32_t idx = ePropertyPrintDecls;
703 return SetPropertyAtIndex(idx, b);
704}
705
706uint64_t Debugger::GetTabSize() const {
707 const uint32_t idx = ePropertyTabSize;
709 idx, g_debugger_properties[idx].default_uint_value);
710}
711
712bool Debugger::SetTabSize(uint64_t tab_size) {
713 const uint32_t idx = ePropertyTabSize;
714 return SetPropertyAtIndex(idx, tab_size);
715}
716
718 const uint32_t idx = ePropertyDWIMPrintVerbosity;
720 idx, static_cast<lldb::DWIMPrintVerbosity>(
721 g_debugger_properties[idx].default_uint_value != 0));
722}
723
725 const uint32_t idx = ePropertyShowInlineDiagnostics;
727 idx, g_debugger_properties[idx].default_uint_value);
728}
729
731 const uint32_t idx = ePropertyShowInlineDiagnostics;
732 return SetPropertyAtIndex(idx, b);
733}
734
735#pragma mark Debugger
736
737// const DebuggerPropertiesSP &
738// Debugger::GetSettings() const
739//{
740// return m_properties_sp;
741//}
742//
743
745 assert(g_debugger_list_ptr == nullptr &&
746 "Debugger::Initialize called more than once!");
747 g_debugger_list_mutex_ptr = new std::recursive_mutex();
749 g_thread_pool = new llvm::DefaultThreadPool(llvm::optimal_concurrency());
750 g_load_plugin_callback = load_plugin_callback;
751}
752
754 assert(g_debugger_list_ptr &&
755 "Debugger::Terminate called without a matching Debugger::Initialize!");
756
758 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
759 for (const auto &debugger : *g_debugger_list_ptr)
760 debugger->HandleDestroyCallback();
761 }
762
763 if (g_thread_pool) {
764 // The destructor will wait for all the threads to complete.
765 delete g_thread_pool;
766 }
767
769 // Clear our global list of debugger objects
770 {
771 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
772 for (const auto &debugger : *g_debugger_list_ptr)
773 debugger->Clear();
774 g_debugger_list_ptr->clear();
775 }
776 }
777}
778
780
782
785 llvm::sys::DynamicLibrary dynlib =
786 g_load_plugin_callback(shared_from_this(), spec, error);
787 if (dynlib.isValid()) {
788 m_loaded_plugins.push_back(dynlib);
789 return true;
790 }
791 } else {
792 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
793 // if the public API layer isn't available (code is linking against all of
794 // the internal LLDB static libraries), then we can't load plugins
795 error = Status::FromErrorString("Public API layer is not available");
796 }
797 return false;
798}
799
801LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
802 llvm::StringRef path) {
804
805 static constexpr llvm::StringLiteral g_dylibext(".dylib");
806 static constexpr llvm::StringLiteral g_solibext(".so");
807
808 if (!baton)
810
811 Debugger *debugger = (Debugger *)baton;
812
813 namespace fs = llvm::sys::fs;
814 // If we have a regular file, a symbolic link or unknown file type, try and
815 // process the file. We must handle unknown as sometimes the directory
816 // enumeration might be enumerating a file system that doesn't have correct
817 // file type information.
818 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
819 ft == fs::file_type::type_unknown) {
820 FileSpec plugin_file_spec(path);
821 FileSystem::Instance().Resolve(plugin_file_spec);
822
823 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
824 plugin_file_spec.GetFileNameExtension() != g_solibext) {
826 }
827
828 Status plugin_load_error;
829 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
830
832 } else if (ft == fs::file_type::directory_file ||
833 ft == fs::file_type::symlink_file ||
834 ft == fs::file_type::type_unknown) {
835 // Try and recurse into anything that a directory or symbolic link. We must
836 // also do this for unknown as sometimes the directory enumeration might be
837 // enumerating a file system that doesn't have correct file type
838 // information.
840 }
841
843}
844
846 const bool find_directories = true;
847 const bool find_files = true;
848 const bool find_other = true;
849 char dir_path[PATH_MAX];
850 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
851 if (FileSystem::Instance().Exists(dir_spec) &&
852 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
853 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
854 find_files, find_other,
855 LoadPluginCallback, this);
856 }
857 }
858
859 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
860 if (FileSystem::Instance().Exists(dir_spec) &&
861 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
862 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
863 find_files, find_other,
864 LoadPluginCallback, this);
865 }
866 }
867
869}
870
872 void *baton) {
875 helper([](lldb_private::telemetry::DebuggerInfo *entry) {
877 });
878 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
879 helper.SetDebugger(debugger_sp.get());
880
882 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
883 g_debugger_list_ptr->push_back(debugger_sp);
884 }
885 debugger_sp->InstanceInitialize();
886 return debugger_sp;
887}
888
894
896 const lldb::user_id_t user_id = GetID();
897 // Invoke and remove all the callbacks in an FIFO order. Callbacks which are
898 // added during this loop will be appended, invoked and then removed last.
899 // Callbacks which are removed during this loop will not be invoked.
900 while (true) {
901 DestroyCallbackInfo callback_info;
902 {
903 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
904 if (m_destroy_callbacks.empty())
905 break;
906 // Pop the first item in the list
907 callback_info = m_destroy_callbacks.front();
909 }
910 // Call the destroy callback with user id and baton
911 callback_info.callback(user_id, callback_info.baton);
912 }
913}
914
915void Debugger::Destroy(DebuggerSP &debugger_sp) {
916 if (!debugger_sp)
917 return;
918
919 debugger_sp->HandleDestroyCallback();
920 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
921
922 if (cmd_interpreter.GetSaveSessionOnQuit()) {
923 CommandReturnObject result(debugger_sp->GetUseColor());
924 cmd_interpreter.SaveTranscript(result);
925 if (result.Succeeded())
926 (*debugger_sp->GetAsyncOutputStream())
927 << result.GetOutputString() << '\n';
928 else
929 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorString() << '\n';
930 }
931
932 debugger_sp->Clear();
933
935 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
936 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
937 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
938 if ((*pos).get() == debugger_sp.get()) {
939 g_debugger_list_ptr->erase(pos);
940 return;
941 }
942 }
943 }
944}
945
947Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) {
949 return DebuggerSP();
950
951 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
952 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
953 if (!debugger_sp)
954 continue;
955
956 if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name)
957 return debugger_sp;
958 }
959 return DebuggerSP();
960}
961
963 TargetSP target_sp;
965 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
966 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
967 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
968 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
969 if (target_sp)
970 break;
971 }
972 }
973 return target_sp;
974}
975
977 TargetSP target_sp;
979 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
980 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
981 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
982 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
983 if (target_sp)
984 break;
985 }
986 }
987 return target_sp;
988}
989
991 static constexpr llvm::StringLiteral class_name("lldb.debugger");
992 return class_name;
993}
994
996 : UserID(g_unique_id++),
997 Properties(std::make_shared<OptionValueProperties>()),
998 m_input_file_sp(std::make_shared<NativeFile>(
999 stdin, File::eOpenOptionReadOnly, NativeFile::Unowned)),
1000 m_output_stream_sp(std::make_shared<LockableStreamFile>(
1001 stdout, NativeFile::Unowned, m_output_mutex)),
1002 m_error_stream_sp(std::make_shared<LockableStreamFile>(
1003 stderr, NativeFile::Unowned, m_output_mutex)),
1004 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
1006 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
1009 std::make_unique<CommandInterpreter>(*this, false)),
1011 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()),
1013 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
1017 // Initialize the debugger properties as early as possible as other parts of
1018 // LLDB will start querying them during construction.
1019 m_collection_sp->Initialize(g_debugger_properties);
1020 m_collection_sp->AppendProperty(
1021 "target", "Settings specify to debugging targets.", true,
1023 m_collection_sp->AppendProperty(
1024 "platform", "Platform settings.", true,
1026 m_collection_sp->AppendProperty(
1027 "symbols", "Symbol lookup and cache settings.", true,
1029 m_collection_sp->AppendProperty(
1030 LanguageProperties::GetSettingName(), "Language settings.", true,
1033 m_collection_sp->AppendProperty(
1034 "interpreter",
1035 "Settings specify to the debugger's command interpreter.", true,
1036 m_command_interpreter_up->GetValueProperties());
1037 }
1038 if (log_callback)
1040 std::make_shared<CallbackLogHandler>(log_callback, baton);
1041 m_command_interpreter_up->Initialize();
1042 // Always add our default platform to the platform list
1043 PlatformSP default_platform_sp(Platform::GetHostPlatform());
1044 assert(default_platform_sp);
1045 m_platform_list.Append(default_platform_sp, true);
1046
1047 // Create the dummy target.
1048 {
1050 if (!arch.IsValid())
1051 arch = HostInfo::GetArchitecture();
1052 assert(arch.IsValid() && "No valid default or host archspec");
1053 const bool is_dummy_target = true;
1054 m_dummy_target_sp.reset(
1055 new Target(*this, arch, default_platform_sp, is_dummy_target));
1056 }
1057 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
1058
1059 OptionValueUInt64 *term_width =
1060 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1061 ePropertyTerminalWidth);
1062 term_width->SetMinimumValue(10);
1063
1064 OptionValueUInt64 *term_height =
1065 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1066 ePropertyTerminalHeight);
1067 term_height->SetMinimumValue(10);
1068
1069 // Turn off use-color if this is a dumb terminal.
1070 const char *term = getenv("TERM");
1071 auto disable_color = [&]() {
1072 SetUseColor(false);
1073 SetSeparator("| ");
1074 };
1075
1076 if (term && !strcmp(term, "dumb"))
1077 disable_color();
1078 // Turn off use-color if we don't write to a terminal with color support.
1079 if (!GetOutputFileSP()->GetIsTerminalWithColors())
1080 disable_color();
1081
1082 if (Diagnostics::Enabled()) {
1084 [this](const FileSpec &dir) -> llvm::Error {
1085 for (auto &entry : m_stream_handlers) {
1086 llvm::StringRef log_path = entry.first();
1087 llvm::StringRef file_name = llvm::sys::path::filename(log_path);
1088 FileSpec destination = dir.CopyByAppendingPathComponent(file_name);
1089 std::error_code ec =
1090 llvm::sys::fs::copy_file(log_path, destination.GetPath());
1091 if (ec)
1092 return llvm::errorCodeToError(ec);
1093 }
1094 return llvm::Error::success();
1095 });
1096 }
1097
1098#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
1099 // Enabling use of ANSI color codes because LLDB is using them to highlight
1100 // text.
1101 llvm::sys::Process::UseANSIEscapeCodes(true);
1102#endif
1103}
1104
1106
1108 // Make sure we call this function only once. With the C++ global destructor
1109 // chain having a list of debuggers and with code that can be running on
1110 // other threads, we need to ensure this doesn't happen multiple times.
1111 //
1112 // The following functions call Debugger::Clear():
1113 // Debugger::~Debugger();
1114 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
1115 // static void Debugger::Terminate();
1116 llvm::call_once(m_clear_once, [this]() {
1119 assert(this == info->debugger);
1120 (void)this;
1121 info->is_exit_entry = true;
1122 },
1123 this);
1127 m_listener_sp->Clear();
1128 for (TargetSP target_sp : m_target_list.Targets()) {
1129 if (target_sp) {
1130 if (ProcessSP process_sp = target_sp->GetProcessSP())
1131 process_sp->Finalize(false /* not destructing */);
1132 target_sp->Destroy();
1133 }
1134 }
1135 m_broadcaster_manager_sp->Clear();
1136
1137 // Close the input file _before_ we close the input read communications
1138 // class as it does NOT own the input file, our m_input_file does.
1139 m_terminal_state.Clear();
1140 GetInputFile().Close();
1141
1142 m_command_interpreter_up->Clear();
1143
1146 });
1147}
1148
1150 return !m_command_interpreter_up->GetSynchronous();
1151}
1152
1153void Debugger::SetAsyncExecution(bool async_execution) {
1154 m_command_interpreter_up->SetSynchronous(!async_execution);
1155}
1156
1157static inline int OpenPipe(int fds[2], std::size_t size) {
1158#ifdef _WIN32
1159 return _pipe(fds, size, O_BINARY);
1160#else
1161 (void)size;
1162 return pipe(fds);
1163#endif
1164}
1165
1167 Status result;
1168 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
1169 int fds[2] = {-1, -1};
1170
1171 if (data == nullptr) {
1172 result = Status::FromErrorString("String data is null");
1173 return result;
1174 }
1175
1176 size_t size = strlen(data);
1177 if (size == 0) {
1178 result = Status::FromErrorString("String data is empty");
1179 return result;
1180 }
1181
1182 if (OpenPipe(fds, size) != 0) {
1183 result = Status::FromErrorString(
1184 "can't create pipe file descriptors for LLDB commands");
1185 return result;
1186 }
1187
1188 int r = write(fds[WRITE], data, size);
1189 (void)r;
1190 // Close the write end of the pipe, so that the command interpreter will exit
1191 // when it consumes all the data.
1192 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
1193
1194 // Open the read file descriptor as a FILE * that we can return as an input
1195 // handle.
1196 FILE *commands_file = fdopen(fds[READ], "rb");
1197 if (commands_file == nullptr) {
1199 "fdopen(%i, \"rb\") failed (errno = %i) "
1200 "when trying to open LLDB commands pipe",
1201 fds[READ], errno);
1202 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
1203 return result;
1204 }
1205
1206 SetInputFile((FileSP)std::make_shared<NativeFile>(
1207 commands_file, File::eOpenOptionReadOnly, true));
1208 return result;
1209}
1210
1212 assert(file_sp && file_sp->IsValid());
1213 m_input_file_sp = std::move(file_sp);
1214 // Save away the terminal state if that is relevant, so that we can restore
1215 // it in RestoreInputState.
1217}
1218
1220 assert(file_sp && file_sp->IsValid());
1222 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1223}
1224
1226 assert(file_sp && file_sp->IsValid());
1228 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1229}
1230
1232 {
1233 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1234 if (m_statusline)
1235 m_statusline->Disable();
1236 }
1237 int fd = GetInputFile().GetDescriptor();
1238 if (fd != File::kInvalidDescriptor)
1239 m_terminal_state.Save(fd, true);
1240}
1241
1243 m_terminal_state.Restore();
1244 {
1245 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1246 if (m_statusline)
1248 }
1249}
1250
1252 std::optional<ExecutionContextRef> exe_ctx_ref) {
1253 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1254
1255 if (!m_statusline)
1256 return;
1257
1258 m_statusline->Redraw(exe_ctx_ref);
1259}
1260
1262 bool adopt_selected = true;
1263 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected);
1264 return ExecutionContext(exe_ctx_ref);
1265}
1266
1268 if (TargetSP selected_target_sp = GetSelectedTarget())
1269 return ExecutionContextRef(selected_target_sp.get(),
1270 /*adopt_selected=*/true);
1271 return ExecutionContextRef(m_dummy_target_sp.get(), /*adopt_selected=*/false);
1272}
1273
1275 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1276 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1277 if (reader_sp)
1278 reader_sp->Interrupt();
1279}
1280
1282 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1283 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1284 if (reader_sp)
1285 reader_sp->GotEOF();
1286}
1287
1289 // The bottom input reader should be the main debugger input reader. We do
1290 // not want to close that one here.
1291 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1292 while (m_io_handler_stack.GetSize() > 1) {
1293 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1294 if (reader_sp)
1295 PopIOHandler(reader_sp);
1296 }
1297}
1298
1300 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1301 while (true) {
1302 if (!reader_sp)
1303 break;
1304
1305 reader_sp->Run();
1306 {
1307 std::lock_guard<std::recursive_mutex> guard(
1309
1310 // Remove all input readers that are done from the top of the stack
1311 while (true) {
1312 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1313 if (top_reader_sp && top_reader_sp->GetIsDone())
1314 PopIOHandler(top_reader_sp);
1315 else
1316 break;
1317 }
1318 reader_sp = m_io_handler_stack.Top();
1319 }
1320 }
1322}
1323
1325 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1326
1327 PushIOHandler(reader_sp);
1328 IOHandlerSP top_reader_sp = reader_sp;
1329
1330 while (top_reader_sp) {
1331 top_reader_sp->Run();
1332
1333 // Don't unwind past the starting point.
1334 if (top_reader_sp.get() == reader_sp.get()) {
1335 if (PopIOHandler(reader_sp))
1336 break;
1337 }
1338
1339 // If we pushed new IO handlers, pop them if they're done or restart the
1340 // loop to run them if they're not.
1341 while (true) {
1342 top_reader_sp = m_io_handler_stack.Top();
1343 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1344 PopIOHandler(top_reader_sp);
1345 // Don't unwind past the starting point.
1346 if (top_reader_sp.get() == reader_sp.get())
1347 return;
1348 } else {
1349 break;
1350 }
1351 }
1352 }
1353}
1354
1356 return m_io_handler_stack.IsTop(reader_sp);
1357}
1358
1360 IOHandler::Type second_top_type) {
1361 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1362}
1363
1364void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1365 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1366 if (!printed) {
1367 LockableStreamFileSP stream_sp =
1369 LockedStreamFile locked_stream = stream_sp->Lock();
1370 locked_stream.Write(s, len);
1371 }
1372}
1373
1375 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1376}
1377
1379 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1380}
1381
1383 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1384}
1385
1387 return PopIOHandler(reader_sp);
1388}
1389
1391 bool cancel_top_handler) {
1392 PushIOHandler(reader_sp, cancel_top_handler);
1393}
1394
1397 LockableStreamFileSP &err) {
1398 // Before an IOHandler runs, it must have in/out/err streams. This function
1399 // is called when one ore more of the streams are nullptr. We use the top
1400 // input reader's in/out/err streams, or fall back to the debugger file
1401 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1402
1403 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1404 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1405 // If no STDIN has been set, then set it appropriately
1406 if (!in || !in->IsValid()) {
1407 if (top_reader_sp)
1408 in = top_reader_sp->GetInputFileSP();
1409 else
1410 in = GetInputFileSP();
1411 // If there is nothing, use stdin
1412 if (!in)
1413 in = std::make_shared<NativeFile>(stdin, File::eOpenOptionReadOnly,
1415 }
1416 // If no STDOUT has been set, then set it appropriately
1417 if (!out || !out->GetUnlockedFile().IsValid()) {
1418 if (top_reader_sp)
1419 out = top_reader_sp->GetOutputStreamFileSP();
1420 else
1421 out = GetOutputStreamSP();
1422 // If there is nothing, use stdout
1423 if (!out)
1424 out = std::make_shared<LockableStreamFile>(stdout, NativeFile::Unowned,
1426 }
1427 // If no STDERR has been set, then set it appropriately
1428 if (!err || !err->GetUnlockedFile().IsValid()) {
1429 if (top_reader_sp)
1430 err = top_reader_sp->GetErrorStreamFileSP();
1431 else
1432 err = GetErrorStreamSP();
1433 // If there is nothing, use stderr
1434 if (!err)
1435 err = std::make_shared<LockableStreamFile>(stderr, NativeFile::Unowned,
1437 }
1438}
1439
1441 bool cancel_top_handler) {
1442 if (!reader_sp)
1443 return;
1444
1445 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1446
1447 // Get the current top input reader...
1448 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1449
1450 // Don't push the same IO handler twice...
1451 if (reader_sp == top_reader_sp)
1452 return;
1453
1454 // Push our new input reader
1455 m_io_handler_stack.Push(reader_sp);
1456 reader_sp->Activate();
1457
1458 // Interrupt the top input reader to it will exit its Run() function and let
1459 // this new input reader take over
1460 if (top_reader_sp) {
1461 top_reader_sp->Deactivate();
1462 if (cancel_top_handler)
1463 top_reader_sp->Cancel();
1464 }
1465}
1466
1467bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1468 if (!pop_reader_sp)
1469 return false;
1470
1471 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1472
1473 // The reader on the stop of the stack is done, so let the next read on the
1474 // stack refresh its prompt and if there is one...
1475 if (m_io_handler_stack.IsEmpty())
1476 return false;
1477
1478 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1479
1480 if (pop_reader_sp != reader_sp)
1481 return false;
1482
1483 reader_sp->Deactivate();
1484 reader_sp->Cancel();
1485 m_io_handler_stack.Pop();
1486
1487 reader_sp = m_io_handler_stack.Top();
1488 if (reader_sp)
1489 reader_sp->Activate();
1490
1491 return true;
1492}
1493
1495 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1496 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1497 if (reader_sp)
1498 reader_sp->Refresh();
1499}
1500
1502 return std::make_unique<StreamAsynchronousIO>(*this,
1504}
1505
1507 return std::make_unique<StreamAsynchronousIO>(*this,
1509}
1510
1512 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1514}
1515
1517 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1518 if (m_interrupt_requested > 0)
1520}
1521
1523 // This is the one we should call internally. This will return true either
1524 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1525 // or if we are on the IOHandler thread and there's a CommandInterpreter
1526 // interrupt.
1528 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1529 return m_interrupt_requested != 0;
1530 }
1532}
1533
1535 std::string function_name, const llvm::formatv_object_base &payload)
1536 : m_function_name(std::move(function_name)),
1537 m_interrupt_time(std::chrono::system_clock::now()),
1538 m_thread_id(llvm::get_threadid()) {
1539 llvm::raw_string_ostream desc(m_description);
1540 desc << payload << "\n";
1541}
1542
1544 // For now, just log the description:
1545 Log *log = GetLog(LLDBLog::Host);
1546 LLDB_LOG(log, "Interruption: {0}", report.m_description);
1547}
1548
1550 DebuggerList result;
1552 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1553 for (auto debugger_sp : *g_debugger_list_ptr) {
1554 if (debugger_sp->InterruptRequested())
1555 result.push_back(debugger_sp);
1556 }
1557 }
1558 return result;
1559}
1560
1563 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1564 return g_debugger_list_ptr->size();
1565 }
1566 return 0;
1567}
1568
1570 DebuggerSP debugger_sp;
1571
1573 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1574 if (index < g_debugger_list_ptr->size())
1575 debugger_sp = g_debugger_list_ptr->at(index);
1576 }
1577
1578 return debugger_sp;
1579}
1580
1582 DebuggerSP debugger_sp;
1583
1585 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1586 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1587 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1588 if ((*pos)->GetID() == id) {
1589 debugger_sp = *pos;
1590 break;
1591 }
1592 }
1593 }
1594 return debugger_sp;
1595}
1596
1598 const SymbolContext *sc,
1599 const SymbolContext *prev_sc,
1600 const ExecutionContext *exe_ctx,
1601 const Address *addr, Stream &s) {
1602 FormatEntity::Entry format_entry;
1603
1604 if (format == nullptr) {
1605 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) {
1606 format_entry =
1608 format = &format_entry;
1609 }
1610 if (format == nullptr) {
1611 FormatEntity::Parse("${addr}: ", format_entry);
1612 format = &format_entry;
1613 }
1614 }
1615 bool function_changed = false;
1616 bool initial_function = false;
1617 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1618 if (sc && (sc->function || sc->symbol)) {
1619 if (prev_sc->symbol && sc->symbol) {
1620 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1621 prev_sc->symbol->GetType())) {
1622 function_changed = true;
1623 }
1624 } else if (prev_sc->function && sc->function) {
1625 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1626 function_changed = true;
1627 }
1628 }
1629 }
1630 }
1631 // The first context on a list of instructions will have a prev_sc that has
1632 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1633 // would return false. But we do get a prev_sc pointer.
1634 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1635 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1636 initial_function = true;
1637 }
1638 return FormatEntity::Formatter(sc, exe_ctx, addr, function_changed,
1639 initial_function)
1640 .Format(*format, s);
1641}
1642
1643void Debugger::AssertCallback(llvm::StringRef message,
1644 llvm::StringRef backtrace,
1645 llvm::StringRef prompt) {
1646 Debugger::ReportError(llvm::formatv("{0}\n{1}{2}\n{3}", message, backtrace,
1647 GetVersion(), prompt)
1648 .str());
1649}
1650
1652 void *baton) {
1653 // For simplicity's sake, I am not going to deal with how to close down any
1654 // open logging streams, I just redirect everything from here on out to the
1655 // callback.
1657 std::make_shared<CallbackLogHandler>(log_callback, baton);
1658}
1659
1661 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1662 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1663 m_destroy_callbacks.clear();
1665 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1666}
1667
1669 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1670 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1672 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1673 return token;
1674}
1675
1677 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1678 for (auto it = m_destroy_callbacks.begin(); it != m_destroy_callbacks.end();
1679 ++it) {
1680 if (it->token == token) {
1681 m_destroy_callbacks.erase(it);
1682 return true;
1683 }
1684 }
1685 return false;
1686}
1687
1688static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1689 std::string title, std::string details,
1690 uint64_t completed, uint64_t total,
1691 bool is_debugger_specific,
1692 uint32_t progress_broadcast_bit) {
1693 // Only deliver progress events if we have any progress listeners.
1694 if (!debugger.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit))
1695 return;
1696
1697 EventSP event_sp(new Event(
1698 progress_broadcast_bit,
1699 new ProgressEventData(progress_id, std::move(title), std::move(details),
1700 completed, total, is_debugger_specific)));
1701 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1702}
1703
1704void Debugger::ReportProgress(uint64_t progress_id, std::string title,
1705 std::string details, uint64_t completed,
1706 uint64_t total,
1707 std::optional<lldb::user_id_t> debugger_id,
1708 uint32_t progress_broadcast_bit) {
1709 // Check if this progress is for a specific debugger.
1710 if (debugger_id) {
1711 // It is debugger specific, grab it and deliver the event if the debugger
1712 // still exists.
1713 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1714 if (debugger_sp)
1715 PrivateReportProgress(*debugger_sp, progress_id, std::move(title),
1716 std::move(details), completed, total,
1717 /*is_debugger_specific*/ true,
1718 progress_broadcast_bit);
1719 return;
1720 }
1721 // The progress event is not debugger specific, iterate over all debuggers
1722 // and deliver a progress event to each one.
1724 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1725 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1726 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1727 PrivateReportProgress(*(*pos), progress_id, title, details, completed,
1728 total, /*is_debugger_specific*/ false,
1729 progress_broadcast_bit);
1730 }
1731}
1732
1733static void PrivateReportDiagnostic(Debugger &debugger, Severity severity,
1734 std::string message,
1735 bool debugger_specific) {
1736 uint32_t event_type = 0;
1737 switch (severity) {
1738 case eSeverityInfo:
1739 assert(false && "eSeverityInfo should not be broadcast");
1740 return;
1741 case eSeverityWarning:
1742 event_type = lldb::eBroadcastBitWarning;
1743 break;
1744 case eSeverityError:
1745 event_type = lldb::eBroadcastBitError;
1746 break;
1747 }
1748
1749 Broadcaster &broadcaster = debugger.GetBroadcaster();
1750 if (!broadcaster.EventTypeHasListeners(event_type)) {
1751 // Diagnostics are too important to drop. If nobody is listening, print the
1752 // diagnostic directly to the debugger's error stream.
1753 DiagnosticEventData event_data(severity, std::move(message),
1754 debugger_specific);
1755 event_data.Dump(debugger.GetAsyncErrorStream().get());
1756 return;
1757 }
1758 EventSP event_sp = std::make_shared<Event>(
1759 event_type,
1760 new DiagnosticEventData(severity, std::move(message), debugger_specific));
1761 broadcaster.BroadcastEvent(event_sp);
1762}
1763
1764void Debugger::ReportDiagnosticImpl(Severity severity, std::string message,
1765 std::optional<lldb::user_id_t> debugger_id,
1766 std::once_flag *once) {
1767 auto ReportDiagnosticLambda = [&]() {
1768 // Always log diagnostics to the system log.
1769 Host::SystemLog(severity, message);
1770
1771 // The diagnostic subsystem is optional but we still want to broadcast
1772 // events when it's disabled.
1774 Diagnostics::Instance().Report(message);
1775
1776 // We don't broadcast info events.
1777 if (severity == lldb::eSeverityInfo)
1778 return;
1779
1780 // Check if this diagnostic is for a specific debugger.
1781 if (debugger_id) {
1782 // It is debugger specific, grab it and deliver the event if the debugger
1783 // still exists.
1784 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1785 if (debugger_sp)
1786 PrivateReportDiagnostic(*debugger_sp, severity, std::move(message),
1787 true);
1788 return;
1789 }
1790 // The diagnostic event is not debugger specific, iterate over all debuggers
1791 // and deliver a diagnostic event to each one.
1793 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1794 for (const auto &debugger : *g_debugger_list_ptr)
1795 PrivateReportDiagnostic(*debugger, severity, message, false);
1796 }
1797 };
1798
1799 if (once)
1800 std::call_once(*once, ReportDiagnosticLambda);
1801 else
1802 ReportDiagnosticLambda();
1803}
1804
1805void Debugger::ReportWarning(std::string message,
1806 std::optional<lldb::user_id_t> debugger_id,
1807 std::once_flag *once) {
1808 ReportDiagnosticImpl(eSeverityWarning, std::move(message), debugger_id, once);
1809}
1810
1811void Debugger::ReportError(std::string message,
1812 std::optional<lldb::user_id_t> debugger_id,
1813 std::once_flag *once) {
1814 ReportDiagnosticImpl(eSeverityError, std::move(message), debugger_id, once);
1815}
1816
1817void Debugger::ReportInfo(std::string message,
1818 std::optional<lldb::user_id_t> debugger_id,
1819 std::once_flag *once) {
1820 ReportDiagnosticImpl(eSeverityInfo, std::move(message), debugger_id, once);
1821}
1822
1825 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1826 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1827 EventSP event_sp = std::make_shared<Event>(
1829 new SymbolChangeEventData(debugger_sp, module_spec));
1830 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1831 }
1832 }
1833}
1834
1835static std::shared_ptr<LogHandler>
1836CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1837 size_t buffer_size) {
1838 switch (log_handler_kind) {
1839 case eLogHandlerStream:
1840 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1842 return std::make_shared<RotatingLogHandler>(buffer_size);
1843 case eLogHandlerSystem:
1844 return std::make_shared<SystemLogHandler>();
1846 return {};
1847 }
1848 return {};
1849}
1850
1851bool Debugger::EnableLog(llvm::StringRef channel,
1852 llvm::ArrayRef<const char *> categories,
1853 llvm::StringRef log_file, uint32_t log_options,
1854 size_t buffer_size, LogHandlerKind log_handler_kind,
1855 llvm::raw_ostream &error_stream) {
1856
1857 std::shared_ptr<LogHandler> log_handler_sp;
1859 log_handler_sp = m_callback_handler_sp;
1860 // For now when using the callback mode you always get thread & timestamp.
1861 log_options |=
1863 } else if (log_file.empty()) {
1864 log_handler_sp =
1865 CreateLogHandler(log_handler_kind, GetOutputFileSP()->GetDescriptor(),
1866 /*should_close=*/false, buffer_size);
1867 } else {
1868 auto pos = m_stream_handlers.find(log_file);
1869 if (pos != m_stream_handlers.end())
1870 log_handler_sp = pos->second.lock();
1871 if (!log_handler_sp) {
1872 File::OpenOptions flags =
1874 if (log_options & LLDB_LOG_OPTION_APPEND)
1875 flags |= File::eOpenOptionAppend;
1876 else
1878 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1879 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1880 if (!file) {
1881 error_stream << "Unable to open log file '" << log_file
1882 << "': " << llvm::toString(file.takeError()) << "\n";
1883 return false;
1884 }
1885
1886 log_handler_sp =
1887 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1888 /*should_close=*/true, buffer_size);
1889 m_stream_handlers[log_file] = log_handler_sp;
1890 }
1891 }
1892 assert(log_handler_sp);
1893
1894 if (log_options == 0)
1896
1897 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories,
1898 error_stream);
1899}
1900
1903 std::optional<lldb::ScriptLanguage> language) {
1904 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1905 lldb::ScriptLanguage script_language =
1906 language ? *language : GetScriptLanguage();
1907
1908 if (!m_script_interpreters[script_language]) {
1909 if (!can_create)
1910 return nullptr;
1911 m_script_interpreters[script_language] =
1912 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1913 }
1914
1915 return m_script_interpreters[script_language].get();
1916}
1917
1920 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1921 return *m_source_manager_up;
1922}
1923
1924// This function handles events that were broadcast by the process.
1926 using namespace lldb;
1927 const uint32_t event_type =
1929 event_sp);
1930
1931 // if (event_type & eBreakpointEventTypeAdded
1932 // || event_type & eBreakpointEventTypeRemoved
1933 // || event_type & eBreakpointEventTypeEnabled
1934 // || event_type & eBreakpointEventTypeDisabled
1935 // || event_type & eBreakpointEventTypeCommandChanged
1936 // || event_type & eBreakpointEventTypeConditionChanged
1937 // || event_type & eBreakpointEventTypeIgnoreChanged
1938 // || event_type & eBreakpointEventTypeLocationsResolved)
1939 // {
1940 // // Don't do anything about these events, since the breakpoint
1941 // commands already echo these actions.
1942 // }
1943 //
1944 if (event_type & eBreakpointEventTypeLocationsAdded) {
1945 uint32_t num_new_locations =
1947 event_sp);
1948 if (num_new_locations > 0) {
1949 BreakpointSP breakpoint =
1951 if (StreamUP output_up = GetAsyncOutputStream()) {
1952 output_up->Printf("%d location%s added to breakpoint %d\n",
1953 num_new_locations, num_new_locations == 1 ? "" : "s",
1954 breakpoint->GetID());
1955 output_up->Flush();
1956 }
1957 }
1958 }
1959 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1960 // {
1961 // // These locations just get disabled, not sure it is worth spamming
1962 // folks about this on the command line.
1963 // }
1964 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1965 // {
1966 // // This might be an interesting thing to note, but I'm going to
1967 // leave it quiet for now, it just looked noisy.
1968 // }
1969}
1970
1971void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1972 bool flush_stderr) {
1973 const auto &flush = [&](Stream &stream,
1974 size_t (Process::*get)(char *, size_t, Status &)) {
1975 Status error;
1976 size_t len;
1977 char buffer[1024];
1978 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1979 stream.Write(buffer, len);
1980 stream.Flush();
1981 };
1982
1983 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1984 if (flush_stdout)
1986 if (flush_stderr)
1988}
1989
1990// This function handles events that were broadcast by the process.
1992 const uint32_t event_type = event_sp->GetType();
1993 ProcessSP process_sp =
1997
1998 StreamUP output_stream_up = GetAsyncOutputStream();
1999 StreamUP error_stream_up = GetAsyncErrorStream();
2000 const bool gui_enabled = IsForwardingEvents();
2001
2002 if (!gui_enabled) {
2003 bool pop_process_io_handler = false;
2004 assert(process_sp);
2005
2006 bool state_is_stopped = false;
2007 const bool got_state_changed =
2008 (event_type & Process::eBroadcastBitStateChanged) != 0;
2009 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
2010 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
2011 const bool got_structured_data =
2012 (event_type & Process::eBroadcastBitStructuredData) != 0;
2013
2014 if (got_state_changed) {
2015 StateType event_state =
2017 state_is_stopped = StateIsStoppedState(event_state, false);
2018 }
2019
2020 // Display running state changes first before any STDIO
2021 if (got_state_changed && !state_is_stopped) {
2022 // This is a public stop which we are going to announce to the user, so
2023 // we should force the most relevant frame selection here.
2024 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2026 pop_process_io_handler);
2027 }
2028
2029 // Now display STDOUT and STDERR
2030 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
2031 got_stderr || got_state_changed);
2032
2033 // Give structured data events an opportunity to display.
2034 if (got_structured_data) {
2035 StructuredDataPluginSP plugin_sp =
2037 if (plugin_sp) {
2038 auto structured_data_sp =
2040 StreamString content_stream;
2041 Status error =
2042 plugin_sp->GetDescription(structured_data_sp, content_stream);
2043 if (error.Success()) {
2044 if (!content_stream.GetString().empty()) {
2045 // Add newline.
2046 content_stream.PutChar('\n');
2047 content_stream.Flush();
2048
2049 // Print it.
2050 output_stream_up->PutCString(content_stream.GetString());
2051 }
2052 } else {
2053 error_stream_up->Format("Failed to print structured "
2054 "data with plugin {0}: {1}",
2055 plugin_sp->GetPluginName(), error);
2056 }
2057 }
2058 }
2059
2060 // Now display any stopped state changes after any STDIO
2061 if (got_state_changed && state_is_stopped) {
2062 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2064 pop_process_io_handler);
2065 }
2066
2067 output_stream_up->Flush();
2068 error_stream_up->Flush();
2069
2070 if (pop_process_io_handler)
2071 process_sp->PopProcessIOHandler();
2072 }
2073 return process_sp;
2074}
2075
2077 // At present the only thread event we handle is the Frame Changed event, and
2078 // all we do for that is just reprint the thread status for that thread.
2079 const uint32_t event_type = event_sp->GetType();
2080 const bool stop_format = true;
2081 ThreadSP thread_sp;
2082 if (event_type == Thread::eBroadcastBitStackChanged ||
2084 thread_sp = Thread::ThreadEventData::GetThreadFromEvent(event_sp.get());
2085 if (thread_sp) {
2086 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format,
2087 /*show_hidden*/ true);
2088 }
2089 }
2090 return thread_sp;
2091}
2092
2094
2096 m_forward_listener_sp = listener_sp;
2097}
2098
2100 m_forward_listener_sp.reset();
2101}
2102
2105 File &file = stream_sp->GetUnlockedFile();
2106 return file.GetIsInteractive() && file.GetIsRealTerminal() &&
2108 }
2109 return false;
2110}
2111
2113// We have trouble with the contol codes on Windows, see
2114// https://github.com/llvm/llvm-project/issues/134846.
2115#ifndef _WIN32
2117#else
2118 return false;
2119#endif
2120}
2121
2122static bool RequiresFollowChildWorkaround(const Process &process) {
2123 // FIXME: https://github.com/llvm/llvm-project/issues/160216
2124 return process.GetFollowForkMode() == eFollowChild;
2125}
2126
2128 ListenerSP listener_sp(GetListener());
2129 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
2130 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
2131 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
2132 BroadcastEventSpec target_event_spec(broadcaster_class_target,
2134
2135 BroadcastEventSpec process_event_spec(
2136 broadcaster_class_process,
2139
2140 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
2143
2144 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2145 target_event_spec);
2146 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2147 process_event_spec);
2148 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2149 thread_event_spec);
2150 listener_sp->StartListeningForEvents(
2155
2156 listener_sp->StartListeningForEvents(
2161
2162 // Let the thread that spawned us know that we have started up and that we
2163 // are now listening to all required events so no events get missed
2165
2166 if (StatuslineSupported()) {
2167 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2168 if (!m_statusline) {
2169 m_statusline.emplace(*this);
2171 }
2172 }
2173
2174 bool done = false;
2175 while (!done) {
2176 EventSP event_sp;
2177 if (listener_sp->GetEvent(event_sp, std::nullopt)) {
2178 std::optional<ExecutionContextRef> exe_ctx_ref = std::nullopt;
2179 if (event_sp) {
2180 Broadcaster *broadcaster = event_sp->GetBroadcaster();
2181 if (broadcaster) {
2182 uint32_t event_type = event_sp->GetType();
2183 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
2184 if (broadcaster_class == broadcaster_class_process) {
2185 if (ProcessSP process_sp = HandleProcessEvent(event_sp))
2186 if (!RequiresFollowChildWorkaround(*process_sp))
2187 exe_ctx_ref = ExecutionContextRef(process_sp.get(),
2188 /*adopt_selected=*/true);
2189 } else if (broadcaster_class == broadcaster_class_target) {
2191 event_sp.get())) {
2192 HandleBreakpointEvent(event_sp);
2193 }
2194 } else if (broadcaster_class == broadcaster_class_thread) {
2195 if (ThreadSP thread_sp = HandleThreadEvent(event_sp))
2196 if (!RequiresFollowChildWorkaround(*thread_sp->GetProcess()))
2197 exe_ctx_ref = ExecutionContextRef(thread_sp.get(),
2198 /*adopt_selected=*/true);
2199 } else if (broadcaster == m_command_interpreter_up.get()) {
2200 if (event_type &
2202 done = true;
2203 } else if (event_type &
2205 const char *data = static_cast<const char *>(
2206 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2207 if (data && data[0]) {
2208 StreamUP error_up = GetAsyncErrorStream();
2209 error_up->PutCString(data);
2210 error_up->Flush();
2211 }
2212 } else if (event_type & CommandInterpreter::
2213 eBroadcastBitAsynchronousOutputData) {
2214 const char *data = static_cast<const char *>(
2215 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2216 if (data && data[0]) {
2217 StreamUP output_up = GetAsyncOutputStream();
2218 output_up->PutCString(data);
2219 output_up->Flush();
2220 }
2221 }
2222 } else if (broadcaster == &m_broadcaster) {
2223 if (event_type & lldb::eBroadcastBitProgress ||
2225 HandleProgressEvent(event_sp);
2226 else if (event_type & lldb::eBroadcastBitWarning)
2227 HandleDiagnosticEvent(event_sp);
2228 else if (event_type & lldb::eBroadcastBitError)
2229 HandleDiagnosticEvent(event_sp);
2230 }
2231 }
2232
2234 m_forward_listener_sp->AddEvent(event_sp);
2235 }
2236 RedrawStatusline(exe_ctx_ref);
2237 }
2238 }
2239
2240 {
2241 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2242 if (m_statusline)
2243 m_statusline.reset();
2244 }
2245
2246 return {};
2247}
2248
2250 if (!m_event_handler_thread.IsJoinable()) {
2251 // We must synchronize with the DefaultEventHandler() thread to ensure it
2252 // is up and running and listening to events before we return from this
2253 // function. We do this by listening to events for the
2254 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2255 ConstString full_name("lldb.debugger.event-handler");
2256 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
2257 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
2259
2260 llvm::StringRef thread_name =
2261 full_name.GetLength() < llvm::get_max_thread_name_length()
2262 ? full_name.GetStringRef()
2263 : "dbg.evt-handler";
2264
2265 // Use larger 8MB stack for this thread
2266 llvm::Expected<HostThread> event_handler_thread =
2268 thread_name, [this] { return DefaultEventHandler(); },
2270
2271 if (event_handler_thread) {
2272 m_event_handler_thread = *event_handler_thread;
2273 } else {
2274 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(),
2275 "failed to launch host thread: {0}");
2276 }
2277
2278 // Make sure DefaultEventHandler() is running and listening to events
2279 // before we return from this function. We are only listening for events of
2280 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2281 // event, we just need to wait an infinite amount of time for it (nullptr
2282 // timeout as the first parameter)
2283 lldb::EventSP event_sp;
2284 listener_sp->GetEvent(event_sp, std::nullopt);
2285 }
2286 return m_event_handler_thread.IsJoinable();
2287}
2288
2296
2302
2304 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
2305 if (!data)
2306 return;
2307
2308 // Make a local copy of the incoming progress report that we'll store.
2309 ProgressReport progress_report{data->GetID(), data->GetCompleted(),
2310 data->GetTotal(), data->GetMessage()};
2311
2312 {
2313 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2314
2315 // Do some bookkeeping regardless of whether we're going to display
2316 // progress reports.
2317 auto it = llvm::find_if(m_progress_reports, [&](const auto &report) {
2318 return report.id == progress_report.id;
2319 });
2320 if (it != m_progress_reports.end()) {
2321 const bool complete = data->GetCompleted() == data->GetTotal();
2322 if (complete)
2323 m_progress_reports.erase(it);
2324 else
2325 *it = progress_report;
2326 } else {
2327 m_progress_reports.push_back(progress_report);
2328 }
2329
2330 // Show progress using Operating System Command (OSC) sequences.
2333
2334 // Clear progress if this was the last progress event.
2335 if (m_progress_reports.empty()) {
2336 stream_sp->Lock() << OSC_PROGRESS_REMOVE;
2337 return;
2338 }
2339
2340 const ProgressReport &report = m_progress_reports.back();
2341
2342 // Show indeterminate progress.
2343 if (report.total == UINT64_MAX) {
2344 stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE;
2345 return;
2346 }
2347
2348 // Compute and show the progress value (0-100).
2349 const unsigned value = (report.completed / report.total) * 100;
2350 stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value);
2351 }
2352 }
2353 }
2354}
2355
2356std::optional<Debugger::ProgressReport>
2358 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2359 if (m_progress_reports.empty())
2360 return std::nullopt;
2361 return m_progress_reports.back();
2362}
2363
2365 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
2366 if (!data)
2367 return;
2368
2369 data->Dump(GetAsyncErrorStream().get());
2370}
2371
2373 return m_io_handler_thread.IsJoinable();
2374}
2375
2378 m_io_handler_thread = new_thread;
2379 return old_host;
2380}
2381
2383 if (!m_io_handler_thread.IsJoinable()) {
2384 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
2385 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2386 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2387 if (io_handler_thread) {
2388 m_io_handler_thread = *io_handler_thread;
2389 } else {
2390 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(),
2391 "failed to launch host thread: {0}");
2392 }
2393 }
2394 return m_io_handler_thread.IsJoinable();
2395}
2396
2398 if (m_io_handler_thread.IsJoinable()) {
2399 GetInputFile().Close();
2400 m_io_handler_thread.Join(nullptr);
2401 }
2402}
2403
2411
2413 if (!HasIOHandlerThread())
2414 return false;
2415 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread());
2416}
2417
2419 if (!prefer_dummy) {
2420 if (TargetSP target = m_target_list.GetSelectedTarget())
2421 return *target;
2422 }
2423 return GetDummyTarget();
2424}
2425
2426Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
2427 Status err;
2428 FileSpec repl_executable;
2429
2430 if (language == eLanguageTypeUnknown)
2431 language = GetREPLLanguage();
2432
2433 if (language == eLanguageTypeUnknown) {
2435
2436 if (auto single_lang = repl_languages.GetSingularLanguage()) {
2437 language = *single_lang;
2438 } else if (repl_languages.Empty()) {
2440 "LLDB isn't configured with REPL support for any languages.");
2441 return err;
2442 } else {
2444 "Multiple possible REPL languages. Please specify a language.");
2445 return err;
2446 }
2447 }
2448
2449 Target *const target =
2450 nullptr; // passing in an empty target means the REPL must create one
2451
2452 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2453
2454 if (!err.Success()) {
2455 return err;
2456 }
2457
2458 if (!repl_sp) {
2460 "couldn't find a REPL for %s",
2462 return err;
2463 }
2464
2465 repl_sp->SetCompilerOptions(repl_options);
2466 repl_sp->RunLoop();
2467
2468 return err;
2469}
2470
2471llvm::ThreadPoolInterface &Debugger::GetThreadPool() {
2472 assert(g_thread_pool &&
2473 "Debugger::GetThreadPool called before Debugger::Initialize");
2474 return *g_thread_pool;
2475}
2476
2478 llvm::StringRef name, bool value,
2479 llvm::StringRef description) {
2480 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2481 entry_up->AddBooleanItem("value", value);
2482 entry_up->AddStringItem("description", description);
2483 dict.AddItem(name, std::move(entry_up));
2484}
2485
2487 auto array_up = std::make_unique<StructuredData::Array>();
2488#define LLVM_TARGET(target) \
2489 array_up->AddItem(std::make_unique<StructuredData::String>(#target));
2490#include "llvm/Config/Targets.def"
2491 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2492 entry_up->AddItem("value", std::move(array_up));
2493 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
2494 dict.AddItem("targets", std::move(entry_up));
2495}
2496
2498 auto config_up = std::make_unique<StructuredData::Dictionary>();
2500 *config_up, "xml", XMLDocument::XMLEnabled(),
2501 "A boolean value that indicates if XML support is enabled in LLDB");
2503 *config_up, "curl", LLVM_ENABLE_CURL,
2504 "A boolean value that indicates if CURL support is enabled in LLDB");
2506 *config_up, "curses", LLDB_ENABLE_CURSES,
2507 "A boolean value that indicates if curses support is enabled in LLDB");
2509 *config_up, "editline", LLDB_ENABLE_LIBEDIT,
2510 "A boolean value that indicates if editline support is enabled in LLDB");
2511 AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,
2512 "A boolean value that indicates if editline wide "
2513 "characters support is enabled in LLDB");
2515 *config_up, "zlib", LLVM_ENABLE_ZLIB,
2516 "A boolean value that indicates if zlib support is enabled in LLDB");
2518 *config_up, "lzma", LLDB_ENABLE_LZMA,
2519 "A boolean value that indicates if lzma support is enabled in LLDB");
2521 *config_up, "python", LLDB_ENABLE_PYTHON,
2522 "A boolean value that indicates if python support is enabled in LLDB");
2524 *config_up, "lua", LLDB_ENABLE_LUA,
2525 "A boolean value that indicates if lua support is enabled in LLDB");
2526 AddBoolConfigEntry(*config_up, "fbsdvmcore", LLDB_ENABLE_FBSDVMCORE,
2527 "A boolean value that indicates if fbsdvmcore support is "
2528 "enabled in LLDB");
2529 AddLLVMTargets(*config_up);
2530 return config_up;
2531}
#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 std::recursive_mutex * g_debugger_list_mutex_ptr
Definition Debugger.cpp:110
static llvm::DefaultThreadPool * g_thread_pool
Definition Debugger.cpp:114
static constexpr OptionEnumValueElement g_show_disassembly_enum_values[]
Definition Debugger.cpp:116
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:112
static int OpenPipe(int fds[2], std::size_t size)
static size_t g_debugger_event_thread_stack_bytes
Definition Debugger.cpp:106
static FileSystem::EnumerateDirectoryResult LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path)
Definition Debugger.cpp:801
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:31
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:366
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:503
InterruptionReport(std::string function_name, std::string description)
Definition Debugger.h:485
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:751
HostThread m_event_handler_thread
Definition Debugger.h:781
static lldb::TargetSP FindTargetWithProcessID(lldb::pid_t pid)
Definition Debugger.cpp:962
FormatEntity::Entry GetDisassemblyFormat() const
Definition Debugger.cpp:330
uint64_t GetDisassemblyLineCount() const
Definition Debugger.cpp:666
lldb::TargetSP GetSelectedTarget()
Definition Debugger.h:190
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:738
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:777
static void Terminate()
Definition Debugger.cpp:753
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:695
lldb::FileSP GetInputFileSP()
Definition Debugger.h:146
bool GetHighlightSource() const
Definition Debugger.cpp:615
llvm::StringMap< std::weak_ptr< LogHandler > > m_stream_handlers
Definition Debugger.h:775
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:173
FormatEntity::Entry GetStatuslineFormat() const
Definition Debugger.cpp:528
LoadedPluginsList m_loaded_plugins
Definition Debugger.h:780
bool GetShowInlineDiagnostics() const
Definition Debugger.cpp:724
bool SetTabSize(uint64_t tab_size)
Definition Debugger.cpp:712
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:752
void PushIOHandler(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
std::mutex m_destroy_callback_mutex
Definition Debugger.h:796
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
static lldb::TargetSP FindTargetWithProcess(Process *process)
Definition Debugger.cpp:976
llvm::StringRef GetDisabledAnsiPrefix() const
Definition Debugger.cpp:546
bool GetUseExternalEditor() const
Definition Debugger.cpp:462
TerminalState m_terminal_state
Definition Debugger.h:748
lldb::StreamUP GetAsyncErrorStream()
bool GetEscapeNonPrintables() const
Definition Debugger.cpp:678
lldb::TargetSP m_dummy_target_sp
Definition Debugger.h:787
llvm::SmallVector< DestroyCallbackInfo, 2 > m_destroy_callbacks
Definition Debugger.h:808
std::unique_ptr< CommandInterpreter > m_command_interpreter_up
Definition Debugger.h:762
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:779
LockableStreamFile::Mutex m_output_mutex
Definition Debugger.h:740
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:792
bool IsIOHandlerThreadCurrentThread() const
void DispatchClientTelemetry(const lldb_private::StructuredDataImpl &entry)
Definition Debugger.cpp:889
std::mutex m_progress_reports_mutex
Definition Debugger.h:793
lldb::ProcessSP HandleProcessEvent(const lldb::EventSP &event_sp)
lldb::ListenerSP m_forward_listener_sp
Definition Debugger.h:785
std::array< lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown > m_script_interpreters
Definition Debugger.h:766
std::shared_ptr< CallbackLogHandler > m_callback_handler_sp
Definition Debugger.h:776
void SetDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback, void *baton)
DEPRECATED: We used to only support one Destroy callback.
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:149
Broadcaster m_broadcaster
Public Debugger event broadcaster.
Definition Debugger.h:784
static void Initialize(LoadPluginCallbackType load_plugin_callback)
Definition Debugger.cpp:744
static lldb::DebuggerSP FindDebuggerWithInstanceName(llvm::StringRef instance_name)
Definition Debugger.cpp:947
uint64_t GetTerminalWidth() const
Definition Debugger.cpp:418
std::mutex m_interrupt_mutex
Definition Debugger.h:811
std::recursive_mutex m_io_handler_synchronous_mutex
Definition Debugger.h:769
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:788
bool GetAutoOneLineSummaries() const
Definition Debugger.cpp:672
const char * GetIOHandlerCommandPrefix()
std::optional< Statusline > m_statusline
Definition Debugger.h:773
bool GetUseColor() const
Definition Debugger.cpp:484
lldb::BroadcasterManagerSP m_broadcaster_manager_sp
Definition Debugger.h:742
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:778
bool GetShowStatusline() const
Definition Debugger.cpp:522
std::recursive_mutex m_script_interpreter_mutex
Definition Debugger.h:764
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:691
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:783
bool GetUseSourceCache() const
Definition Debugger.cpp:601
HostThread m_io_handler_thread
Definition Debugger.h:782
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:589
static llvm::StringRef GetStaticBroadcasterClass()
Definition Debugger.cpp:990
lldb::FileSP m_input_file_sp
Definition Debugger.h:737
bool SetREPLLanguage(lldb::LanguageType repl_lang)
Definition Debugger.cpp:413
bool GetAutoIndent() const
Definition Debugger.cpp:684
llvm::StringRef GetStopShowColumnAnsiSuffix() const
Definition Debugger.cpp:634
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:749
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:396
lldb::callback_token_t m_destroy_callback_next_token
Definition Debugger.h:797
std::unique_ptr< SourceManager > m_source_manager_up
Definition Debugger.h:753
static lldb::DebuggerSP CreateInstance(lldb::LogOutputCallback log_callback=nullptr, void *baton=nullptr)
Definition Debugger.cpp:871
lldb::StopShowColumn GetStopShowColumn() const
Definition Debugger.cpp:621
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:701
bool SetScriptLanguage(lldb::ScriptLanguage script_lang)
Definition Debugger.cpp:403
lldb::LockableStreamFileSP m_error_stream_sp
Definition Debugger.h:739
bool SetShowInlineDiagnostics(bool)
Definition Debugger.cpp:730
bool LoadPlugin(const FileSpec &spec, Status &error)
Definition Debugger.cpp:783
void SetOutputFile(lldb::FileSP file)
uint64_t GetStopSourceLineCount(bool before) const
Definition Debugger.cpp:652
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:518
lldb::ListenerSP GetListener()
Definition Debugger.h:182
static void Destroy(lldb::DebuggerSP &debugger_sp)
Definition Debugger.cpp:915
SourceManager::SourceFileCache m_source_file_cache
Definition Debugger.h:757
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:640
bool GetShowDontUsePoHint() const
Definition Debugger.cpp:595
uint64_t GetTabSize() const
Definition Debugger.cpp:706
bool GetShowProgress() const
Definition Debugger.cpp:499
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:583
std::mutex m_output_flush_mutex
Definition Debugger.h:732
llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const
Definition Debugger.cpp:646
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:772
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:768
llvm::once_flag m_clear_once
Definition Debugger.h:786
static void SettingsTerminate()
Definition Debugger.cpp:781
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:995
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:810
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition Debugger.cpp:717
lldb::thread_result_t DefaultEventHandler()
void PrintAsync(const char *s, size_t len, bool is_stdout)
lldb::LockableStreamFileSP GetErrorStreamSP()
Definition Debugger.h:692
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:659
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:690
friend class CommandInterpreter
Definition Debugger.h:638
llvm::StringRef GetStopShowColumnAnsiPrefix() const
Definition Debugger.cpp:628
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:479
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:309
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:4505
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4513
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:733
static llvm::StringRef GetStaticBroadcasterClass()
Definition Process.cpp:423
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4708
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4689
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:304
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:1194
static void SettingsTerminate()
Definition Target.cpp:2795
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:169
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3287
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2805
@ eBroadcastBitBreakpointChanged
Definition Target.h:535
static void SettingsInitialize()
Definition Target.cpp:2793
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:187
@ eBroadcastBitThreadSelected
Definition Thread.h:77
static llvm::StringRef GetStaticBroadcasterClass()
Definition Thread.cpp:219
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:55
@ eLoadScriptFromSymFileTrue
Definition Target.h:56
@ eLoadScriptFromSymFileFalse
Definition Target.h:57
@ eLoadScriptFromSymFileWarn
Definition Target.h:58
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
uint64_t pid_t
Definition lldb-types.h:83
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:805
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