1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/Debugger.h"
11 #include "lldb/Breakpoint/Breakpoint.h"
12 #include "lldb/Core/FormatEntity.h"
13 #include "lldb/Core/Mangled.h"
14 #include "lldb/Core/ModuleList.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/StreamAsynchronousIO.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/DataFormatters/DataVisualization.h"
19 #include "lldb/Expression/REPL.h"
20 #include "lldb/Host/File.h"
21 #include "lldb/Host/FileSystem.h"
22 #include "lldb/Host/HostInfo.h"
23 #include "lldb/Host/Terminal.h"
24 #include "lldb/Host/ThreadLauncher.h"
25 #include "lldb/Interpreter/CommandInterpreter.h"
26 #include "lldb/Interpreter/OptionValue.h"
27 #include "lldb/Interpreter/OptionValueProperties.h"
28 #include "lldb/Interpreter/OptionValueSInt64.h"
29 #include "lldb/Interpreter/OptionValueString.h"
30 #include "lldb/Interpreter/Property.h"
31 #include "lldb/Interpreter/ScriptInterpreter.h"
32 #include "lldb/Symbol/Function.h"
33 #include "lldb/Symbol/Symbol.h"
34 #include "lldb/Symbol/SymbolContext.h"
35 #include "lldb/Target/Language.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/StructuredDataPlugin.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/TargetList.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Target/ThreadList.h"
42 #include "lldb/Utility/AnsiTerminal.h"
43 #include "lldb/Utility/Event.h"
44 #include "lldb/Utility/Listener.h"
45 #include "lldb/Utility/Log.h"
46 #include "lldb/Utility/Reproducer.h"
47 #include "lldb/Utility/State.h"
48 #include "lldb/Utility/Stream.h"
49 #include "lldb/Utility/StreamCallback.h"
50 #include "lldb/Utility/StreamString.h"
53 #include "lldb/Host/windows/PosixApi.h"
54 #include "lldb/Host/windows/windows.h"
57 #include "llvm/ADT/None.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/iterator.h"
61 #include "llvm/Support/DynamicLibrary.h"
62 #include "llvm/Support/FileSystem.h"
63 #include "llvm/Support/Process.h"
64 #include "llvm/Support/Threading.h"
65 #include "llvm/Support/raw_ostream.h"
75 #include <system_error>
77 namespace lldb_private {
82 using namespace lldb_private;
84 static lldb::user_id_t g_unique_id = 1;
85 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
87 #pragma mark Static Functions
89 typedef std::vector<DebuggerSP> DebuggerList;
90 static std::recursive_mutex *g_debugger_list_mutex_ptr =
91 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
92 static DebuggerList *g_debugger_list_ptr =
93 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
95 static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
97 Debugger::eStopDisassemblyTypeNever,
99 "Never show disassembly when displaying a stop context.",
102 Debugger::eStopDisassemblyTypeNoDebugInfo,
104 "Show disassembly when there is no debug information.",
107 Debugger::eStopDisassemblyTypeNoSource,
109 "Show disassembly when there is no source information, or the source "
111 "is missing when displaying a stop context.",
114 Debugger::eStopDisassemblyTypeAlways,
116 "Always show disassembly when displaying a stop context.",
120 static constexpr OptionEnumValueElement g_language_enumerators[] = {
124 "Disable scripting languages.",
127 eScriptLanguagePython,
129 "Select python as the default scripting language.",
132 eScriptLanguageDefault,
134 "Select the lldb default as the default scripting language.",
138 #define MODULE_WITH_FUNC \
140 "${module.file.basename}{`${function.name-with-args}" \
141 "{${frame.no-debug}${function.pc-offset}}}}"
143 #define MODULE_WITH_FUNC_NO_ARGS \
145 "${module.file.basename}{`${function.name-without-args}" \
146 "{${frame.no-debug}${function.pc-offset}}}}"
148 #define FILE_AND_LINE \
149 "{ at ${ansi.fg.cyan}${line.file.basename}${ansi.normal}" \
150 ":${ansi.fg.yellow}${line.number}${ansi.normal}" \
151 "{:${ansi.fg.yellow}${line.column}${ansi.normal}}}"
153 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
155 #define IS_ARTIFICIAL "{${frame.is-artificial} [artificial]}"
157 #define DEFAULT_THREAD_FORMAT \
158 "thread #${thread.index}: tid = ${thread.id%tid}" \
159 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
160 "{, name = ${ansi.fg.green}'${thread.name}'${ansi.normal}}" \
161 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
163 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
164 "{, ${thread.info.trace_messages} messages}" \
165 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
166 "{\\nReturn value: ${thread.return-value}}" \
167 "{\\nCompleted expression: ${thread.completed-expression}}" \
170 #define DEFAULT_THREAD_STOP_FORMAT \
171 "thread #${thread.index}{, name = '${thread.name}'}" \
172 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
174 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
175 "{, ${thread.info.trace_messages} messages}" \
176 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
177 "{\\nReturn value: ${thread.return-value}}" \
178 "{\\nCompleted expression: ${thread.completed-expression}}" \
181 #define DEFAULT_FRAME_FORMAT \
182 "frame #${frame.index}: " \
183 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC FILE_AND_LINE \
184 IS_OPTIMIZED IS_ARTIFICIAL "\\n"
186 #define DEFAULT_FRAME_FORMAT_NO_ARGS \
187 "frame #${frame.index}: " \
188 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC_NO_ARGS \
189 FILE_AND_LINE IS_OPTIMIZED IS_ARTIFICIAL "\\n"
191 // Three parts to this disassembly format specification:
192 // 1. If this is a new function/symbol (no previous symbol/function), print
194 // 2. If this is a symbol context change (different from previous
195 // symbol/function), print
198 // address <+offset>:
199 #define DEFAULT_DISASSEMBLY_FORMAT \
200 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
201 "without-args}}:\\n}{${function.changed}\\n{${module.file.basename}`}{${" \
202 "function.name-without-args}}:\\n}{${current-pc-arrow} " \
203 "}${addr-file-or-load}{ " \
204 "<${function.concrete-only-addr-offset-no-padding}>}: "
206 // gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
207 // file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
208 // offset-no-padding}>}:
210 // lldb's original format for disassembly would look like this format string -
211 // {${function.initial-function}{${module.file.basename}`}{${function.name-
213 // args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
214 // without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
216 static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
218 eStopShowColumnAnsiOrCaret,
220 "Highlight the stop column with ANSI terminal codes when color/ANSI "
221 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
222 "as if \"caret-only\" mode was selected.",
227 "Highlight the stop column with ANSI terminal codes when running LLDB "
228 "with color/ANSI enabled.",
231 eStopShowColumnCaret,
233 "Highlight the stop column with a caret character (^) underneath the "
234 "stop column. This method introduces a new line in source listings "
235 "that display thread stop locations.",
240 "Do not highlight the stop column.",
244 #define LLDB_PROPERTIES_debugger
245 #include "CoreProperties.inc"
248 #define LLDB_PROPERTIES_debugger
249 #include "CorePropertiesEnum.inc"
252 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
254 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
255 VarSetOperationType op,
256 llvm::StringRef property_path,
257 llvm::StringRef value) {
258 bool is_load_script =
259 (property_path == "target.load-script-from-symbol-file");
260 // These properties might change how we visualize data.
261 bool invalidate_data_vis = (property_path == "escape-non-printables");
262 invalidate_data_vis |=
263 (property_path == "target.max-zero-padding-in-float-format");
264 if (invalidate_data_vis) {
265 DataVisualization::ForceUpdate();
269 LoadScriptFromSymFile load_script_old_value;
270 if (is_load_script && exe_ctx->GetTargetSP()) {
271 target_sp = exe_ctx->GetTargetSP();
272 load_script_old_value =
273 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
275 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
276 if (error.Success()) {
277 // FIXME it would be nice to have "on-change" callbacks for properties
278 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
279 llvm::StringRef new_prompt = GetPrompt();
280 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes(
281 new_prompt, GetUseColor());
284 GetCommandInterpreter().UpdatePrompt(new_prompt);
285 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
286 auto prompt_change_event_sp = std::make_shared<Event>(
287 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
288 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
289 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
290 // use-color changed. Ping the prompt so it can reset the ansi terminal
292 SetPrompt(GetPrompt());
293 } else if (is_load_script && target_sp &&
294 load_script_old_value == eLoadScriptFromSymFileWarn) {
295 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
296 eLoadScriptFromSymFileTrue) {
297 std::list<Status> errors;
298 StreamString feedback_stream;
299 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
300 Stream &s = GetErrorStream();
301 for (auto error : errors) {
302 s.Printf("%s\n", error.AsCString());
304 if (feedback_stream.GetSize())
305 s.PutCString(feedback_stream.GetString());
313 bool Debugger::GetAutoConfirm() const {
314 const uint32_t idx = ePropertyAutoConfirm;
315 return m_collection_sp->GetPropertyAtIndexAsBoolean(
316 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
319 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
320 const uint32_t idx = ePropertyDisassemblyFormat;
321 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
324 const FormatEntity::Entry *Debugger::GetFrameFormat() const {
325 const uint32_t idx = ePropertyFrameFormat;
326 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
329 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
330 const uint32_t idx = ePropertyFrameFormatUnique;
331 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
334 bool Debugger::GetNotifyVoid() const {
335 const uint32_t idx = ePropertyNotiftVoid;
336 return m_collection_sp->GetPropertyAtIndexAsBoolean(
337 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
340 llvm::StringRef Debugger::GetPrompt() const {
341 const uint32_t idx = ePropertyPrompt;
342 return m_collection_sp->GetPropertyAtIndexAsString(
343 nullptr, idx, g_debugger_properties[idx].default_cstr_value);
346 void Debugger::SetPrompt(llvm::StringRef p) {
347 const uint32_t idx = ePropertyPrompt;
348 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
349 llvm::StringRef new_prompt = GetPrompt();
351 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
354 GetCommandInterpreter().UpdatePrompt(new_prompt);
357 llvm::StringRef Debugger::GetReproducerPath() const {
358 auto &r = repro::Reproducer::Instance();
359 return r.GetReproducerPath().GetCString();
362 const FormatEntity::Entry *Debugger::GetThreadFormat() const {
363 const uint32_t idx = ePropertyThreadFormat;
364 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
367 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
368 const uint32_t idx = ePropertyThreadStopFormat;
369 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
372 lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
373 const uint32_t idx = ePropertyScriptLanguage;
374 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
375 nullptr, idx, g_debugger_properties[idx].default_uint_value);
378 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
379 const uint32_t idx = ePropertyScriptLanguage;
380 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
384 uint32_t Debugger::GetTerminalWidth() const {
385 const uint32_t idx = ePropertyTerminalWidth;
386 return m_collection_sp->GetPropertyAtIndexAsSInt64(
387 nullptr, idx, g_debugger_properties[idx].default_uint_value);
390 bool Debugger::SetTerminalWidth(uint32_t term_width) {
391 const uint32_t idx = ePropertyTerminalWidth;
392 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
395 bool Debugger::GetUseExternalEditor() const {
396 const uint32_t idx = ePropertyUseExternalEditor;
397 return m_collection_sp->GetPropertyAtIndexAsBoolean(
398 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
401 bool Debugger::SetUseExternalEditor(bool b) {
402 const uint32_t idx = ePropertyUseExternalEditor;
403 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
406 bool Debugger::GetUseColor() const {
407 const uint32_t idx = ePropertyUseColor;
408 return m_collection_sp->GetPropertyAtIndexAsBoolean(
409 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
412 bool Debugger::SetUseColor(bool b) {
413 const uint32_t idx = ePropertyUseColor;
414 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
415 SetPrompt(GetPrompt());
419 bool Debugger::GetHighlightSource() const {
420 const uint32_t idx = ePropertyHighlightSource;
421 return m_collection_sp->GetPropertyAtIndexAsBoolean(
422 nullptr, idx, g_debugger_properties[idx].default_uint_value);
425 StopShowColumn Debugger::GetStopShowColumn() const {
426 const uint32_t idx = ePropertyStopShowColumn;
427 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
428 nullptr, idx, g_debugger_properties[idx].default_uint_value);
431 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
432 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
433 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
436 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
437 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
438 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
441 uint32_t Debugger::GetStopSourceLineCount(bool before) const {
443 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
444 return m_collection_sp->GetPropertyAtIndexAsSInt64(
445 nullptr, idx, g_debugger_properties[idx].default_uint_value);
448 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
449 const uint32_t idx = ePropertyStopDisassemblyDisplay;
450 return (Debugger::StopDisassemblyType)
451 m_collection_sp->GetPropertyAtIndexAsEnumeration(
452 nullptr, idx, g_debugger_properties[idx].default_uint_value);
455 uint32_t Debugger::GetDisassemblyLineCount() const {
456 const uint32_t idx = ePropertyStopDisassemblyCount;
457 return m_collection_sp->GetPropertyAtIndexAsSInt64(
458 nullptr, idx, g_debugger_properties[idx].default_uint_value);
461 bool Debugger::GetAutoOneLineSummaries() const {
462 const uint32_t idx = ePropertyAutoOneLineSummaries;
463 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
466 bool Debugger::GetEscapeNonPrintables() const {
467 const uint32_t idx = ePropertyEscapeNonPrintables;
468 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
471 bool Debugger::GetAutoIndent() const {
472 const uint32_t idx = ePropertyAutoIndent;
473 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
476 bool Debugger::SetAutoIndent(bool b) {
477 const uint32_t idx = ePropertyAutoIndent;
478 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
481 bool Debugger::GetPrintDecls() const {
482 const uint32_t idx = ePropertyPrintDecls;
483 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
486 bool Debugger::SetPrintDecls(bool b) {
487 const uint32_t idx = ePropertyPrintDecls;
488 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
491 uint32_t Debugger::GetTabSize() const {
492 const uint32_t idx = ePropertyTabSize;
493 return m_collection_sp->GetPropertyAtIndexAsUInt64(
494 nullptr, idx, g_debugger_properties[idx].default_uint_value);
497 bool Debugger::SetTabSize(uint32_t tab_size) {
498 const uint32_t idx = ePropertyTabSize;
499 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
502 #pragma mark Debugger
504 // const DebuggerPropertiesSP &
505 // Debugger::GetSettings() const
507 // return m_properties_sp;
511 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
512 assert(g_debugger_list_ptr == nullptr &&
513 "Debugger::Initialize called more than once!");
514 g_debugger_list_mutex_ptr = new std::recursive_mutex();
515 g_debugger_list_ptr = new DebuggerList();
516 g_load_plugin_callback = load_plugin_callback;
519 void Debugger::Terminate() {
520 assert(g_debugger_list_ptr &&
521 "Debugger::Terminate called without a matching Debugger::Initialize!");
523 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
524 // Clear our master list of debugger objects
526 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
527 for (const auto &debugger : *g_debugger_list_ptr)
529 g_debugger_list_ptr->clear();
534 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
536 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
538 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
539 if (g_load_plugin_callback) {
540 llvm::sys::DynamicLibrary dynlib =
541 g_load_plugin_callback(shared_from_this(), spec, error);
542 if (dynlib.isValid()) {
543 m_loaded_plugins.push_back(dynlib);
547 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
548 // if the public API layer isn't available (code is linking against all of
549 // the internal LLDB static libraries), then we can't load plugins
550 error.SetErrorString("Public API layer is not available");
555 static FileSystem::EnumerateDirectoryResult
556 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
557 llvm::StringRef path) {
560 static ConstString g_dylibext(".dylib");
561 static ConstString g_solibext(".so");
564 return FileSystem::eEnumerateDirectoryResultQuit;
566 Debugger *debugger = (Debugger *)baton;
568 namespace fs = llvm::sys::fs;
569 // If we have a regular file, a symbolic link or unknown file type, try and
570 // process the file. We must handle unknown as sometimes the directory
571 // enumeration might be enumerating a file system that doesn't have correct
572 // file type information.
573 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
574 ft == fs::file_type::type_unknown) {
575 FileSpec plugin_file_spec(path);
576 FileSystem::Instance().Resolve(plugin_file_spec);
578 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
579 plugin_file_spec.GetFileNameExtension() != g_solibext) {
580 return FileSystem::eEnumerateDirectoryResultNext;
583 Status plugin_load_error;
584 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
586 return FileSystem::eEnumerateDirectoryResultNext;
587 } else if (ft == fs::file_type::directory_file ||
588 ft == fs::file_type::symlink_file ||
589 ft == fs::file_type::type_unknown) {
590 // Try and recurse into anything that a directory or symbolic link. We must
591 // also do this for unknown as sometimes the directory enumeration might be
592 // enumerating a file system that doesn't have correct file type
594 return FileSystem::eEnumerateDirectoryResultEnter;
597 return FileSystem::eEnumerateDirectoryResultNext;
600 void Debugger::InstanceInitialize() {
601 const bool find_directories = true;
602 const bool find_files = true;
603 const bool find_other = true;
604 char dir_path[PATH_MAX];
605 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
606 if (FileSystem::Instance().Exists(dir_spec) &&
607 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
608 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
609 find_files, find_other,
610 LoadPluginCallback, this);
614 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
615 if (FileSystem::Instance().Exists(dir_spec) &&
616 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
617 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
618 find_files, find_other,
619 LoadPluginCallback, this);
623 PluginManager::DebuggerInitialize(*this);
626 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
628 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
629 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
630 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
631 g_debugger_list_ptr->push_back(debugger_sp);
633 debugger_sp->InstanceInitialize();
637 void Debugger::Destroy(DebuggerSP &debugger_sp) {
641 debugger_sp->Clear();
643 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
644 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
645 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
646 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
647 if ((*pos).get() == debugger_sp.get()) {
648 g_debugger_list_ptr->erase(pos);
655 DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
656 DebuggerSP debugger_sp;
657 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
658 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
659 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
660 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
661 if ((*pos)->m_instance_name == instance_name) {
670 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
672 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
673 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
674 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
675 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
676 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
684 TargetSP Debugger::FindTargetWithProcess(Process *process) {
686 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
687 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
688 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
689 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
690 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
698 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
699 : UserID(g_unique_id++),
700 Properties(std::make_shared<OptionValueProperties>()),
701 m_input_file_sp(std::make_shared<NativeFile>(stdin, false)),
702 m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)),
703 m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)),
704 m_input_recorder(nullptr),
705 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
706 m_terminal_state(), m_target_list(*this), m_platform_list(),
707 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
708 m_source_manager_up(), m_source_file_cache(),
709 m_command_interpreter_up(
710 std::make_unique<CommandInterpreter>(*this, false)),
711 m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(),
712 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
713 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
714 m_forward_listener_sp(), m_clear_once() {
715 char instance_cstr[256];
716 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
717 m_instance_name.SetCString(instance_cstr);
719 m_log_callback_stream_sp =
720 std::make_shared<StreamCallback>(log_callback, baton);
721 m_command_interpreter_up->Initialize();
722 // Always add our default platform to the platform list
723 PlatformSP default_platform_sp(Platform::GetHostPlatform());
724 assert(default_platform_sp);
725 m_platform_list.Append(default_platform_sp, true);
727 m_dummy_target_sp = m_target_list.GetDummyTarget(*this);
728 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
730 m_collection_sp->Initialize(g_debugger_properties);
731 m_collection_sp->AppendProperty(
732 ConstString("target"),
733 ConstString("Settings specify to debugging targets."), true,
734 Target::GetGlobalProperties()->GetValueProperties());
735 m_collection_sp->AppendProperty(
736 ConstString("platform"), ConstString("Platform settings."), true,
737 Platform::GetGlobalPlatformProperties()->GetValueProperties());
738 m_collection_sp->AppendProperty(
739 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
740 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
741 if (m_command_interpreter_up) {
742 m_collection_sp->AppendProperty(
743 ConstString("interpreter"),
744 ConstString("Settings specify to the debugger's command interpreter."),
745 true, m_command_interpreter_up->GetValueProperties());
747 OptionValueSInt64 *term_width =
748 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
749 nullptr, ePropertyTerminalWidth);
750 term_width->SetMinimumValue(10);
751 term_width->SetMaximumValue(1024);
753 // Turn off use-color if this is a dumb terminal.
754 const char *term = getenv("TERM");
755 if (term && !strcmp(term, "dumb"))
757 // Turn off use-color if we don't write to a terminal with color support.
758 if (!GetOutputFile().GetIsTerminalWithColors())
761 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
762 // Enabling use of ANSI color codes because LLDB is using them to highlight
764 llvm::sys::Process::UseANSIEscapeCodes(true);
768 Debugger::~Debugger() { Clear(); }
770 void Debugger::Clear() {
771 // Make sure we call this function only once. With the C++ global destructor
772 // chain having a list of debuggers and with code that can be running on
773 // other threads, we need to ensure this doesn't happen multiple times.
775 // The following functions call Debugger::Clear():
776 // Debugger::~Debugger();
777 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
778 // static void Debugger::Terminate();
779 llvm::call_once(m_clear_once, [this]() {
781 StopIOHandlerThread();
782 StopEventHandlerThread();
783 m_listener_sp->Clear();
784 int num_targets = m_target_list.GetNumTargets();
785 for (int i = 0; i < num_targets; i++) {
786 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
788 ProcessSP process_sp(target_sp->GetProcessSP());
790 process_sp->Finalize();
791 target_sp->Destroy();
794 m_broadcaster_manager_sp->Clear();
796 // Close the input file _before_ we close the input read communications
797 // class as it does NOT own the input file, our m_input_file does.
798 m_terminal_state.Clear();
799 GetInputFile().Close();
801 m_command_interpreter_up->Clear();
805 bool Debugger::GetCloseInputOnEOF() const {
806 // return m_input_comm.GetCloseOnEOF();
810 void Debugger::SetCloseInputOnEOF(bool b) {
811 // m_input_comm.SetCloseOnEOF(b);
814 bool Debugger::GetAsyncExecution() {
815 return !m_command_interpreter_up->GetSynchronous();
818 void Debugger::SetAsyncExecution(bool async_execution) {
819 m_command_interpreter_up->SetSynchronous(!async_execution);
822 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
824 void Debugger::SetInputFile(FileSP file_sp, repro::DataRecorder *recorder) {
825 assert(file_sp && file_sp->IsValid());
826 m_input_recorder = recorder;
827 m_input_file_sp = file_sp;
828 // Save away the terminal state if that is relevant, so that we can restore
829 // it in RestoreInputState.
830 SaveInputTerminalState();
833 void Debugger::SetOutputFile(FileSP file_sp) {
834 assert(file_sp && file_sp->IsValid());
835 m_output_stream_sp = std::make_shared<StreamFile>(file_sp);
838 void Debugger::SetErrorFile(FileSP file_sp) {
839 assert(file_sp && file_sp->IsValid());
840 m_error_stream_sp = std::make_shared<StreamFile>(file_sp);
843 void Debugger::SaveInputTerminalState() {
844 int fd = GetInputFile().GetDescriptor();
845 if (fd != File::kInvalidDescriptor)
846 m_terminal_state.Save(fd, true);
849 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
851 ExecutionContext Debugger::GetSelectedExecutionContext() {
852 ExecutionContext exe_ctx;
853 TargetSP target_sp(GetSelectedTarget());
854 exe_ctx.SetTargetSP(target_sp);
857 ProcessSP process_sp(target_sp->GetProcessSP());
858 exe_ctx.SetProcessSP(process_sp);
859 if (process_sp && !process_sp->IsRunning()) {
860 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
862 exe_ctx.SetThreadSP(thread_sp);
863 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
864 if (exe_ctx.GetFramePtr() == nullptr)
865 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
872 void Debugger::DispatchInputInterrupt() {
873 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
874 IOHandlerSP reader_sp(m_input_reader_stack.Top());
876 reader_sp->Interrupt();
879 void Debugger::DispatchInputEndOfFile() {
880 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
881 IOHandlerSP reader_sp(m_input_reader_stack.Top());
886 void Debugger::ClearIOHandlers() {
887 // The bottom input reader should be the main debugger input reader. We do
888 // not want to close that one here.
889 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
890 while (m_input_reader_stack.GetSize() > 1) {
891 IOHandlerSP reader_sp(m_input_reader_stack.Top());
893 PopIOHandler(reader_sp);
897 void Debugger::ExecuteIOHandlers() {
899 IOHandlerSP reader_sp(m_input_reader_stack.Top());
905 // Remove all input readers that are done from the top of the stack
907 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
908 if (top_reader_sp && top_reader_sp->GetIsDone())
909 PopIOHandler(top_reader_sp);
917 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
918 return m_input_reader_stack.IsTop(reader_sp);
921 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
922 IOHandler::Type second_top_type) {
923 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
926 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
927 lldb_private::StreamFile &stream =
928 is_stdout ? GetOutputStream() : GetErrorStream();
929 m_input_reader_stack.PrintAsync(&stream, s, len);
932 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
933 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
936 const char *Debugger::GetIOHandlerCommandPrefix() {
937 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
940 const char *Debugger::GetIOHandlerHelpPrologue() {
941 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
944 void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
945 PushIOHandler(reader_sp);
947 IOHandlerSP top_reader_sp = reader_sp;
948 while (top_reader_sp) {
949 top_reader_sp->Run();
951 if (top_reader_sp.get() == reader_sp.get()) {
952 if (PopIOHandler(reader_sp))
957 top_reader_sp = m_input_reader_stack.Top();
958 if (top_reader_sp && top_reader_sp->GetIsDone())
959 PopIOHandler(top_reader_sp);
966 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out,
968 // Before an IOHandler runs, it must have in/out/err streams. This function
969 // is called when one ore more of the streams are nullptr. We use the top
970 // input reader's in/out/err streams, or fall back to the debugger file
971 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
973 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
974 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
975 // If no STDIN has been set, then set it appropriately
976 if (!in || !in->IsValid()) {
978 in = top_reader_sp->GetInputFileSP();
980 in = GetInputFileSP();
981 // If there is nothing, use stdin
983 in = std::make_shared<NativeFile>(stdin, false);
985 // If no STDOUT has been set, then set it appropriately
986 if (!out || !out->GetFile().IsValid()) {
988 out = top_reader_sp->GetOutputStreamFileSP();
990 out = GetOutputStreamSP();
991 // If there is nothing, use stdout
993 out = std::make_shared<StreamFile>(stdout, false);
995 // If no STDERR has been set, then set it appropriately
996 if (!err || !err->GetFile().IsValid()) {
998 err = top_reader_sp->GetErrorStreamFileSP();
1000 err = GetErrorStreamSP();
1001 // If there is nothing, use stderr
1003 err = std::make_shared<StreamFile>(stderr, false);
1007 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1008 bool cancel_top_handler) {
1012 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1014 // Get the current top input reader...
1015 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1017 // Don't push the same IO handler twice...
1018 if (reader_sp == top_reader_sp)
1021 // Push our new input reader
1022 m_input_reader_stack.Push(reader_sp);
1023 reader_sp->Activate();
1025 // Interrupt the top input reader to it will exit its Run() function and let
1026 // this new input reader take over
1027 if (top_reader_sp) {
1028 top_reader_sp->Deactivate();
1029 if (cancel_top_handler)
1030 top_reader_sp->Cancel();
1034 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1038 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1040 // The reader on the stop of the stack is done, so let the next read on the
1041 // stack refresh its prompt and if there is one...
1042 if (m_input_reader_stack.IsEmpty())
1045 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1047 if (pop_reader_sp != reader_sp)
1050 reader_sp->Deactivate();
1051 reader_sp->Cancel();
1052 m_input_reader_stack.Pop();
1054 reader_sp = m_input_reader_stack.Top();
1056 reader_sp->Activate();
1061 StreamSP Debugger::GetAsyncOutputStream() {
1062 return std::make_shared<StreamAsynchronousIO>(*this, true);
1065 StreamSP Debugger::GetAsyncErrorStream() {
1066 return std::make_shared<StreamAsynchronousIO>(*this, false);
1069 size_t Debugger::GetNumDebuggers() {
1070 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1071 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1072 return g_debugger_list_ptr->size();
1077 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1078 DebuggerSP debugger_sp;
1080 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1081 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1082 if (index < g_debugger_list_ptr->size())
1083 debugger_sp = g_debugger_list_ptr->at(index);
1089 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1090 DebuggerSP debugger_sp;
1092 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1093 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1094 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1095 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1096 if ((*pos)->GetID() == id) {
1105 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1106 const SymbolContext *sc,
1107 const SymbolContext *prev_sc,
1108 const ExecutionContext *exe_ctx,
1109 const Address *addr, Stream &s) {
1110 FormatEntity::Entry format_entry;
1112 if (format == nullptr) {
1113 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1114 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1115 if (format == nullptr) {
1116 FormatEntity::Parse("${addr}: ", format_entry);
1117 format = &format_entry;
1120 bool function_changed = false;
1121 bool initial_function = false;
1122 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1123 if (sc && (sc->function || sc->symbol)) {
1124 if (prev_sc->symbol && sc->symbol) {
1125 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1126 prev_sc->symbol->GetType())) {
1127 function_changed = true;
1129 } else if (prev_sc->function && sc->function) {
1130 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1131 function_changed = true;
1136 // The first context on a list of instructions will have a prev_sc that has
1137 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1138 // would return false. But we do get a prev_sc pointer.
1139 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1140 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1141 initial_function = true;
1143 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1144 function_changed, initial_function);
1147 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1149 // For simplicity's sake, I am not going to deal with how to close down any
1150 // open logging streams, I just redirect everything from here on out to the
1152 m_log_callback_stream_sp =
1153 std::make_shared<StreamCallback>(log_callback, baton);
1156 bool Debugger::EnableLog(llvm::StringRef channel,
1157 llvm::ArrayRef<const char *> categories,
1158 llvm::StringRef log_file, uint32_t log_options,
1159 llvm::raw_ostream &error_stream) {
1160 const bool should_close = true;
1161 const bool unbuffered = true;
1163 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
1164 if (m_log_callback_stream_sp) {
1165 log_stream_sp = m_log_callback_stream_sp;
1166 // For now when using the callback mode you always get thread & timestamp.
1168 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1169 } else if (log_file.empty()) {
1170 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1171 GetOutputFile().GetDescriptor(), !should_close, unbuffered);
1173 auto pos = m_log_streams.find(log_file);
1174 if (pos != m_log_streams.end())
1175 log_stream_sp = pos->second.lock();
1176 if (!log_stream_sp) {
1177 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::OF_Text;
1178 if (log_options & LLDB_LOG_OPTION_APPEND)
1179 flags |= llvm::sys::fs::OF_Append;
1181 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1182 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
1183 error_stream << "Unable to open log file: " << ec.message();
1187 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
1188 m_log_streams[log_file] = log_stream_sp;
1191 assert(log_stream_sp);
1193 if (log_options == 0)
1195 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1197 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1201 ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) {
1202 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1204 if (!m_script_interpreter_sp) {
1207 m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(
1208 GetScriptLanguage(), *this);
1211 return m_script_interpreter_sp.get();
1214 SourceManager &Debugger::GetSourceManager() {
1215 if (!m_source_manager_up)
1216 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1217 return *m_source_manager_up;
1220 // This function handles events that were broadcast by the process.
1221 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1222 using namespace lldb;
1223 const uint32_t event_type =
1224 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1227 // if (event_type & eBreakpointEventTypeAdded
1228 // || event_type & eBreakpointEventTypeRemoved
1229 // || event_type & eBreakpointEventTypeEnabled
1230 // || event_type & eBreakpointEventTypeDisabled
1231 // || event_type & eBreakpointEventTypeCommandChanged
1232 // || event_type & eBreakpointEventTypeConditionChanged
1233 // || event_type & eBreakpointEventTypeIgnoreChanged
1234 // || event_type & eBreakpointEventTypeLocationsResolved)
1236 // // Don't do anything about these events, since the breakpoint
1237 // commands already echo these actions.
1240 if (event_type & eBreakpointEventTypeLocationsAdded) {
1241 uint32_t num_new_locations =
1242 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1244 if (num_new_locations > 0) {
1245 BreakpointSP breakpoint =
1246 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1247 StreamSP output_sp(GetAsyncOutputStream());
1249 output_sp->Printf("%d location%s added to breakpoint %d\n",
1250 num_new_locations, num_new_locations == 1 ? "" : "s",
1251 breakpoint->GetID());
1256 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1258 // // These locations just get disabled, not sure it is worth spamming
1259 // folks about this on the command line.
1261 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1263 // // This might be an interesting thing to note, but I'm going to
1264 // leave it quiet for now, it just looked noisy.
1268 void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1269 bool flush_stderr) {
1270 const auto &flush = [&](Stream &stream,
1271 size_t (Process::*get)(char *, size_t, Status &)) {
1275 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1276 stream.Write(buffer, len);
1280 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1282 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT);
1284 flush(*GetAsyncErrorStream(), &Process::GetSTDERR);
1287 // This function handles events that were broadcast by the process.
1288 void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1289 using namespace lldb;
1290 const uint32_t event_type = event_sp->GetType();
1291 ProcessSP process_sp =
1292 (event_type == Process::eBroadcastBitStructuredData)
1293 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1294 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1296 StreamSP output_stream_sp = GetAsyncOutputStream();
1297 StreamSP error_stream_sp = GetAsyncErrorStream();
1298 const bool gui_enabled = IsForwardingEvents();
1301 bool pop_process_io_handler = false;
1304 bool state_is_stopped = false;
1305 const bool got_state_changed =
1306 (event_type & Process::eBroadcastBitStateChanged) != 0;
1307 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1308 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1309 const bool got_structured_data =
1310 (event_type & Process::eBroadcastBitStructuredData) != 0;
1312 if (got_state_changed) {
1313 StateType event_state =
1314 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1315 state_is_stopped = StateIsStoppedState(event_state, false);
1318 // Display running state changes first before any STDIO
1319 if (got_state_changed && !state_is_stopped) {
1320 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1321 pop_process_io_handler);
1324 // Now display STDOUT and STDERR
1325 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
1326 got_stderr || got_state_changed);
1328 // Give structured data events an opportunity to display.
1329 if (got_structured_data) {
1330 StructuredDataPluginSP plugin_sp =
1331 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1333 auto structured_data_sp =
1334 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1335 if (output_stream_sp) {
1336 StreamString content_stream;
1338 plugin_sp->GetDescription(structured_data_sp, content_stream);
1339 if (error.Success()) {
1340 if (!content_stream.GetString().empty()) {
1342 content_stream.PutChar('\n');
1343 content_stream.Flush();
1346 output_stream_sp->PutCString(content_stream.GetString());
1349 error_stream_sp->Printf("Failed to print structured "
1350 "data with plugin %s: %s",
1351 plugin_sp->GetPluginName().AsCString(),
1358 // Now display any stopped state changes after any STDIO
1359 if (got_state_changed && state_is_stopped) {
1360 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1361 pop_process_io_handler);
1364 output_stream_sp->Flush();
1365 error_stream_sp->Flush();
1367 if (pop_process_io_handler)
1368 process_sp->PopProcessIOHandler();
1372 void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1373 // At present the only thread event we handle is the Frame Changed event, and
1374 // all we do for that is just reprint the thread status for that thread.
1375 using namespace lldb;
1376 const uint32_t event_type = event_sp->GetType();
1377 const bool stop_format = true;
1378 if (event_type == Thread::eBroadcastBitStackChanged ||
1379 event_type == Thread::eBroadcastBitThreadSelected) {
1381 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1383 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1388 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1390 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1391 m_forward_listener_sp = listener_sp;
1394 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1395 m_forward_listener_sp.reset();
1398 void Debugger::DefaultEventHandler() {
1399 ListenerSP listener_sp(GetListener());
1400 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1401 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1402 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1403 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1404 Target::eBroadcastBitBreakpointChanged);
1406 BroadcastEventSpec process_event_spec(
1407 broadcaster_class_process,
1408 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1409 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1411 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1412 Thread::eBroadcastBitStackChanged |
1413 Thread::eBroadcastBitThreadSelected);
1415 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1417 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1418 process_event_spec);
1419 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1421 listener_sp->StartListeningForEvents(
1422 m_command_interpreter_up.get(),
1423 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1424 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1425 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1427 // Let the thread that spawned us know that we have started up and that we
1428 // are now listening to all required events so no events get missed
1429 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1434 if (listener_sp->GetEvent(event_sp, llvm::None)) {
1436 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1438 uint32_t event_type = event_sp->GetType();
1439 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1440 if (broadcaster_class == broadcaster_class_process) {
1441 HandleProcessEvent(event_sp);
1442 } else if (broadcaster_class == broadcaster_class_target) {
1443 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1445 HandleBreakpointEvent(event_sp);
1447 } else if (broadcaster_class == broadcaster_class_thread) {
1448 HandleThreadEvent(event_sp);
1449 } else if (broadcaster == m_command_interpreter_up.get()) {
1451 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1453 } else if (event_type &
1454 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1455 const char *data = reinterpret_cast<const char *>(
1456 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1457 if (data && data[0]) {
1458 StreamSP error_sp(GetAsyncErrorStream());
1460 error_sp->PutCString(data);
1464 } else if (event_type & CommandInterpreter::
1465 eBroadcastBitAsynchronousOutputData) {
1466 const char *data = reinterpret_cast<const char *>(
1467 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1468 if (data && data[0]) {
1469 StreamSP output_sp(GetAsyncOutputStream());
1471 output_sp->PutCString(data);
1479 if (m_forward_listener_sp)
1480 m_forward_listener_sp->AddEvent(event_sp);
1486 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1487 ((Debugger *)arg)->DefaultEventHandler();
1491 bool Debugger::StartEventHandlerThread() {
1492 if (!m_event_handler_thread.IsJoinable()) {
1493 // We must synchronize with the DefaultEventHandler() thread to ensure it
1494 // is up and running and listening to events before we return from this
1495 // function. We do this by listening to events for the
1496 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1497 ConstString full_name("lldb.debugger.event-handler");
1498 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
1499 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1500 eBroadcastBitEventThreadIsListening);
1503 full_name.GetLength() < llvm::get_max_thread_name_length()
1504 ? full_name.AsCString()
1505 : "dbg.evt-handler";
1507 // Use larger 8MB stack for this thread
1508 llvm::Expected<HostThread> event_handler_thread =
1509 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1510 g_debugger_event_thread_stack_bytes);
1512 if (event_handler_thread) {
1513 m_event_handler_thread = *event_handler_thread;
1515 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1516 "failed to launch host thread: {}",
1517 llvm::toString(event_handler_thread.takeError()));
1520 // Make sure DefaultEventHandler() is running and listening to events
1521 // before we return from this function. We are only listening for events of
1522 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1523 // event, we just need to wait an infinite amount of time for it (nullptr
1524 // timeout as the first parameter)
1525 lldb::EventSP event_sp;
1526 listener_sp->GetEvent(event_sp, llvm::None);
1528 return m_event_handler_thread.IsJoinable();
1531 void Debugger::StopEventHandlerThread() {
1532 if (m_event_handler_thread.IsJoinable()) {
1533 GetCommandInterpreter().BroadcastEvent(
1534 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1535 m_event_handler_thread.Join(nullptr);
1539 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1540 Debugger *debugger = (Debugger *)arg;
1541 debugger->ExecuteIOHandlers();
1542 debugger->StopEventHandlerThread();
1546 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1548 bool Debugger::StartIOHandlerThread() {
1549 if (!m_io_handler_thread.IsJoinable()) {
1550 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1551 "lldb.debugger.io-handler", IOHandlerThread, this,
1552 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1553 if (io_handler_thread) {
1554 m_io_handler_thread = *io_handler_thread;
1556 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1557 "failed to launch host thread: {}",
1558 llvm::toString(io_handler_thread.takeError()));
1561 return m_io_handler_thread.IsJoinable();
1564 void Debugger::StopIOHandlerThread() {
1565 if (m_io_handler_thread.IsJoinable()) {
1566 GetInputFile().Close();
1567 m_io_handler_thread.Join(nullptr);
1571 void Debugger::JoinIOHandlerThread() {
1572 if (HasIOHandlerThread()) {
1573 thread_result_t result;
1574 m_io_handler_thread.Join(&result);
1575 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1579 Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1580 Target *target = nullptr;
1581 if (!prefer_dummy) {
1582 target = m_target_list.GetSelectedTarget().get();
1587 return GetDummyTarget();
1590 Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1592 FileSpec repl_executable;
1594 if (language == eLanguageTypeUnknown) {
1595 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
1597 if (auto single_lang = repl_languages.GetSingularLanguage()) {
1598 language = *single_lang;
1599 } else if (repl_languages.Empty()) {
1600 err.SetErrorStringWithFormat(
1601 "LLDB isn't configured with REPL support for any languages.");
1604 err.SetErrorStringWithFormat(
1605 "Multiple possible REPL languages. Please specify a language.");
1610 Target *const target =
1611 nullptr; // passing in an empty target means the REPL must create one
1613 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1615 if (!err.Success()) {
1620 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1621 Language::GetNameForLanguageType(language));
1625 repl_sp->SetCompilerOptions(repl_options);