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
206
209 llvm::StringRef property_path,
210 llvm::StringRef value) {
211 bool is_load_script =
212 (property_path == "target.load-script-from-symbol-file");
213 // These properties might change how we visualize data.
214 bool invalidate_data_vis = (property_path == "escape-non-printables");
215 invalidate_data_vis |=
216 (property_path == "target.max-zero-padding-in-float-format");
217 if (invalidate_data_vis) {
219 }
220
221 TargetSP target_sp;
223 if (is_load_script && exe_ctx && exe_ctx->GetTargetSP()) {
224 target_sp = exe_ctx->GetTargetSP();
225 load_script_old_value =
226 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
227 }
228 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
229 if (error.Success()) {
230 // FIXME it would be nice to have "on-change" callbacks for properties
231 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
232 llvm::StringRef new_prompt = GetPrompt();
234 new_prompt, GetUseColor());
235 if (str.length())
236 new_prompt = str;
238 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
239 auto prompt_change_event_sp = std::make_shared<Event>(
241 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
242 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
243 // use-color changed. set use-color, this also pings the prompt so it can
244 // reset the ansi terminal codes.
246 } else if (property_path ==
247 g_debugger_properties[ePropertyPromptAnsiPrefix].name ||
248 property_path ==
249 g_debugger_properties[ePropertyPromptAnsiSuffix].name) {
250 // Prompt color changed. set use-color, this also pings the prompt so it
251 // can reset the ansi terminal codes.
253 } else if (property_path ==
254 g_debugger_properties[ePropertyShowStatusline].name) {
255 // Statusline setting changed. If we have a statusline instance, update it
256 // now. Otherwise it will get created in the default event handler.
257 std::lock_guard<std::mutex> guard(m_statusline_mutex);
258 if (StatuslineSupported()) {
259 m_statusline.emplace(*this);
261 } else {
262 m_statusline.reset();
263 }
264 } else if (property_path ==
265 g_debugger_properties[ePropertyStatuslineFormat].name ||
266 property_path ==
267 g_debugger_properties[ePropertySeparator].name) {
268 // Statusline format changed. Redraw the statusline.
269 RedrawStatusline(std::nullopt);
270 } else if (property_path ==
271 g_debugger_properties[ePropertyUseSourceCache].name) {
272 // use-source-cache changed. Wipe out the cache contents if it was
273 // disabled.
274 if (!GetUseSourceCache()) {
275 m_source_file_cache.Clear();
276 }
277 } else if (is_load_script && target_sp &&
278 load_script_old_value == eLoadScriptFromSymFileWarn) {
279 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
281 std::list<Status> errors;
282 StreamString feedback_stream;
283 if (!target_sp->LoadScriptingResources(errors, feedback_stream)) {
285 for (auto &error : errors)
286 s->Printf("%s\n", error.AsCString());
287 if (feedback_stream.GetSize())
288 s->PutCString(feedback_stream.GetString());
289 }
290 }
291 }
292 }
293 return error;
294}
295
297 constexpr uint32_t idx = ePropertyAutoConfirm;
299 idx, g_debugger_properties[idx].default_uint_value != 0);
300}
301
303 constexpr uint32_t idx = ePropertyDisassemblyFormat;
305}
306
308 constexpr uint32_t idx = ePropertyFrameFormat;
310}
311
313 constexpr uint32_t idx = ePropertyFrameFormatUnique;
315}
316
318 constexpr uint32_t idx = ePropertyStopDisassemblyMaxSize;
320 idx, g_debugger_properties[idx].default_uint_value);
321}
322
324 constexpr uint32_t idx = ePropertyNotiftVoid;
326 idx, g_debugger_properties[idx].default_uint_value != 0);
327}
328
329llvm::StringRef Debugger::GetPrompt() const {
330 constexpr uint32_t idx = ePropertyPrompt;
332 idx, g_debugger_properties[idx].default_cstr_value);
333}
334
335llvm::StringRef Debugger::GetPromptAnsiPrefix() const {
336 const uint32_t idx = ePropertyPromptAnsiPrefix;
338 idx, g_debugger_properties[idx].default_cstr_value);
339}
340
341llvm::StringRef Debugger::GetPromptAnsiSuffix() const {
342 const uint32_t idx = ePropertyPromptAnsiSuffix;
344 idx, g_debugger_properties[idx].default_cstr_value);
345}
346
347void Debugger::SetPrompt(llvm::StringRef p) {
348 constexpr uint32_t idx = ePropertyPrompt;
349 SetPropertyAtIndex(idx, p);
350 llvm::StringRef new_prompt = GetPrompt();
351 std::string str =
353 if (str.length())
354 new_prompt = str;
356}
357
359 constexpr uint32_t idx = ePropertyThreadFormat;
361}
362
364 constexpr uint32_t idx = ePropertyThreadStopFormat;
366}
367
369 const uint32_t idx = ePropertyScriptLanguage;
371 idx, static_cast<lldb::ScriptLanguage>(
372 g_debugger_properties[idx].default_uint_value));
373}
374
376 const uint32_t idx = ePropertyScriptLanguage;
377 return SetPropertyAtIndex(idx, script_lang);
378}
379
381 const uint32_t idx = ePropertyREPLLanguage;
383}
384
386 const uint32_t idx = ePropertyREPLLanguage;
387 return SetPropertyAtIndex(idx, repl_lang);
388}
389
391 const uint32_t idx = ePropertyTerminalWidth;
393 idx, g_debugger_properties[idx].default_uint_value);
394}
395
396bool Debugger::SetTerminalWidth(uint64_t term_width) {
397 const uint32_t idx = ePropertyTerminalWidth;
398 const bool success = SetPropertyAtIndex(idx, term_width);
399
400 if (auto handler_sp = m_io_handler_stack.Top())
401 handler_sp->TerminalSizeChanged();
402
403 {
404 std::lock_guard<std::mutex> guard(m_statusline_mutex);
405 if (m_statusline)
406 m_statusline->TerminalSizeChanged();
407 }
408
409 return success;
410}
411
413 const uint32_t idx = ePropertyTerminalHeight;
415 idx, g_debugger_properties[idx].default_uint_value);
416}
417
418bool Debugger::SetTerminalHeight(uint64_t term_height) {
419 const uint32_t idx = ePropertyTerminalHeight;
420 const bool success = SetPropertyAtIndex(idx, term_height);
421
422 if (auto handler_sp = m_io_handler_stack.Top())
423 handler_sp->TerminalSizeChanged();
424
425 {
426 std::lock_guard<std::mutex> guard(m_statusline_mutex);
427 if (m_statusline)
428 m_statusline->TerminalSizeChanged();
429 }
430
431 return success;
432}
433
435 const uint32_t idx = ePropertyUseExternalEditor;
437 idx, g_debugger_properties[idx].default_uint_value != 0);
438}
439
441 const uint32_t idx = ePropertyUseExternalEditor;
442 return SetPropertyAtIndex(idx, b);
443}
444
445llvm::StringRef Debugger::GetExternalEditor() const {
446 const uint32_t idx = ePropertyExternalEditor;
448 idx, g_debugger_properties[idx].default_cstr_value);
449}
450
451bool Debugger::SetExternalEditor(llvm::StringRef editor) {
452 const uint32_t idx = ePropertyExternalEditor;
453 return SetPropertyAtIndex(idx, editor);
454}
455
457 const uint32_t idx = ePropertyUseColor;
459 idx, g_debugger_properties[idx].default_uint_value != 0);
460}
461
463 const uint32_t idx = ePropertyUseColor;
464 bool ret = SetPropertyAtIndex(idx, b);
465
468 return ret;
469}
470
472 const uint32_t idx = ePropertyShowProgress;
474 idx, g_debugger_properties[idx].default_uint_value != 0);
475}
476
477bool Debugger::SetShowProgress(bool show_progress) {
478 const uint32_t idx = ePropertyShowProgress;
479 return SetPropertyAtIndex(idx, show_progress);
480}
481
482llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const {
483 const uint32_t idx = ePropertyShowProgressAnsiPrefix;
485 idx, g_debugger_properties[idx].default_cstr_value);
486}
487
488llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const {
489 const uint32_t idx = ePropertyShowProgressAnsiSuffix;
491 idx, g_debugger_properties[idx].default_cstr_value);
492}
493
495 const uint32_t idx = ePropertyShowStatusline;
497 idx, g_debugger_properties[idx].default_uint_value != 0);
498}
499
501 constexpr uint32_t idx = ePropertyStatuslineFormat;
503}
504
506 constexpr uint32_t idx = ePropertyStatuslineFormat;
507 bool ret = SetPropertyAtIndex(idx, format);
508 RedrawStatusline(std::nullopt);
509 return ret;
510}
511
512llvm::StringRef Debugger::GetSeparator() const {
513 constexpr uint32_t idx = ePropertySeparator;
515 idx, g_debugger_properties[idx].default_cstr_value);
516}
517
518llvm::StringRef Debugger::GetDisabledAnsiPrefix() const {
519 const uint32_t idx = ePropertyShowDisabledAnsiPrefix;
521 idx, g_debugger_properties[idx].default_cstr_value);
522}
523
524llvm::StringRef Debugger::GetDisabledAnsiSuffix() const {
525 const uint32_t idx = ePropertyShowDisabledAnsiSuffix;
527 idx, g_debugger_properties[idx].default_cstr_value);
528}
529
530bool Debugger::SetSeparator(llvm::StringRef s) {
531 constexpr uint32_t idx = ePropertySeparator;
532 bool ret = SetPropertyAtIndex(idx, s);
533 RedrawStatusline(std::nullopt);
534 return ret;
535}
536
538 const uint32_t idx = ePropertyShowAutosuggestion;
540 idx, g_debugger_properties[idx].default_uint_value != 0);
541}
542
544 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix;
546 idx, g_debugger_properties[idx].default_cstr_value);
547}
548
550 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix;
552 idx, g_debugger_properties[idx].default_cstr_value);
553}
554
555llvm::StringRef Debugger::GetRegexMatchAnsiPrefix() const {
556 const uint32_t idx = ePropertyShowRegexMatchAnsiPrefix;
558 idx, g_debugger_properties[idx].default_cstr_value);
559}
560
561llvm::StringRef Debugger::GetRegexMatchAnsiSuffix() const {
562 const uint32_t idx = ePropertyShowRegexMatchAnsiSuffix;
564 idx, g_debugger_properties[idx].default_cstr_value);
565}
566
568 const uint32_t idx = ePropertyShowDontUsePoHint;
570 idx, g_debugger_properties[idx].default_uint_value != 0);
571}
572
574 const uint32_t idx = ePropertyUseSourceCache;
576 idx, g_debugger_properties[idx].default_uint_value != 0);
577}
578
580 const uint32_t idx = ePropertyUseSourceCache;
581 bool ret = SetPropertyAtIndex(idx, b);
582 if (!ret) {
583 m_source_file_cache.Clear();
584 }
585 return ret;
586}
588 const uint32_t idx = ePropertyHighlightSource;
590 idx, g_debugger_properties[idx].default_uint_value != 0);
591}
592
594 const uint32_t idx = ePropertyStopShowColumn;
596 idx, static_cast<lldb::StopShowColumn>(
597 g_debugger_properties[idx].default_uint_value));
598}
599
601 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
603 idx, g_debugger_properties[idx].default_cstr_value);
604}
605
607 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
609 idx, g_debugger_properties[idx].default_cstr_value);
610}
611
613 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
615 idx, g_debugger_properties[idx].default_cstr_value);
616}
617
619 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
621 idx, g_debugger_properties[idx].default_cstr_value);
622}
623
624uint64_t Debugger::GetStopSourceLineCount(bool before) const {
625 const uint32_t idx =
626 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
628 idx, g_debugger_properties[idx].default_uint_value);
629}
630
632 const uint32_t idx = ePropertyStopDisassemblyDisplay;
634 idx, static_cast<lldb::StopDisassemblyType>(
635 g_debugger_properties[idx].default_uint_value));
636}
637
639 const uint32_t idx = ePropertyStopDisassemblyCount;
641 idx, g_debugger_properties[idx].default_uint_value);
642}
643
645 const uint32_t idx = ePropertyAutoOneLineSummaries;
647 idx, g_debugger_properties[idx].default_uint_value != 0);
648}
649
651 const uint32_t idx = ePropertyEscapeNonPrintables;
653 idx, g_debugger_properties[idx].default_uint_value != 0);
654}
655
657 const uint32_t idx = ePropertyAutoIndent;
659 idx, g_debugger_properties[idx].default_uint_value != 0);
660}
661
663 const uint32_t idx = ePropertyAutoIndent;
664 return SetPropertyAtIndex(idx, b);
665}
666
668 const uint32_t idx = ePropertyPrintDecls;
670 idx, g_debugger_properties[idx].default_uint_value != 0);
671}
672
674 const uint32_t idx = ePropertyPrintDecls;
675 return SetPropertyAtIndex(idx, b);
676}
677
678uint64_t Debugger::GetTabSize() const {
679 const uint32_t idx = ePropertyTabSize;
681 idx, g_debugger_properties[idx].default_uint_value);
682}
683
684bool Debugger::SetTabSize(uint64_t tab_size) {
685 const uint32_t idx = ePropertyTabSize;
686 return SetPropertyAtIndex(idx, tab_size);
687}
688
690 const uint32_t idx = ePropertyDWIMPrintVerbosity;
692 idx, static_cast<lldb::DWIMPrintVerbosity>(
693 g_debugger_properties[idx].default_uint_value != 0));
694}
695
697 const uint32_t idx = ePropertyShowInlineDiagnostics;
699 idx, g_debugger_properties[idx].default_uint_value);
700}
701
703 const uint32_t idx = ePropertyShowInlineDiagnostics;
704 return SetPropertyAtIndex(idx, b);
705}
706
707#pragma mark Debugger
708
709// const DebuggerPropertiesSP &
710// Debugger::GetSettings() const
711//{
712// return m_properties_sp;
713//}
714//
715
717 assert(g_debugger_list_ptr == nullptr &&
718 "Debugger::Initialize called more than once!");
719 g_debugger_list_mutex_ptr = new std::recursive_mutex();
721 g_thread_pool = new llvm::DefaultThreadPool(llvm::optimal_concurrency());
722 g_load_plugin_callback = load_plugin_callback;
723}
724
726 assert(g_debugger_list_ptr &&
727 "Debugger::Terminate called without a matching Debugger::Initialize!");
728
730 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
731 for (const auto &debugger : *g_debugger_list_ptr)
732 debugger->HandleDestroyCallback();
733 }
734
735 if (g_thread_pool) {
736 // The destructor will wait for all the threads to complete.
737 delete g_thread_pool;
738 }
739
741 // Clear our global list of debugger objects
742 {
743 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
744 for (const auto &debugger : *g_debugger_list_ptr)
745 debugger->Clear();
746 g_debugger_list_ptr->clear();
747 }
748 }
749}
750
752
754
757 llvm::sys::DynamicLibrary dynlib =
758 g_load_plugin_callback(shared_from_this(), spec, error);
759 if (dynlib.isValid()) {
760 m_loaded_plugins.push_back(dynlib);
761 return true;
762 }
763 } else {
764 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
765 // if the public API layer isn't available (code is linking against all of
766 // the internal LLDB static libraries), then we can't load plugins
767 error = Status::FromErrorString("Public API layer is not available");
768 }
769 return false;
770}
771
773LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
774 llvm::StringRef path) {
776
777 static constexpr llvm::StringLiteral g_dylibext(".dylib");
778 static constexpr llvm::StringLiteral g_solibext(".so");
779
780 if (!baton)
782
783 Debugger *debugger = (Debugger *)baton;
784
785 namespace fs = llvm::sys::fs;
786 // If we have a regular file, a symbolic link or unknown file type, try and
787 // process the file. We must handle unknown as sometimes the directory
788 // enumeration might be enumerating a file system that doesn't have correct
789 // file type information.
790 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
791 ft == fs::file_type::type_unknown) {
792 FileSpec plugin_file_spec(path);
793 FileSystem::Instance().Resolve(plugin_file_spec);
794
795 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
796 plugin_file_spec.GetFileNameExtension() != g_solibext) {
798 }
799
800 Status plugin_load_error;
801 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
802
804 } else if (ft == fs::file_type::directory_file ||
805 ft == fs::file_type::symlink_file ||
806 ft == fs::file_type::type_unknown) {
807 // Try and recurse into anything that a directory or symbolic link. We must
808 // also do this for unknown as sometimes the directory enumeration might be
809 // enumerating a file system that doesn't have correct file type
810 // information.
812 }
813
815}
816
818 const bool find_directories = true;
819 const bool find_files = true;
820 const bool find_other = true;
821 char dir_path[PATH_MAX];
822 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
823 if (FileSystem::Instance().Exists(dir_spec) &&
824 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
825 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
826 find_files, find_other,
827 LoadPluginCallback, this);
828 }
829 }
830
831 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
832 if (FileSystem::Instance().Exists(dir_spec) &&
833 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
834 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
835 find_files, find_other,
836 LoadPluginCallback, this);
837 }
838 }
839
841}
842
844 void *baton) {
847 helper([](lldb_private::telemetry::DebuggerInfo *entry) {
849 });
850 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
851 helper.SetDebugger(debugger_sp.get());
852
854 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
855 g_debugger_list_ptr->push_back(debugger_sp);
856 }
857 debugger_sp->InstanceInitialize();
858 return debugger_sp;
859}
860
866
868 const lldb::user_id_t user_id = GetID();
869 // Invoke and remove all the callbacks in an FIFO order. Callbacks which are
870 // added during this loop will be appended, invoked and then removed last.
871 // Callbacks which are removed during this loop will not be invoked.
872 while (true) {
873 DestroyCallbackInfo callback_info;
874 {
875 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
876 if (m_destroy_callbacks.empty())
877 break;
878 // Pop the first item in the list
879 callback_info = m_destroy_callbacks.front();
881 }
882 // Call the destroy callback with user id and baton
883 callback_info.callback(user_id, callback_info.baton);
884 }
885}
886
887void Debugger::Destroy(DebuggerSP &debugger_sp) {
888 if (!debugger_sp)
889 return;
890
891 debugger_sp->HandleDestroyCallback();
892 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
893
894 if (cmd_interpreter.GetSaveSessionOnQuit()) {
895 CommandReturnObject result(debugger_sp->GetUseColor());
896 cmd_interpreter.SaveTranscript(result);
897 if (result.Succeeded())
898 (*debugger_sp->GetAsyncOutputStream())
899 << result.GetOutputString() << '\n';
900 else
901 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorString() << '\n';
902 }
903
904 debugger_sp->Clear();
905
907 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
908 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
909 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
910 if ((*pos).get() == debugger_sp.get()) {
911 g_debugger_list_ptr->erase(pos);
912 return;
913 }
914 }
915 }
916}
917
919Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) {
921 return DebuggerSP();
922
923 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
924 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) {
925 if (!debugger_sp)
926 continue;
927
928 if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name)
929 return debugger_sp;
930 }
931 return DebuggerSP();
932}
933
935 TargetSP target_sp;
937 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
938 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
939 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
940 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
941 if (target_sp)
942 break;
943 }
944 }
945 return target_sp;
946}
947
949 TargetSP target_sp;
951 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
952 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
953 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
954 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
955 if (target_sp)
956 break;
957 }
958 }
959 return target_sp;
960}
961
963 static constexpr llvm::StringLiteral class_name("lldb.debugger");
964 return class_name;
965}
966
968 : UserID(g_unique_id++),
969 Properties(std::make_shared<OptionValueProperties>()),
970 m_input_file_sp(std::make_shared<NativeFile>(
971 stdin, File::eOpenOptionReadOnly, NativeFile::Unowned)),
972 m_output_stream_sp(std::make_shared<LockableStreamFile>(
973 stdout, NativeFile::Unowned, m_output_mutex)),
974 m_error_stream_sp(std::make_shared<LockableStreamFile>(
975 stderr, NativeFile::Unowned, m_output_mutex)),
976 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
978 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
981 std::make_unique<CommandInterpreter>(*this, false)),
983 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()),
985 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
989 // Initialize the debugger properties as early as possible as other parts of
990 // LLDB will start querying them during construction.
991 m_collection_sp->Initialize(g_debugger_properties);
992 m_collection_sp->AppendProperty(
993 "target", "Settings specify to debugging targets.", true,
995 m_collection_sp->AppendProperty(
996 "platform", "Platform settings.", true,
998 m_collection_sp->AppendProperty(
999 "symbols", "Symbol lookup and cache settings.", true,
1001 m_collection_sp->AppendProperty(
1002 LanguageProperties::GetSettingName(), "Language settings.", true,
1005 m_collection_sp->AppendProperty(
1006 "interpreter",
1007 "Settings specify to the debugger's command interpreter.", true,
1008 m_command_interpreter_up->GetValueProperties());
1009 }
1010 if (log_callback)
1012 std::make_shared<CallbackLogHandler>(log_callback, baton);
1013 m_command_interpreter_up->Initialize();
1014 // Always add our default platform to the platform list
1015 PlatformSP default_platform_sp(Platform::GetHostPlatform());
1016 assert(default_platform_sp);
1017 m_platform_list.Append(default_platform_sp, true);
1018
1019 // Create the dummy target.
1020 {
1022 if (!arch.IsValid())
1023 arch = HostInfo::GetArchitecture();
1024 assert(arch.IsValid() && "No valid default or host archspec");
1025 const bool is_dummy_target = true;
1026 m_dummy_target_sp.reset(
1027 new Target(*this, arch, default_platform_sp, is_dummy_target));
1028 }
1029 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
1030
1031 OptionValueUInt64 *term_width =
1032 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1033 ePropertyTerminalWidth);
1034 term_width->SetMinimumValue(10);
1035
1036 OptionValueUInt64 *term_height =
1037 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(
1038 ePropertyTerminalHeight);
1039 term_height->SetMinimumValue(10);
1040
1041 // Turn off use-color if this is a dumb terminal.
1042 const char *term = getenv("TERM");
1043 auto disable_color = [&]() {
1044 SetUseColor(false);
1045 SetSeparator("| ");
1046 };
1047
1048 if (term && !strcmp(term, "dumb"))
1049 disable_color();
1050 // Turn off use-color if we don't write to a terminal with color support.
1051 if (!GetOutputFileSP()->GetIsTerminalWithColors())
1052 disable_color();
1053
1054 if (Diagnostics::Enabled()) {
1056 [this](const FileSpec &dir) -> llvm::Error {
1057 for (auto &entry : m_stream_handlers) {
1058 llvm::StringRef log_path = entry.first();
1059 llvm::StringRef file_name = llvm::sys::path::filename(log_path);
1060 FileSpec destination = dir.CopyByAppendingPathComponent(file_name);
1061 std::error_code ec =
1062 llvm::sys::fs::copy_file(log_path, destination.GetPath());
1063 if (ec)
1064 return llvm::errorCodeToError(ec);
1065 }
1066 return llvm::Error::success();
1067 });
1068 }
1069
1070#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
1071 // Enabling use of ANSI color codes because LLDB is using them to highlight
1072 // text.
1073 llvm::sys::Process::UseANSIEscapeCodes(true);
1074#endif
1075}
1076
1078
1080 // Make sure we call this function only once. With the C++ global destructor
1081 // chain having a list of debuggers and with code that can be running on
1082 // other threads, we need to ensure this doesn't happen multiple times.
1083 //
1084 // The following functions call Debugger::Clear():
1085 // Debugger::~Debugger();
1086 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
1087 // static void Debugger::Terminate();
1088 llvm::call_once(m_clear_once, [this]() {
1091 assert(this == info->debugger);
1092 (void)this;
1093 info->is_exit_entry = true;
1094 },
1095 this);
1099 m_listener_sp->Clear();
1100 for (TargetSP target_sp : m_target_list.Targets()) {
1101 if (target_sp) {
1102 if (ProcessSP process_sp = target_sp->GetProcessSP())
1103 process_sp->Finalize(false /* not destructing */);
1104 target_sp->Destroy();
1105 }
1106 }
1107 m_broadcaster_manager_sp->Clear();
1108
1109 // Close the input file _before_ we close the input read communications
1110 // class as it does NOT own the input file, our m_input_file does.
1111 m_terminal_state.Clear();
1112 GetInputFile().Close();
1113
1114 m_command_interpreter_up->Clear();
1115
1118 });
1119}
1120
1122 return !m_command_interpreter_up->GetSynchronous();
1123}
1124
1125void Debugger::SetAsyncExecution(bool async_execution) {
1126 m_command_interpreter_up->SetSynchronous(!async_execution);
1127}
1128
1129static inline int OpenPipe(int fds[2], std::size_t size) {
1130#ifdef _WIN32
1131 return _pipe(fds, size, O_BINARY);
1132#else
1133 (void)size;
1134 return pipe(fds);
1135#endif
1136}
1137
1139 Status result;
1140 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
1141 int fds[2] = {-1, -1};
1142
1143 if (data == nullptr) {
1144 result = Status::FromErrorString("String data is null");
1145 return result;
1146 }
1147
1148 size_t size = strlen(data);
1149 if (size == 0) {
1150 result = Status::FromErrorString("String data is empty");
1151 return result;
1152 }
1153
1154 if (OpenPipe(fds, size) != 0) {
1155 result = Status::FromErrorString(
1156 "can't create pipe file descriptors for LLDB commands");
1157 return result;
1158 }
1159
1160 int r = write(fds[WRITE], data, size);
1161 (void)r;
1162 // Close the write end of the pipe, so that the command interpreter will exit
1163 // when it consumes all the data.
1164 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
1165
1166 // Open the read file descriptor as a FILE * that we can return as an input
1167 // handle.
1168 FILE *commands_file = fdopen(fds[READ], "rb");
1169 if (commands_file == nullptr) {
1171 "fdopen(%i, \"rb\") failed (errno = %i) "
1172 "when trying to open LLDB commands pipe",
1173 fds[READ], errno);
1174 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
1175 return result;
1176 }
1177
1178 SetInputFile((FileSP)std::make_shared<NativeFile>(
1179 commands_file, File::eOpenOptionReadOnly, true));
1180 return result;
1181}
1182
1184 assert(file_sp && file_sp->IsValid());
1185 m_input_file_sp = std::move(file_sp);
1186 // Save away the terminal state if that is relevant, so that we can restore
1187 // it in RestoreInputState.
1189}
1190
1192 assert(file_sp && file_sp->IsValid());
1194 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1195}
1196
1198 assert(file_sp && file_sp->IsValid());
1200 std::make_shared<LockableStreamFile>(file_sp, m_output_mutex);
1201}
1202
1204 {
1205 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1206 if (m_statusline)
1207 m_statusline->Disable();
1208 }
1209 int fd = GetInputFile().GetDescriptor();
1210 if (fd != File::kInvalidDescriptor)
1211 m_terminal_state.Save(fd, true);
1212}
1213
1215 m_terminal_state.Restore();
1216 {
1217 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1218 if (m_statusline)
1220 }
1221}
1222
1224 std::optional<ExecutionContextRef> exe_ctx_ref) {
1225 std::lock_guard<std::mutex> guard(m_statusline_mutex);
1226
1227 if (!m_statusline)
1228 return;
1229
1230 m_statusline->Redraw(exe_ctx_ref);
1231}
1232
1234 bool adopt_selected = true;
1235 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected);
1236 return ExecutionContext(exe_ctx_ref);
1237}
1238
1240 if (TargetSP selected_target_sp = GetSelectedTarget())
1241 return ExecutionContextRef(selected_target_sp.get(),
1242 /*adopt_selected=*/true);
1243 return ExecutionContextRef(m_dummy_target_sp.get(), /*adopt_selected=*/false);
1244}
1245
1247 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1248 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1249 if (reader_sp)
1250 reader_sp->Interrupt();
1251}
1252
1254 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1255 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1256 if (reader_sp)
1257 reader_sp->GotEOF();
1258}
1259
1261 // The bottom input reader should be the main debugger input reader. We do
1262 // not want to close that one here.
1263 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1264 while (m_io_handler_stack.GetSize() > 1) {
1265 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1266 if (reader_sp)
1267 PopIOHandler(reader_sp);
1268 }
1269}
1270
1272 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1273 while (true) {
1274 if (!reader_sp)
1275 break;
1276
1277 reader_sp->Run();
1278 {
1279 std::lock_guard<std::recursive_mutex> guard(
1281
1282 // Remove all input readers that are done from the top of the stack
1283 while (true) {
1284 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1285 if (top_reader_sp && top_reader_sp->GetIsDone())
1286 PopIOHandler(top_reader_sp);
1287 else
1288 break;
1289 }
1290 reader_sp = m_io_handler_stack.Top();
1291 }
1292 }
1294}
1295
1297 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1298
1299 PushIOHandler(reader_sp);
1300 IOHandlerSP top_reader_sp = reader_sp;
1301
1302 while (top_reader_sp) {
1303 top_reader_sp->Run();
1304
1305 // Don't unwind past the starting point.
1306 if (top_reader_sp.get() == reader_sp.get()) {
1307 if (PopIOHandler(reader_sp))
1308 break;
1309 }
1310
1311 // If we pushed new IO handlers, pop them if they're done or restart the
1312 // loop to run them if they're not.
1313 while (true) {
1314 top_reader_sp = m_io_handler_stack.Top();
1315 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1316 PopIOHandler(top_reader_sp);
1317 // Don't unwind past the starting point.
1318 if (top_reader_sp.get() == reader_sp.get())
1319 return;
1320 } else {
1321 break;
1322 }
1323 }
1324 }
1325}
1326
1328 return m_io_handler_stack.IsTop(reader_sp);
1329}
1330
1332 IOHandler::Type second_top_type) {
1333 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1334}
1335
1336void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1337 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1338 if (!printed) {
1339 LockableStreamFileSP stream_sp =
1341 LockedStreamFile locked_stream = stream_sp->Lock();
1342 locked_stream.Write(s, len);
1343 }
1344}
1345
1347 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1348}
1349
1351 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1352}
1353
1355 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1356}
1357
1359 return PopIOHandler(reader_sp);
1360}
1361
1363 bool cancel_top_handler) {
1364 PushIOHandler(reader_sp, cancel_top_handler);
1365}
1366
1369 LockableStreamFileSP &err) {
1370 // Before an IOHandler runs, it must have in/out/err streams. This function
1371 // is called when one ore more of the streams are nullptr. We use the top
1372 // input reader's in/out/err streams, or fall back to the debugger file
1373 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1374
1375 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1376 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1377 // If no STDIN has been set, then set it appropriately
1378 if (!in || !in->IsValid()) {
1379 if (top_reader_sp)
1380 in = top_reader_sp->GetInputFileSP();
1381 else
1382 in = GetInputFileSP();
1383 // If there is nothing, use stdin
1384 if (!in)
1385 in = std::make_shared<NativeFile>(stdin, File::eOpenOptionReadOnly,
1387 }
1388 // If no STDOUT has been set, then set it appropriately
1389 if (!out || !out->GetUnlockedFile().IsValid()) {
1390 if (top_reader_sp)
1391 out = top_reader_sp->GetOutputStreamFileSP();
1392 else
1393 out = GetOutputStreamSP();
1394 // If there is nothing, use stdout
1395 if (!out)
1396 out = std::make_shared<LockableStreamFile>(stdout, NativeFile::Unowned,
1398 }
1399 // If no STDERR has been set, then set it appropriately
1400 if (!err || !err->GetUnlockedFile().IsValid()) {
1401 if (top_reader_sp)
1402 err = top_reader_sp->GetErrorStreamFileSP();
1403 else
1404 err = GetErrorStreamSP();
1405 // If there is nothing, use stderr
1406 if (!err)
1407 err = std::make_shared<LockableStreamFile>(stderr, NativeFile::Unowned,
1409 }
1410}
1411
1413 bool cancel_top_handler) {
1414 if (!reader_sp)
1415 return;
1416
1417 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1418
1419 // Get the current top input reader...
1420 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1421
1422 // Don't push the same IO handler twice...
1423 if (reader_sp == top_reader_sp)
1424 return;
1425
1426 // Push our new input reader
1427 m_io_handler_stack.Push(reader_sp);
1428 reader_sp->Activate();
1429
1430 // Interrupt the top input reader to it will exit its Run() function and let
1431 // this new input reader take over
1432 if (top_reader_sp) {
1433 top_reader_sp->Deactivate();
1434 if (cancel_top_handler)
1435 top_reader_sp->Cancel();
1436 }
1437}
1438
1439bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1440 if (!pop_reader_sp)
1441 return false;
1442
1443 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1444
1445 // The reader on the stop of the stack is done, so let the next read on the
1446 // stack refresh its prompt and if there is one...
1447 if (m_io_handler_stack.IsEmpty())
1448 return false;
1449
1450 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1451
1452 if (pop_reader_sp != reader_sp)
1453 return false;
1454
1455 reader_sp->Deactivate();
1456 reader_sp->Cancel();
1457 m_io_handler_stack.Pop();
1458
1459 reader_sp = m_io_handler_stack.Top();
1460 if (reader_sp)
1461 reader_sp->Activate();
1462
1463 return true;
1464}
1465
1467 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1468 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1469 if (reader_sp)
1470 reader_sp->Refresh();
1471}
1472
1474 return std::make_unique<StreamAsynchronousIO>(*this,
1476}
1477
1479 return std::make_unique<StreamAsynchronousIO>(*this,
1481}
1482
1484 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1486}
1487
1489 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1490 if (m_interrupt_requested > 0)
1492}
1493
1495 // This is the one we should call internally. This will return true either
1496 // if there's a debugger interrupt and we aren't on the IOHandler thread,
1497 // or if we are on the IOHandler thread and there's a CommandInterpreter
1498 // interrupt.
1500 std::lock_guard<std::mutex> guard(m_interrupt_mutex);
1501 return m_interrupt_requested != 0;
1502 }
1504}
1505
1507 std::string function_name, const llvm::formatv_object_base &payload)
1508 : m_function_name(std::move(function_name)),
1509 m_interrupt_time(std::chrono::system_clock::now()),
1510 m_thread_id(llvm::get_threadid()) {
1511 llvm::raw_string_ostream desc(m_description);
1512 desc << payload << "\n";
1513}
1514
1516 // For now, just log the description:
1517 Log *log = GetLog(LLDBLog::Host);
1518 LLDB_LOG(log, "Interruption: {0}", report.m_description);
1519}
1520
1522 DebuggerList result;
1524 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1525 for (auto debugger_sp : *g_debugger_list_ptr) {
1526 if (debugger_sp->InterruptRequested())
1527 result.push_back(debugger_sp);
1528 }
1529 }
1530 return result;
1531}
1532
1535 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1536 return g_debugger_list_ptr->size();
1537 }
1538 return 0;
1539}
1540
1542 DebuggerSP debugger_sp;
1543
1545 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1546 if (index < g_debugger_list_ptr->size())
1547 debugger_sp = g_debugger_list_ptr->at(index);
1548 }
1549
1550 return debugger_sp;
1551}
1552
1554 DebuggerSP debugger_sp;
1555
1557 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1558 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1559 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1560 if ((*pos)->GetID() == id) {
1561 debugger_sp = *pos;
1562 break;
1563 }
1564 }
1565 }
1566 return debugger_sp;
1567}
1568
1570 const SymbolContext *sc,
1571 const SymbolContext *prev_sc,
1572 const ExecutionContext *exe_ctx,
1573 const Address *addr, Stream &s) {
1574 FormatEntity::Entry format_entry;
1575
1576 if (format == nullptr) {
1577 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) {
1578 format_entry =
1580 format = &format_entry;
1581 }
1582 if (format == nullptr) {
1583 FormatEntity::Parse("${addr}: ", format_entry);
1584 format = &format_entry;
1585 }
1586 }
1587 bool function_changed = false;
1588 bool initial_function = false;
1589 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1590 if (sc && (sc->function || sc->symbol)) {
1591 if (prev_sc->symbol && sc->symbol) {
1592 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1593 prev_sc->symbol->GetType())) {
1594 function_changed = true;
1595 }
1596 } else if (prev_sc->function && sc->function) {
1597 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1598 function_changed = true;
1599 }
1600 }
1601 }
1602 }
1603 // The first context on a list of instructions will have a prev_sc that has
1604 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1605 // would return false. But we do get a prev_sc pointer.
1606 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1607 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1608 initial_function = true;
1609 }
1610 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1611 function_changed, initial_function);
1612}
1613
1614void Debugger::AssertCallback(llvm::StringRef message,
1615 llvm::StringRef backtrace,
1616 llvm::StringRef prompt) {
1617 Debugger::ReportError(llvm::formatv("{0}\n{1}{2}\n{3}", message, backtrace,
1618 GetVersion(), prompt)
1619 .str());
1620}
1621
1623 void *baton) {
1624 // For simplicity's sake, I am not going to deal with how to close down any
1625 // open logging streams, I just redirect everything from here on out to the
1626 // callback.
1628 std::make_shared<CallbackLogHandler>(log_callback, baton);
1629}
1630
1632 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1633 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1634 m_destroy_callbacks.clear();
1636 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1637}
1638
1640 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) {
1641 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1643 m_destroy_callbacks.emplace_back(token, destroy_callback, baton);
1644 return token;
1645}
1646
1648 std::lock_guard<std::mutex> guard(m_destroy_callback_mutex);
1649 for (auto it = m_destroy_callbacks.begin(); it != m_destroy_callbacks.end();
1650 ++it) {
1651 if (it->token == token) {
1652 m_destroy_callbacks.erase(it);
1653 return true;
1654 }
1655 }
1656 return false;
1657}
1658
1659static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1660 std::string title, std::string details,
1661 uint64_t completed, uint64_t total,
1662 bool is_debugger_specific,
1663 uint32_t progress_broadcast_bit) {
1664 // Only deliver progress events if we have any progress listeners.
1665 if (!debugger.GetBroadcaster().EventTypeHasListeners(progress_broadcast_bit))
1666 return;
1667
1668 EventSP event_sp(new Event(
1669 progress_broadcast_bit,
1670 new ProgressEventData(progress_id, std::move(title), std::move(details),
1671 completed, total, is_debugger_specific)));
1672 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1673}
1674
1675void Debugger::ReportProgress(uint64_t progress_id, std::string title,
1676 std::string details, uint64_t completed,
1677 uint64_t total,
1678 std::optional<lldb::user_id_t> debugger_id,
1679 uint32_t progress_broadcast_bit) {
1680 // Check if this progress is for a specific debugger.
1681 if (debugger_id) {
1682 // It is debugger specific, grab it and deliver the event if the debugger
1683 // still exists.
1684 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1685 if (debugger_sp)
1686 PrivateReportProgress(*debugger_sp, progress_id, std::move(title),
1687 std::move(details), completed, total,
1688 /*is_debugger_specific*/ true,
1689 progress_broadcast_bit);
1690 return;
1691 }
1692 // The progress event is not debugger specific, iterate over all debuggers
1693 // and deliver a progress event to each one.
1695 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1696 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1697 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1698 PrivateReportProgress(*(*pos), progress_id, title, details, completed,
1699 total, /*is_debugger_specific*/ false,
1700 progress_broadcast_bit);
1701 }
1702}
1703
1704static void PrivateReportDiagnostic(Debugger &debugger, Severity severity,
1705 std::string message,
1706 bool debugger_specific) {
1707 uint32_t event_type = 0;
1708 switch (severity) {
1709 case eSeverityInfo:
1710 assert(false && "eSeverityInfo should not be broadcast");
1711 return;
1712 case eSeverityWarning:
1713 event_type = lldb::eBroadcastBitWarning;
1714 break;
1715 case eSeverityError:
1716 event_type = lldb::eBroadcastBitError;
1717 break;
1718 }
1719
1720 Broadcaster &broadcaster = debugger.GetBroadcaster();
1721 if (!broadcaster.EventTypeHasListeners(event_type)) {
1722 // Diagnostics are too important to drop. If nobody is listening, print the
1723 // diagnostic directly to the debugger's error stream.
1724 DiagnosticEventData event_data(severity, std::move(message),
1725 debugger_specific);
1726 event_data.Dump(debugger.GetAsyncErrorStream().get());
1727 return;
1728 }
1729 EventSP event_sp = std::make_shared<Event>(
1730 event_type,
1731 new DiagnosticEventData(severity, std::move(message), debugger_specific));
1732 broadcaster.BroadcastEvent(event_sp);
1733}
1734
1735void Debugger::ReportDiagnosticImpl(Severity severity, std::string message,
1736 std::optional<lldb::user_id_t> debugger_id,
1737 std::once_flag *once) {
1738 auto ReportDiagnosticLambda = [&]() {
1739 // Always log diagnostics to the system log.
1740 Host::SystemLog(severity, message);
1741
1742 // The diagnostic subsystem is optional but we still want to broadcast
1743 // events when it's disabled.
1745 Diagnostics::Instance().Report(message);
1746
1747 // We don't broadcast info events.
1748 if (severity == lldb::eSeverityInfo)
1749 return;
1750
1751 // Check if this diagnostic is for a specific debugger.
1752 if (debugger_id) {
1753 // It is debugger specific, grab it and deliver the event if the debugger
1754 // still exists.
1755 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1756 if (debugger_sp)
1757 PrivateReportDiagnostic(*debugger_sp, severity, std::move(message),
1758 true);
1759 return;
1760 }
1761 // The diagnostic event is not debugger specific, iterate over all debuggers
1762 // and deliver a diagnostic event to each one.
1764 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1765 for (const auto &debugger : *g_debugger_list_ptr)
1766 PrivateReportDiagnostic(*debugger, severity, message, false);
1767 }
1768 };
1769
1770 if (once)
1771 std::call_once(*once, ReportDiagnosticLambda);
1772 else
1773 ReportDiagnosticLambda();
1774}
1775
1776void Debugger::ReportWarning(std::string message,
1777 std::optional<lldb::user_id_t> debugger_id,
1778 std::once_flag *once) {
1779 ReportDiagnosticImpl(eSeverityWarning, std::move(message), debugger_id, once);
1780}
1781
1782void Debugger::ReportError(std::string message,
1783 std::optional<lldb::user_id_t> debugger_id,
1784 std::once_flag *once) {
1785 ReportDiagnosticImpl(eSeverityError, std::move(message), debugger_id, once);
1786}
1787
1788void Debugger::ReportInfo(std::string message,
1789 std::optional<lldb::user_id_t> debugger_id,
1790 std::once_flag *once) {
1791 ReportDiagnosticImpl(eSeverityInfo, std::move(message), debugger_id, once);
1792}
1793
1796 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1797 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1798 EventSP event_sp = std::make_shared<Event>(
1800 new SymbolChangeEventData(debugger_sp, module_spec));
1801 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1802 }
1803 }
1804}
1805
1806static std::shared_ptr<LogHandler>
1807CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1808 size_t buffer_size) {
1809 switch (log_handler_kind) {
1810 case eLogHandlerStream:
1811 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1813 return std::make_shared<RotatingLogHandler>(buffer_size);
1814 case eLogHandlerSystem:
1815 return std::make_shared<SystemLogHandler>();
1817 return {};
1818 }
1819 return {};
1820}
1821
1822bool Debugger::EnableLog(llvm::StringRef channel,
1823 llvm::ArrayRef<const char *> categories,
1824 llvm::StringRef log_file, uint32_t log_options,
1825 size_t buffer_size, LogHandlerKind log_handler_kind,
1826 llvm::raw_ostream &error_stream) {
1827
1828 std::shared_ptr<LogHandler> log_handler_sp;
1830 log_handler_sp = m_callback_handler_sp;
1831 // For now when using the callback mode you always get thread & timestamp.
1832 log_options |=
1834 } else if (log_file.empty()) {
1835 log_handler_sp =
1836 CreateLogHandler(log_handler_kind, GetOutputFileSP()->GetDescriptor(),
1837 /*should_close=*/false, buffer_size);
1838 } else {
1839 auto pos = m_stream_handlers.find(log_file);
1840 if (pos != m_stream_handlers.end())
1841 log_handler_sp = pos->second.lock();
1842 if (!log_handler_sp) {
1843 File::OpenOptions flags =
1845 if (log_options & LLDB_LOG_OPTION_APPEND)
1846 flags |= File::eOpenOptionAppend;
1847 else
1849 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1850 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1851 if (!file) {
1852 error_stream << "Unable to open log file '" << log_file
1853 << "': " << llvm::toString(file.takeError()) << "\n";
1854 return false;
1855 }
1856
1857 log_handler_sp =
1858 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1859 /*should_close=*/true, buffer_size);
1860 m_stream_handlers[log_file] = log_handler_sp;
1861 }
1862 }
1863 assert(log_handler_sp);
1864
1865 if (log_options == 0)
1867
1868 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories,
1869 error_stream);
1870}
1871
1874 std::optional<lldb::ScriptLanguage> language) {
1875 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1876 lldb::ScriptLanguage script_language =
1877 language ? *language : GetScriptLanguage();
1878
1879 if (!m_script_interpreters[script_language]) {
1880 if (!can_create)
1881 return nullptr;
1882 m_script_interpreters[script_language] =
1883 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1884 }
1885
1886 return m_script_interpreters[script_language].get();
1887}
1888
1891 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1892 return *m_source_manager_up;
1893}
1894
1895// This function handles events that were broadcast by the process.
1897 using namespace lldb;
1898 const uint32_t event_type =
1900 event_sp);
1901
1902 // if (event_type & eBreakpointEventTypeAdded
1903 // || event_type & eBreakpointEventTypeRemoved
1904 // || event_type & eBreakpointEventTypeEnabled
1905 // || event_type & eBreakpointEventTypeDisabled
1906 // || event_type & eBreakpointEventTypeCommandChanged
1907 // || event_type & eBreakpointEventTypeConditionChanged
1908 // || event_type & eBreakpointEventTypeIgnoreChanged
1909 // || event_type & eBreakpointEventTypeLocationsResolved)
1910 // {
1911 // // Don't do anything about these events, since the breakpoint
1912 // commands already echo these actions.
1913 // }
1914 //
1915 if (event_type & eBreakpointEventTypeLocationsAdded) {
1916 uint32_t num_new_locations =
1918 event_sp);
1919 if (num_new_locations > 0) {
1920 BreakpointSP breakpoint =
1922 if (StreamUP output_up = GetAsyncOutputStream()) {
1923 output_up->Printf("%d location%s added to breakpoint %d\n",
1924 num_new_locations, num_new_locations == 1 ? "" : "s",
1925 breakpoint->GetID());
1926 output_up->Flush();
1927 }
1928 }
1929 }
1930 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1931 // {
1932 // // These locations just get disabled, not sure it is worth spamming
1933 // folks about this on the command line.
1934 // }
1935 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1936 // {
1937 // // This might be an interesting thing to note, but I'm going to
1938 // leave it quiet for now, it just looked noisy.
1939 // }
1940}
1941
1942void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1943 bool flush_stderr) {
1944 const auto &flush = [&](Stream &stream,
1945 size_t (Process::*get)(char *, size_t, Status &)) {
1946 Status error;
1947 size_t len;
1948 char buffer[1024];
1949 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1950 stream.Write(buffer, len);
1951 stream.Flush();
1952 };
1953
1954 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1955 if (flush_stdout)
1957 if (flush_stderr)
1959}
1960
1961// This function handles events that were broadcast by the process.
1963 const uint32_t event_type = event_sp->GetType();
1964 ProcessSP process_sp =
1968
1969 StreamUP output_stream_up = GetAsyncOutputStream();
1970 StreamUP error_stream_up = GetAsyncErrorStream();
1971 const bool gui_enabled = IsForwardingEvents();
1972
1973 if (!gui_enabled) {
1974 bool pop_process_io_handler = false;
1975 assert(process_sp);
1976
1977 bool state_is_stopped = false;
1978 const bool got_state_changed =
1979 (event_type & Process::eBroadcastBitStateChanged) != 0;
1980 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1981 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1982 const bool got_structured_data =
1983 (event_type & Process::eBroadcastBitStructuredData) != 0;
1984
1985 if (got_state_changed) {
1986 StateType event_state =
1988 state_is_stopped = StateIsStoppedState(event_state, false);
1989 }
1990
1991 // Display running state changes first before any STDIO
1992 if (got_state_changed && !state_is_stopped) {
1993 // This is a public stop which we are going to announce to the user, so
1994 // we should force the most relevant frame selection here.
1995 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
1997 pop_process_io_handler);
1998 }
1999
2000 // Now display STDOUT and STDERR
2001 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
2002 got_stderr || got_state_changed);
2003
2004 // Give structured data events an opportunity to display.
2005 if (got_structured_data) {
2006 StructuredDataPluginSP plugin_sp =
2008 if (plugin_sp) {
2009 auto structured_data_sp =
2011 StreamString content_stream;
2012 Status error =
2013 plugin_sp->GetDescription(structured_data_sp, content_stream);
2014 if (error.Success()) {
2015 if (!content_stream.GetString().empty()) {
2016 // Add newline.
2017 content_stream.PutChar('\n');
2018 content_stream.Flush();
2019
2020 // Print it.
2021 output_stream_up->PutCString(content_stream.GetString());
2022 }
2023 } else {
2024 error_stream_up->Format("Failed to print structured "
2025 "data with plugin {0}: {1}",
2026 plugin_sp->GetPluginName(), error);
2027 }
2028 }
2029 }
2030
2031 // Now display any stopped state changes after any STDIO
2032 if (got_state_changed && state_is_stopped) {
2033 Process::HandleProcessStateChangedEvent(event_sp, output_stream_up.get(),
2035 pop_process_io_handler);
2036 }
2037
2038 output_stream_up->Flush();
2039 error_stream_up->Flush();
2040
2041 if (pop_process_io_handler)
2042 process_sp->PopProcessIOHandler();
2043 }
2044 return process_sp;
2045}
2046
2048 // At present the only thread event we handle is the Frame Changed event, and
2049 // all we do for that is just reprint the thread status for that thread.
2050 const uint32_t event_type = event_sp->GetType();
2051 const bool stop_format = true;
2052 ThreadSP thread_sp;
2053 if (event_type == Thread::eBroadcastBitStackChanged ||
2055 thread_sp = Thread::ThreadEventData::GetThreadFromEvent(event_sp.get());
2056 if (thread_sp) {
2057 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format,
2058 /*show_hidden*/ true);
2059 }
2060 }
2061 return thread_sp;
2062}
2063
2065
2067 m_forward_listener_sp = listener_sp;
2068}
2069
2071 m_forward_listener_sp.reset();
2072}
2073
2076 File &file = stream_sp->GetUnlockedFile();
2077 return file.GetIsInteractive() && file.GetIsRealTerminal() &&
2079 }
2080 return false;
2081}
2082
2084// We have trouble with the contol codes on Windows, see
2085// https://github.com/llvm/llvm-project/issues/134846.
2086#ifndef _WIN32
2088#else
2089 return false;
2090#endif
2091}
2092
2093static bool RequiresFollowChildWorkaround(const Process &process) {
2094 // FIXME: https://github.com/llvm/llvm-project/issues/160216
2095 return process.GetFollowForkMode() == eFollowChild;
2096}
2097
2099 ListenerSP listener_sp(GetListener());
2100 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
2101 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
2102 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
2103 BroadcastEventSpec target_event_spec(broadcaster_class_target,
2105
2106 BroadcastEventSpec process_event_spec(
2107 broadcaster_class_process,
2110
2111 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
2114
2115 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2116 target_event_spec);
2117 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2118 process_event_spec);
2119 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
2120 thread_event_spec);
2121 listener_sp->StartListeningForEvents(
2126
2127 listener_sp->StartListeningForEvents(
2132
2133 // Let the thread that spawned us know that we have started up and that we
2134 // are now listening to all required events so no events get missed
2136
2137 if (StatuslineSupported()) {
2138 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2139 if (!m_statusline) {
2140 m_statusline.emplace(*this);
2142 }
2143 }
2144
2145 bool done = false;
2146 while (!done) {
2147 EventSP event_sp;
2148 if (listener_sp->GetEvent(event_sp, std::nullopt)) {
2149 std::optional<ExecutionContextRef> exe_ctx_ref = std::nullopt;
2150 if (event_sp) {
2151 Broadcaster *broadcaster = event_sp->GetBroadcaster();
2152 if (broadcaster) {
2153 uint32_t event_type = event_sp->GetType();
2154 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
2155 if (broadcaster_class == broadcaster_class_process) {
2156 if (ProcessSP process_sp = HandleProcessEvent(event_sp))
2157 if (!RequiresFollowChildWorkaround(*process_sp))
2158 exe_ctx_ref = ExecutionContextRef(process_sp.get(),
2159 /*adopt_selected=*/true);
2160 } else if (broadcaster_class == broadcaster_class_target) {
2162 event_sp.get())) {
2163 HandleBreakpointEvent(event_sp);
2164 }
2165 } else if (broadcaster_class == broadcaster_class_thread) {
2166 if (ThreadSP thread_sp = HandleThreadEvent(event_sp))
2167 if (!RequiresFollowChildWorkaround(*thread_sp->GetProcess()))
2168 exe_ctx_ref = ExecutionContextRef(thread_sp.get(),
2169 /*adopt_selected=*/true);
2170 } else if (broadcaster == m_command_interpreter_up.get()) {
2171 if (event_type &
2173 done = true;
2174 } else if (event_type &
2176 const char *data = static_cast<const char *>(
2177 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2178 if (data && data[0]) {
2179 StreamUP error_up = GetAsyncErrorStream();
2180 error_up->PutCString(data);
2181 error_up->Flush();
2182 }
2183 } else if (event_type & CommandInterpreter::
2184 eBroadcastBitAsynchronousOutputData) {
2185 const char *data = static_cast<const char *>(
2186 EventDataBytes::GetBytesFromEvent(event_sp.get()));
2187 if (data && data[0]) {
2188 StreamUP output_up = GetAsyncOutputStream();
2189 output_up->PutCString(data);
2190 output_up->Flush();
2191 }
2192 }
2193 } else if (broadcaster == &m_broadcaster) {
2194 if (event_type & lldb::eBroadcastBitProgress ||
2196 HandleProgressEvent(event_sp);
2197 else if (event_type & lldb::eBroadcastBitWarning)
2198 HandleDiagnosticEvent(event_sp);
2199 else if (event_type & lldb::eBroadcastBitError)
2200 HandleDiagnosticEvent(event_sp);
2201 }
2202 }
2203
2205 m_forward_listener_sp->AddEvent(event_sp);
2206 }
2207 RedrawStatusline(exe_ctx_ref);
2208 }
2209 }
2210
2211 {
2212 std::lock_guard<std::mutex> guard(m_statusline_mutex);
2213 if (m_statusline)
2214 m_statusline.reset();
2215 }
2216
2217 return {};
2218}
2219
2221 if (!m_event_handler_thread.IsJoinable()) {
2222 // We must synchronize with the DefaultEventHandler() thread to ensure it
2223 // is up and running and listening to events before we return from this
2224 // function. We do this by listening to events for the
2225 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
2226 ConstString full_name("lldb.debugger.event-handler");
2227 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
2228 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
2230
2231 llvm::StringRef thread_name =
2232 full_name.GetLength() < llvm::get_max_thread_name_length()
2233 ? full_name.GetStringRef()
2234 : "dbg.evt-handler";
2235
2236 // Use larger 8MB stack for this thread
2237 llvm::Expected<HostThread> event_handler_thread =
2239 thread_name, [this] { return DefaultEventHandler(); },
2241
2242 if (event_handler_thread) {
2243 m_event_handler_thread = *event_handler_thread;
2244 } else {
2245 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(),
2246 "failed to launch host thread: {0}");
2247 }
2248
2249 // Make sure DefaultEventHandler() is running and listening to events
2250 // before we return from this function. We are only listening for events of
2251 // type eBroadcastBitEventThreadIsListening so we don't need to check the
2252 // event, we just need to wait an infinite amount of time for it (nullptr
2253 // timeout as the first parameter)
2254 lldb::EventSP event_sp;
2255 listener_sp->GetEvent(event_sp, std::nullopt);
2256 }
2257 return m_event_handler_thread.IsJoinable();
2258}
2259
2267
2273
2275 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
2276 if (!data)
2277 return;
2278
2279 // Make a local copy of the incoming progress report that we'll store.
2280 ProgressReport progress_report{data->GetID(), data->GetCompleted(),
2281 data->GetTotal(), data->GetMessage()};
2282
2283 {
2284 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2285
2286 // Do some bookkeeping regardless of whether we're going to display
2287 // progress reports.
2288 auto it = llvm::find_if(m_progress_reports, [&](const auto &report) {
2289 return report.id == progress_report.id;
2290 });
2291 if (it != m_progress_reports.end()) {
2292 const bool complete = data->GetCompleted() == data->GetTotal();
2293 if (complete)
2294 m_progress_reports.erase(it);
2295 else
2296 *it = progress_report;
2297 } else {
2298 m_progress_reports.push_back(progress_report);
2299 }
2300
2301 // Show progress using Operating System Command (OSC) sequences.
2304
2305 // Clear progress if this was the last progress event.
2306 if (m_progress_reports.empty()) {
2307 stream_sp->Lock() << OSC_PROGRESS_REMOVE;
2308 return;
2309 }
2310
2311 const ProgressReport &report = m_progress_reports.back();
2312
2313 // Show indeterminate progress.
2314 if (report.total == UINT64_MAX) {
2315 stream_sp->Lock() << OSC_PROGRESS_INDETERMINATE;
2316 return;
2317 }
2318
2319 // Compute and show the progress value (0-100).
2320 const unsigned value = (report.completed / report.total) * 100;
2321 stream_sp->Lock().Printf(OSC_PROGRESS_SHOW, value);
2322 }
2323 }
2324 }
2325}
2326
2327std::optional<Debugger::ProgressReport>
2329 std::lock_guard<std::mutex> guard(m_progress_reports_mutex);
2330 if (m_progress_reports.empty())
2331 return std::nullopt;
2332 return m_progress_reports.back();
2333}
2334
2336 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
2337 if (!data)
2338 return;
2339
2340 data->Dump(GetAsyncErrorStream().get());
2341}
2342
2344 return m_io_handler_thread.IsJoinable();
2345}
2346
2349 m_io_handler_thread = new_thread;
2350 return old_host;
2351}
2352
2354 if (!m_io_handler_thread.IsJoinable()) {
2355 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
2356 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
2357 8 * 1024 * 1024); // Use larger 8MB stack for this thread
2358 if (io_handler_thread) {
2359 m_io_handler_thread = *io_handler_thread;
2360 } else {
2361 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(),
2362 "failed to launch host thread: {0}");
2363 }
2364 }
2365 return m_io_handler_thread.IsJoinable();
2366}
2367
2369 if (m_io_handler_thread.IsJoinable()) {
2370 GetInputFile().Close();
2371 m_io_handler_thread.Join(nullptr);
2372 }
2373}
2374
2382
2384 if (!HasIOHandlerThread())
2385 return false;
2386 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread());
2387}
2388
2390 if (!prefer_dummy) {
2391 if (TargetSP target = m_target_list.GetSelectedTarget())
2392 return *target;
2393 }
2394 return GetDummyTarget();
2395}
2396
2397Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
2398 Status err;
2399 FileSpec repl_executable;
2400
2401 if (language == eLanguageTypeUnknown)
2402 language = GetREPLLanguage();
2403
2404 if (language == eLanguageTypeUnknown) {
2406
2407 if (auto single_lang = repl_languages.GetSingularLanguage()) {
2408 language = *single_lang;
2409 } else if (repl_languages.Empty()) {
2411 "LLDB isn't configured with REPL support for any languages.");
2412 return err;
2413 } else {
2415 "Multiple possible REPL languages. Please specify a language.");
2416 return err;
2417 }
2418 }
2419
2420 Target *const target =
2421 nullptr; // passing in an empty target means the REPL must create one
2422
2423 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2424
2425 if (!err.Success()) {
2426 return err;
2427 }
2428
2429 if (!repl_sp) {
2431 "couldn't find a REPL for %s",
2433 return err;
2434 }
2435
2436 repl_sp->SetCompilerOptions(repl_options);
2437 repl_sp->RunLoop();
2438
2439 return err;
2440}
2441
2442llvm::ThreadPoolInterface &Debugger::GetThreadPool() {
2443 assert(g_thread_pool &&
2444 "Debugger::GetThreadPool called before Debugger::Initialize");
2445 return *g_thread_pool;
2446}
2447
2449 llvm::StringRef name, bool value,
2450 llvm::StringRef description) {
2451 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2452 entry_up->AddBooleanItem("value", value);
2453 entry_up->AddStringItem("description", description);
2454 dict.AddItem(name, std::move(entry_up));
2455}
2456
2458 auto array_up = std::make_unique<StructuredData::Array>();
2459#define LLVM_TARGET(target) \
2460 array_up->AddItem(std::make_unique<StructuredData::String>(#target));
2461#include "llvm/Config/Targets.def"
2462 auto entry_up = std::make_unique<StructuredData::Dictionary>();
2463 entry_up->AddItem("value", std::move(array_up));
2464 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
2465 dict.AddItem("targets", std::move(entry_up));
2466}
2467
2469 auto config_up = std::make_unique<StructuredData::Dictionary>();
2471 *config_up, "xml", XMLDocument::XMLEnabled(),
2472 "A boolean value that indicates if XML support is enabled in LLDB");
2474 *config_up, "curl", LLVM_ENABLE_CURL,
2475 "A boolean value that indicates if CURL support is enabled in LLDB");
2477 *config_up, "curses", LLDB_ENABLE_CURSES,
2478 "A boolean value that indicates if curses support is enabled in LLDB");
2480 *config_up, "editline", LLDB_ENABLE_LIBEDIT,
2481 "A boolean value that indicates if editline support is enabled in LLDB");
2482 AddBoolConfigEntry(*config_up, "editline_wchar", LLDB_EDITLINE_USE_WCHAR,
2483 "A boolean value that indicates if editline wide "
2484 "characters support is enabled in LLDB");
2486 *config_up, "lzma", LLDB_ENABLE_LZMA,
2487 "A boolean value that indicates if lzma support is enabled in LLDB");
2489 *config_up, "python", LLDB_ENABLE_PYTHON,
2490 "A boolean value that indicates if python support is enabled in LLDB");
2492 *config_up, "lua", LLDB_ENABLE_LUA,
2493 "A boolean value that indicates if lua support is enabled in LLDB");
2494 AddBoolConfigEntry(*config_up, "fbsdvmcore", LLDB_ENABLE_FBSDVMCORE,
2495 "A boolean value that indicates if fbsdvmcore support is "
2496 "enabled in LLDB");
2497 AddLLVMTargets(*config_up);
2498 return config_up;
2499}
#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:773
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:496
InterruptionReport(std::string function_name, std::string description)
Definition Debugger.h:478
A class to manage flag bits.
Definition Debugger.h:80
static void AssertCallback(llvm::StringRef message, llvm::StringRef backtrace, llvm::StringRef prompt)
llvm::StringRef GetAutosuggestionAnsiPrefix() const
Definition Debugger.cpp:543
bool SetUseExternalEditor(bool use_external_editor_p)
Definition Debugger.cpp:440
PlatformList m_platform_list
Definition Debugger.h:744
HostThread m_event_handler_thread
Definition Debugger.h:774
static lldb::TargetSP FindTargetWithProcessID(lldb::pid_t pid)
Definition Debugger.cpp:934
FormatEntity::Entry GetDisassemblyFormat() const
Definition Debugger.cpp:302
uint64_t GetDisassemblyLineCount() const
Definition Debugger.cpp:638
lldb::TargetSP GetSelectedTarget()
Definition Debugger.h:183
llvm::StringRef GetDisabledAnsiSuffix() const
Definition Debugger.cpp:524
uint64_t GetTerminalHeight() const
Definition Debugger.cpp:412
lldb::LockableStreamFileSP m_output_stream_sp
Definition Debugger.h:731
bool SetExternalEditor(llvm::StringRef editor)
Definition Debugger.cpp:451
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:770
static void Terminate()
Definition Debugger.cpp:725
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:477
bool StartEventHandlerThread()
Manually start the global event handler thread.
bool SetUseSourceCache(bool use_source_cache)
Definition Debugger.cpp:579
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:667
lldb::FileSP GetInputFileSP()
Definition Debugger.h:139
bool GetHighlightSource() const
Definition Debugger.cpp:587
llvm::StringMap< std::weak_ptr< LogHandler > > m_stream_handlers
Definition Debugger.h:768
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:166
FormatEntity::Entry GetStatuslineFormat() const
Definition Debugger.cpp:500
LoadedPluginsList m_loaded_plugins
Definition Debugger.h:773
bool GetShowInlineDiagnostics() const
Definition Debugger.cpp:696
bool SetTabSize(uint64_t tab_size)
Definition Debugger.cpp:684
void HandleDiagnosticEvent(const lldb::EventSP &event_sp)
static lldb::DebuggerSP GetDebuggerAtIndex(size_t index)
llvm::StringRef GetAutosuggestionAnsiSuffix() const
Definition Debugger.cpp:549
lldb::ListenerSP m_listener_sp
Definition Debugger.h:745
void PushIOHandler(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
std::mutex m_destroy_callback_mutex
Definition Debugger.h:789
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:312
std::optional< ProgressReport > GetCurrentProgressReport() const
static lldb::TargetSP FindTargetWithProcess(Process *process)
Definition Debugger.cpp:948
llvm::StringRef GetDisabledAnsiPrefix() const
Definition Debugger.cpp:518
bool GetUseExternalEditor() const
Definition Debugger.cpp:434
TerminalState m_terminal_state
Definition Debugger.h:741
lldb::StreamUP GetAsyncErrorStream()
bool GetEscapeNonPrintables() const
Definition Debugger.cpp:650
lldb::TargetSP m_dummy_target_sp
Definition Debugger.h:780
llvm::SmallVector< DestroyCallbackInfo, 2 > m_destroy_callbacks
Definition Debugger.h:801
std::unique_ptr< CommandInterpreter > m_command_interpreter_up
Definition Debugger.h:755
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:751
LockableStreamFile::Mutex m_output_mutex
Definition Debugger.h:733
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
llvm::StringRef GetShowProgressAnsiSuffix() const
Definition Debugger.cpp:488
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:785
bool IsIOHandlerThreadCurrentThread() const
void DispatchClientTelemetry(const lldb_private::StructuredDataImpl &entry)
Definition Debugger.cpp:861
std::mutex m_progress_reports_mutex
Definition Debugger.h:786
lldb::ProcessSP HandleProcessEvent(const lldb::EventSP &event_sp)
lldb::ListenerSP m_forward_listener_sp
Definition Debugger.h:778
std::array< lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown > m_script_interpreters
Definition Debugger.h:759
std::shared_ptr< CallbackLogHandler > m_callback_handler_sp
Definition Debugger.h:769
void SetDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback, void *baton)
DEPRECATED: We used to only support one Destroy callback.
lldb::FileSP GetOutputFileSP()
Definition Debugger.h:142
Broadcaster m_broadcaster
Public Debugger event broadcaster.
Definition Debugger.h:777
static void Initialize(LoadPluginCallbackType load_plugin_callback)
Definition Debugger.cpp:716
static lldb::DebuggerSP FindDebuggerWithInstanceName(llvm::StringRef instance_name)
Definition Debugger.cpp:919
uint64_t GetTerminalWidth() const
Definition Debugger.cpp:390
std::mutex m_interrupt_mutex
Definition Debugger.h:804
std::recursive_mutex m_io_handler_synchronous_mutex
Definition Debugger.h:762
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:781
bool GetAutoOneLineSummaries() const
Definition Debugger.cpp:644
const char * GetIOHandlerCommandPrefix()
std::optional< Statusline > m_statusline
Definition Debugger.h:766
bool GetUseColor() const
Definition Debugger.cpp:456
lldb::BroadcasterManagerSP m_broadcaster_manager_sp
Definition Debugger.h:735
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:771
bool GetShowStatusline() const
Definition Debugger.cpp:494
std::recursive_mutex m_script_interpreter_mutex
Definition Debugger.h:757
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:684
void SetPrompt(llvm::StringRef p)
Definition Debugger.cpp:347
llvm::StringRef GetSeparator() const
Definition Debugger.cpp:512
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:317
bool SetTerminalHeight(uint64_t term_height)
Definition Debugger.cpp:418
Broadcaster m_sync_broadcaster
Private debugger synchronization.
Definition Debugger.h:776
bool GetUseSourceCache() const
Definition Debugger.cpp:573
HostThread m_io_handler_thread
Definition Debugger.h:775
llvm::StringRef GetRegexMatchAnsiSuffix() const
Definition Debugger.cpp:561
static llvm::StringRef GetStaticBroadcasterClass()
Definition Debugger.cpp:962
lldb::FileSP m_input_file_sp
Definition Debugger.h:730
bool SetREPLLanguage(lldb::LanguageType repl_lang)
Definition Debugger.cpp:385
bool GetAutoIndent() const
Definition Debugger.cpp:656
llvm::StringRef GetStopShowColumnAnsiSuffix() const
Definition Debugger.cpp:606
Status SetPropertyValue(const ExecutionContext *exe_ctx, VarSetOperationType op, llvm::StringRef property_path, llvm::StringRef value) override
Definition Debugger.cpp:207
llvm::StringRef GetPromptAnsiSuffix() const
Definition Debugger.cpp:341
FormatEntity::Entry GetThreadStopFormat() const
Definition Debugger.cpp:363
void SetErrorFile(lldb::FileSP file)
bool GetAutoConfirm() const
Definition Debugger.cpp:296
TargetList m_target_list
Definition Debugger.h:742
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:368
lldb::callback_token_t m_destroy_callback_next_token
Definition Debugger.h:790
std::unique_ptr< SourceManager > m_source_manager_up
Definition Debugger.h:746
static lldb::DebuggerSP CreateInstance(lldb::LogOutputCallback log_callback=nullptr, void *baton=nullptr)
Definition Debugger.cpp:843
lldb::StopShowColumn GetStopShowColumn() const
Definition Debugger.cpp:593
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:673
bool SetScriptLanguage(lldb::ScriptLanguage script_lang)
Definition Debugger.cpp:375
lldb::LockableStreamFileSP m_error_stream_sp
Definition Debugger.h:732
bool SetShowInlineDiagnostics(bool)
Definition Debugger.cpp:702
bool LoadPlugin(const FileSpec &spec, Status &error)
Definition Debugger.cpp:755
void SetOutputFile(lldb::FileSP file)
uint64_t GetStopSourceLineCount(bool before) const
Definition Debugger.cpp:624
bool SetStatuslineFormat(const FormatEntity::Entry &format)
Definition Debugger.cpp:505
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:511
lldb::ListenerSP GetListener()
Definition Debugger.h:175
static void Destroy(lldb::DebuggerSP &debugger_sp)
Definition Debugger.cpp:887
SourceManager::SourceFileCache m_source_file_cache
Definition Debugger.h:750
ExecutionContextRef GetSelectedExecutionContextRef()
Similar to GetSelectedExecutionContext but returns a ExecutionContextRef, and will hold the dummy tar...
llvm::StringRef GetPromptAnsiPrefix() const
Definition Debugger.cpp:335
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:87
llvm::StringRef GetStopShowLineMarkerAnsiPrefix() const
Definition Debugger.cpp:612
bool GetShowDontUsePoHint() const
Definition Debugger.cpp:567
uint64_t GetTabSize() const
Definition Debugger.cpp:678
bool GetShowProgress() const
Definition Debugger.cpp:471
llvm::StringRef GetRegexMatchAnsiPrefix() const
Definition Debugger.cpp:555
std::mutex m_output_flush_mutex
Definition Debugger.h:725
llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const
Definition Debugger.cpp:618
bool SetSeparator(llvm::StringRef s)
Definition Debugger.cpp:530
bool SetUseColor(bool use_color)
Definition Debugger.cpp:462
std::mutex m_statusline_mutex
Mutex protecting the m_statusline member.
Definition Debugger.h:765
const char * GetIOHandlerHelpPrologue()
Status SetInputString(const char *data)
bool GetUseAutosuggestion() const
Definition Debugger.cpp:537
Target & GetSelectedOrDummyTarget(bool prefer_dummy=false)
IOHandlerStack m_io_handler_stack
Definition Debugger.h:761
llvm::once_flag m_clear_once
Definition Debugger.h:779
static void SettingsTerminate()
Definition Debugger.cpp:753
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:380
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:396
Debugger(lldb::LogOutputCallback m_log_callback, void *baton)
Definition Debugger.cpp:967
llvm::StringRef GetExternalEditor() const
Definition Debugger.cpp:445
static size_t GetNumDebuggers()
FormatEntity::Entry GetThreadFormat() const
Definition Debugger.cpp:358
uint32_t m_interrupt_requested
Tracks interrupt requests.
Definition Debugger.h:803
lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const
Definition Debugger.cpp:689
lldb::thread_result_t DefaultEventHandler()
void PrintAsync(const char *s, size_t len, bool is_stdout)
lldb::LockableStreamFileSP GetErrorStreamSP()
Definition Debugger.h:685
llvm::StringRef GetPrompt() const
Definition Debugger.cpp:329
bool GetNotifyVoid() const
Definition Debugger.cpp:323
llvm::StringRef GetShowProgressAnsiPrefix() const
Definition Debugger.cpp:482
void AdoptTopIOHandlerFilesIfInvalid(lldb::FileSP &in, lldb::LockableStreamFileSP &out, lldb::LockableStreamFileSP &err)
FormatEntity::Entry GetFrameFormat() const
Definition Debugger.cpp:307
lldb::StopDisassemblyType GetStopDisassemblyDisplay() const
Definition Debugger.cpp:631
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:82
bool SetAutoIndent(bool b)
Definition Debugger.cpp:662
friend class CommandInterpreter
Definition Debugger.h:631
llvm::StringRef GetStopShowColumnAnsiPrefix() const
Definition Debugger.cpp:600
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 Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
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:181
@ eEnumerateDirectoryResultNext
Enumerate next entry in the current directory.
Definition FileSystem.h:178
@ eEnumerateDirectoryResultQuit
Stop directory enumerations at any level.
Definition FileSystem.h:183
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
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
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:367
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4448
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4456
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:731
static llvm::StringRef GetStaticBroadcasterClass()
Definition Process.cpp:421
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4651
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4632
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)
bool Format(const Entry &entry, Stream &s, const SymbolContext *sc, const ExecutionContext *exe_ctx, const Address *addr, ValueObject *valobj, bool function_changed, bool initial_function)
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:798
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.
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