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
9#include "lldb/Core/Debugger.h"
10
11#include "lldb/Breakpoint/Breakpoint.h"
12#include "lldb/Core/DebuggerEvents.h"
13#include "lldb/Core/FormatEntity.h"
14#include "lldb/Core/Mangled.h"
15#include "lldb/Core/ModuleList.h"
16#include "lldb/Core/ModuleSpec.h"
17#include "lldb/Core/PluginManager.h"
18#include "lldb/Core/StreamAsynchronousIO.h"
19#include "lldb/Core/StreamFile.h"
20#include "lldb/DataFormatters/DataVisualization.h"
21#include "lldb/Expression/REPL.h"
22#include "lldb/Host/File.h"
23#include "lldb/Host/FileSystem.h"
24#include "lldb/Host/HostInfo.h"
25#include "lldb/Host/Terminal.h"
26#include "lldb/Host/ThreadLauncher.h"
27#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandReturnObject.h"
29#include "lldb/Interpreter/OptionValue.h"
30#include "lldb/Interpreter/OptionValueLanguage.h"
31#include "lldb/Interpreter/OptionValueProperties.h"
32#include "lldb/Interpreter/OptionValueSInt64.h"
33#include "lldb/Interpreter/OptionValueString.h"
34#include "lldb/Interpreter/Property.h"
35#include "lldb/Interpreter/ScriptInterpreter.h"
36#include "lldb/Symbol/Function.h"
37#include "lldb/Symbol/Symbol.h"
38#include "lldb/Symbol/SymbolContext.h"
39#include "lldb/Target/Language.h"
40#include "lldb/Target/Process.h"
41#include "lldb/Target/StructuredDataPlugin.h"
42#include "lldb/Target/Target.h"
43#include "lldb/Target/TargetList.h"
44#include "lldb/Target/Thread.h"
45#include "lldb/Target/ThreadList.h"
46#include "lldb/Utility/AnsiTerminal.h"
47#include "lldb/Utility/Event.h"
48#include "lldb/Utility/LLDBLog.h"
49#include "lldb/Utility/Listener.h"
50#include "lldb/Utility/Log.h"
51#include "lldb/Utility/Reproducer.h"
52#include "lldb/Utility/ReproducerProvider.h"
53#include "lldb/Utility/State.h"
54#include "lldb/Utility/Stream.h"
55#include "lldb/Utility/StreamString.h"
56
57#if defined(_WIN32)
58#include "lldb/Host/windows/PosixApi.h"
59#include "lldb/Host/windows/windows.h"
60#endif
61
62#include "llvm/ADT/None.h"
63#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/StringRef.h"
65#include "llvm/ADT/iterator.h"
66#include "llvm/Support/DynamicLibrary.h"
67#include "llvm/Support/FileSystem.h"
68#include "llvm/Support/Process.h"
69#include "llvm/Support/ThreadPool.h"
70#include "llvm/Support/Threading.h"
71#include "llvm/Support/raw_ostream.h"
72
73#include <cstdio>
74#include <cstdlib>
75#include <cstring>
76#include <list>
77#include <memory>
78#include <mutex>
79#include <set>
80#include <string>
81#include <system_error>
82
83// Includes for pipe()
84#if defined(_WIN32)
85#include <fcntl.h>
86#include <io.h>
87#else
88#include <unistd.h>
89#endif
90
91namespace lldb_private {
92class Address;
93}
94
95using namespace lldb;
96using namespace lldb_private;
97
98static lldb::user_id_t g_unique_id = 1;
99static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
100
101#pragma mark Static Functions
102
103typedef std::vector<DebuggerSP> DebuggerList;
104static std::recursive_mutex *g_debugger_list_mutex_ptr =
105 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
106static DebuggerList *g_debugger_list_ptr =
107 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
108static llvm::ThreadPool *g_thread_pool = nullptr;
109
110static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
111 {
112 Debugger::eStopDisassemblyTypeNever,
113 "never",
114 "Never show disassembly when displaying a stop context.",
115 },
116 {
117 Debugger::eStopDisassemblyTypeNoDebugInfo,
118 "no-debuginfo",
119 "Show disassembly when there is no debug information.",
120 },
121 {
122 Debugger::eStopDisassemblyTypeNoSource,
123 "no-source",
124 "Show disassembly when there is no source information, or the source "
125 "file "
126 "is missing when displaying a stop context.",
127 },
128 {
129 Debugger::eStopDisassemblyTypeAlways,
130 "always",
131 "Always show disassembly when displaying a stop context.",
132 },
133};
134
135static constexpr OptionEnumValueElement g_language_enumerators[] = {
136 {
137 eScriptLanguageNone,
138 "none",
139 "Disable scripting languages.",
140 },
141 {
142 eScriptLanguagePython,
143 "python",
144 "Select python as the default scripting language.",
145 },
146 {
147 eScriptLanguageDefault,
148 "default",
149 "Select the lldb default as the default scripting language.",
150 },
151};
152
153static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
154 {
155 eStopShowColumnAnsiOrCaret,
156 "ansi-or-caret",
157 "Highlight the stop column with ANSI terminal codes when color/ANSI "
158 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
159 "as if \"caret-only\" mode was selected.",
160 },
161 {
162 eStopShowColumnAnsi,
163 "ansi",
164 "Highlight the stop column with ANSI terminal codes when running LLDB "
165 "with color/ANSI enabled.",
166 },
167 {
168 eStopShowColumnCaret,
169 "caret",
170 "Highlight the stop column with a caret character (^) underneath the "
171 "stop column. This method introduces a new line in source listings "
172 "that display thread stop locations.",
173 },
174 {
175 eStopShowColumnNone,
176 "none",
177 "Do not highlight the stop column.",
178 },
179};
180
181#define LLDB_PROPERTIES_debugger
182#include "CoreProperties.inc"
183
184enum {
185#define LLDB_PROPERTIES_debugger
186#include "CorePropertiesEnum.inc"
187};
188
189LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
190
191Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
192 VarSetOperationType op,
193 llvm::StringRef property_path,
194 llvm::StringRef value) {
195 bool is_load_script =
196 (property_path == "target.load-script-from-symbol-file");
197 // These properties might change how we visualize data.
198 bool invalidate_data_vis = (property_path == "escape-non-printables");
199 invalidate_data_vis |=
200 (property_path == "target.max-zero-padding-in-float-format");
201 if (invalidate_data_vis) {
202 DataVisualization::ForceUpdate();
203 }
204
205 TargetSP target_sp;
206 LoadScriptFromSymFile load_script_old_value = eLoadScriptFromSymFileFalse;
207 if (is_load_script && exe_ctx->GetTargetSP()) {
208 target_sp = exe_ctx->GetTargetSP();
209 load_script_old_value =
210 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
211 }
212 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
213 if (error.Success()) {
214 // FIXME it would be nice to have "on-change" callbacks for properties
215 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
216 llvm::StringRef new_prompt = GetPrompt();
217 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes(
218 new_prompt, GetUseColor());
219 if (str.length())
220 new_prompt = str;
221 GetCommandInterpreter().UpdatePrompt(new_prompt);
222 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
223 auto prompt_change_event_sp = std::make_shared<Event>(
224 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
225 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
226 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
227 // use-color changed. Ping the prompt so it can reset the ansi terminal
228 // codes.
229 SetPrompt(GetPrompt());
230 } else if (property_path == g_debugger_properties[ePropertyUseSourceCache].name) {
231 // use-source-cache changed. Wipe out the cache contents if it was disabled.
232 if (!GetUseSourceCache()) {
233 m_source_file_cache.Clear();
234 }
235 } else if (is_load_script && target_sp &&
236 load_script_old_value == eLoadScriptFromSymFileWarn) {
237 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
238 eLoadScriptFromSymFileTrue) {
239 std::list<Status> errors;
240 StreamString feedback_stream;
241 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
242 Stream &s = GetErrorStream();
243 for (auto error : errors) {
244 s.Printf("%s\n", error.AsCString());
245 }
246 if (feedback_stream.GetSize())
247 s.PutCString(feedback_stream.GetString());
248 }
249 }
250 }
251 }
252 return error;
253}
254
255bool Debugger::GetAutoConfirm() const {
256 const uint32_t idx = ePropertyAutoConfirm;
257 return m_collection_sp->GetPropertyAtIndexAsBoolean(
258 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
259}
260
261const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
262 const uint32_t idx = ePropertyDisassemblyFormat;
263 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
264}
265
266const FormatEntity::Entry *Debugger::GetFrameFormat() const {
267 const uint32_t idx = ePropertyFrameFormat;
268 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
269}
270
271const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
272 const uint32_t idx = ePropertyFrameFormatUnique;
273 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
274}
275
276uint32_t Debugger::GetStopDisassemblyMaxSize() const {
277 const uint32_t idx = ePropertyStopDisassemblyMaxSize;
278 return m_collection_sp->GetPropertyAtIndexAsUInt64(
279 nullptr, idx, g_debugger_properties[idx].default_uint_value);
280}
281
282bool Debugger::GetNotifyVoid() const {
283 const uint32_t idx = ePropertyNotiftVoid;
284 return m_collection_sp->GetPropertyAtIndexAsBoolean(
285 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
286}
287
288llvm::StringRef Debugger::GetPrompt() const {
289 const uint32_t idx = ePropertyPrompt;
290 return m_collection_sp->GetPropertyAtIndexAsString(
291 nullptr, idx, g_debugger_properties[idx].default_cstr_value);
292}
293
294void Debugger::SetPrompt(llvm::StringRef p) {
295 const uint32_t idx = ePropertyPrompt;
296 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
297 llvm::StringRef new_prompt = GetPrompt();
298 std::string str =
299 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
300 if (str.length())
301 new_prompt = str;
302 GetCommandInterpreter().UpdatePrompt(new_prompt);
303}
304
305llvm::StringRef Debugger::GetReproducerPath() const {
306 auto &r = repro::Reproducer::Instance();
307 return r.GetReproducerPath().GetPathAsConstString().AsCString();
308}
309
310const FormatEntity::Entry *Debugger::GetThreadFormat() const {
311 const uint32_t idx = ePropertyThreadFormat;
312 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
313}
314
315const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
316 const uint32_t idx = ePropertyThreadStopFormat;
317 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
318}
319
320lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
321 const uint32_t idx = ePropertyScriptLanguage;
322 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
323 nullptr, idx, g_debugger_properties[idx].default_uint_value);
324}
325
326bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
327 const uint32_t idx = ePropertyScriptLanguage;
328 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
329 script_lang);
330}
331
332lldb::LanguageType Debugger::GetREPLLanguage() const {
333 const uint32_t idx = ePropertyREPLLanguage;
334 OptionValueLanguage *value =
335 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(nullptr, idx);
336 if (value)
337 return value->GetCurrentValue();
338 return LanguageType();
339}
340
341bool Debugger::SetREPLLanguage(lldb::LanguageType repl_lang) {
342 const uint32_t idx = ePropertyREPLLanguage;
343 return m_collection_sp->SetPropertyAtIndexAsLanguage(nullptr, idx, repl_lang);
344}
345
346uint32_t Debugger::GetTerminalWidth() const {
347 const uint32_t idx = ePropertyTerminalWidth;
348 return m_collection_sp->GetPropertyAtIndexAsSInt64(
349 nullptr, idx, g_debugger_properties[idx].default_uint_value);
350}
351
352bool Debugger::SetTerminalWidth(uint32_t term_width) {
353 if (auto handler_sp = m_io_handler_stack.Top())
354 handler_sp->TerminalSizeChanged();
355
356 const uint32_t idx = ePropertyTerminalWidth;
357 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
358}
359
360bool Debugger::GetUseExternalEditor() const {
361 const uint32_t idx = ePropertyUseExternalEditor;
362 return m_collection_sp->GetPropertyAtIndexAsBoolean(
363 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
364}
365
366bool Debugger::SetUseExternalEditor(bool b) {
367 const uint32_t idx = ePropertyUseExternalEditor;
368 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
369}
370
371bool Debugger::GetUseColor() const {
372 const uint32_t idx = ePropertyUseColor;
373 return m_collection_sp->GetPropertyAtIndexAsBoolean(
374 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
375}
376
377bool Debugger::SetUseColor(bool b) {
378 const uint32_t idx = ePropertyUseColor;
379 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
380 SetPrompt(GetPrompt());
381 return ret;
382}
383
384bool Debugger::GetShowProgress() const {
385 const uint32_t idx = ePropertyShowProgress;
386 return m_collection_sp->GetPropertyAtIndexAsBoolean(
387 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
388}
389
390bool Debugger::SetShowProgress(bool show_progress) {
391 const uint32_t idx = ePropertyShowProgress;
392 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx,
393 show_progress);
394}
395
396llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const {
397 const uint32_t idx = ePropertyShowProgressAnsiPrefix;
398 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
399}
400
401llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const {
402 const uint32_t idx = ePropertyShowProgressAnsiSuffix;
403 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
404}
405
406bool Debugger::GetUseAutosuggestion() const {
407 const uint32_t idx = ePropertyShowAutosuggestion;
408 return m_collection_sp->GetPropertyAtIndexAsBoolean(
409 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
410}
411
412llvm::StringRef Debugger::GetAutosuggestionAnsiPrefix() const {
413 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix;
414 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
415}
416
417llvm::StringRef Debugger::GetAutosuggestionAnsiSuffix() const {
418 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix;
419 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
420}
421
422bool Debugger::GetUseSourceCache() const {
423 const uint32_t idx = ePropertyUseSourceCache;
424 return m_collection_sp->GetPropertyAtIndexAsBoolean(
425 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
426}
427
428bool Debugger::SetUseSourceCache(bool b) {
429 const uint32_t idx = ePropertyUseSourceCache;
430 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
431 if (!ret) {
432 m_source_file_cache.Clear();
433 }
434 return ret;
435}
436bool Debugger::GetHighlightSource() const {
437 const uint32_t idx = ePropertyHighlightSource;
438 return m_collection_sp->GetPropertyAtIndexAsBoolean(
439 nullptr, idx, g_debugger_properties[idx].default_uint_value);
440}
441
442StopShowColumn Debugger::GetStopShowColumn() const {
443 const uint32_t idx = ePropertyStopShowColumn;
444 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
445 nullptr, idx, g_debugger_properties[idx].default_uint_value);
446}
447
448llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
449 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
450 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
451}
452
453llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
454 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
455 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
456}
457
458llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const {
459 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
460 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
461}
462
463llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const {
464 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
465 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
466}
467
468uint32_t Debugger::GetStopSourceLineCount(bool before) const {
469 const uint32_t idx =
470 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
471 return m_collection_sp->GetPropertyAtIndexAsSInt64(
472 nullptr, idx, g_debugger_properties[idx].default_uint_value);
473}
474
475Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
476 const uint32_t idx = ePropertyStopDisassemblyDisplay;
477 return (Debugger::StopDisassemblyType)
478 m_collection_sp->GetPropertyAtIndexAsEnumeration(
479 nullptr, idx, g_debugger_properties[idx].default_uint_value);
480}
481
482uint32_t Debugger::GetDisassemblyLineCount() const {
483 const uint32_t idx = ePropertyStopDisassemblyCount;
484 return m_collection_sp->GetPropertyAtIndexAsSInt64(
485 nullptr, idx, g_debugger_properties[idx].default_uint_value);
486}
487
488bool Debugger::GetAutoOneLineSummaries() const {
489 const uint32_t idx = ePropertyAutoOneLineSummaries;
490 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
491}
492
493bool Debugger::GetEscapeNonPrintables() const {
494 const uint32_t idx = ePropertyEscapeNonPrintables;
495 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
496}
497
498bool Debugger::GetAutoIndent() const {
499 const uint32_t idx = ePropertyAutoIndent;
500 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
501}
502
503bool Debugger::SetAutoIndent(bool b) {
504 const uint32_t idx = ePropertyAutoIndent;
505 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
506}
507
508bool Debugger::GetPrintDecls() const {
509 const uint32_t idx = ePropertyPrintDecls;
510 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
511}
512
513bool Debugger::SetPrintDecls(bool b) {
514 const uint32_t idx = ePropertyPrintDecls;
515 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
516}
517
518uint32_t Debugger::GetTabSize() const {
519 const uint32_t idx = ePropertyTabSize;
520 return m_collection_sp->GetPropertyAtIndexAsUInt64(
521 nullptr, idx, g_debugger_properties[idx].default_uint_value);
522}
523
524bool Debugger::SetTabSize(uint32_t tab_size) {
525 const uint32_t idx = ePropertyTabSize;
526 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
527}
528
529#pragma mark Debugger
530
531// const DebuggerPropertiesSP &
532// Debugger::GetSettings() const
533//{
534// return m_properties_sp;
535//}
536//
537
538void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
539 assert(g_debugger_list_ptr == nullptr &&
540 "Debugger::Initialize called more than once!");
541 g_debugger_list_mutex_ptr = new std::recursive_mutex();
542 g_debugger_list_ptr = new DebuggerList();
543 g_thread_pool = new llvm::ThreadPool(llvm::optimal_concurrency());
544 g_load_plugin_callback = load_plugin_callback;
545}
546
547void Debugger::Terminate() {
548 assert(g_debugger_list_ptr &&
549 "Debugger::Terminate called without a matching Debugger::Initialize!");
550
551 if (g_thread_pool) {
552 // The destructor will wait for all the threads to complete.
553 delete g_thread_pool;
554 }
555
556 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
557 // Clear our global list of debugger objects
558 {
559 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
560 for (const auto &debugger : *g_debugger_list_ptr)
561 debugger->Clear();
562 g_debugger_list_ptr->clear();
563 }
564 }
565}
566
567void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
568
569void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
570
571bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
572 if (g_load_plugin_callback) {
573 llvm::sys::DynamicLibrary dynlib =
574 g_load_plugin_callback(shared_from_this(), spec, error);
575 if (dynlib.isValid()) {
576 m_loaded_plugins.push_back(dynlib);
577 return true;
578 }
579 } else {
580 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
581 // if the public API layer isn't available (code is linking against all of
582 // the internal LLDB static libraries), then we can't load plugins
583 error.SetErrorString("Public API layer is not available");
584 }
585 return false;
586}
587
588static FileSystem::EnumerateDirectoryResult
589LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
590 llvm::StringRef path) {
591 Status error;
592
593 static ConstString g_dylibext(".dylib");
594 static ConstString g_solibext(".so");
595
596 if (!baton)
597 return FileSystem::eEnumerateDirectoryResultQuit;
598
599 Debugger *debugger = (Debugger *)baton;
600
601 namespace fs = llvm::sys::fs;
602 // If we have a regular file, a symbolic link or unknown file type, try and
603 // process the file. We must handle unknown as sometimes the directory
604 // enumeration might be enumerating a file system that doesn't have correct
605 // file type information.
606 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
607 ft == fs::file_type::type_unknown) {
608 FileSpec plugin_file_spec(path);
609 FileSystem::Instance().Resolve(plugin_file_spec);
610
611 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
612 plugin_file_spec.GetFileNameExtension() != g_solibext) {
613 return FileSystem::eEnumerateDirectoryResultNext;
614 }
615
616 Status plugin_load_error;
617 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
618
619 return FileSystem::eEnumerateDirectoryResultNext;
620 } else if (ft == fs::file_type::directory_file ||
621 ft == fs::file_type::symlink_file ||
622 ft == fs::file_type::type_unknown) {
623 // Try and recurse into anything that a directory or symbolic link. We must
624 // also do this for unknown as sometimes the directory enumeration might be
625 // enumerating a file system that doesn't have correct file type
626 // information.
627 return FileSystem::eEnumerateDirectoryResultEnter;
628 }
629
630 return FileSystem::eEnumerateDirectoryResultNext;
631}
632
633void Debugger::InstanceInitialize() {
634 const bool find_directories = true;
635 const bool find_files = true;
636 const bool find_other = true;
637 char dir_path[PATH_MAX];
638 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
639 if (FileSystem::Instance().Exists(dir_spec) &&
640 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
641 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
642 find_files, find_other,
643 LoadPluginCallback, this);
644 }
645 }
646
647 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
648 if (FileSystem::Instance().Exists(dir_spec) &&
649 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
650 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
651 find_files, find_other,
652 LoadPluginCallback, this);
653 }
654 }
655
656 PluginManager::DebuggerInitialize(*this);
657}
658
659DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
660 void *baton) {
661 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
662 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
663 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
664 g_debugger_list_ptr->push_back(debugger_sp);
665 }
666 debugger_sp->InstanceInitialize();
667 return debugger_sp;
668}
669
670void Debugger::Destroy(DebuggerSP &debugger_sp) {
671 if (!debugger_sp)
672 return;
673
674 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
675
676 if (cmd_interpreter.GetSaveSessionOnQuit()) {
677 CommandReturnObject result(debugger_sp->GetUseColor());
678 cmd_interpreter.SaveTranscript(result);
679 if (result.Succeeded())
680 (*debugger_sp->GetAsyncOutputStream()) << result.GetOutputData() << '\n';
681 else
682 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorData() << '\n';
683 }
684
685 debugger_sp->Clear();
686
687 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
688 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
689 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
690 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
691 if ((*pos).get() == debugger_sp.get()) {
692 g_debugger_list_ptr->erase(pos);
693 return;
694 }
695 }
696 }
697}
698
699DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
700 DebuggerSP debugger_sp;
701 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
702 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
703 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
704 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
705 if ((*pos)->m_instance_name == instance_name) {
706 debugger_sp = *pos;
707 break;
708 }
709 }
710 }
711 return debugger_sp;
712}
713
714TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
715 TargetSP target_sp;
716 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
717 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
718 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
719 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
720 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
721 if (target_sp)
722 break;
723 }
724 }
725 return target_sp;
726}
727
728TargetSP Debugger::FindTargetWithProcess(Process *process) {
729 TargetSP target_sp;
730 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
731 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
732 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
733 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
734 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
735 if (target_sp)
736 break;
737 }
738 }
739 return target_sp;
740}
741
742ConstString Debugger::GetStaticBroadcasterClass() {
743 static ConstString class_name("lldb.debugger");
744 return class_name;
745}
746
747Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
748 : UserID(g_unique_id++),
749 Properties(std::make_shared<OptionValueProperties>()),
750 m_input_file_sp(std::make_shared<NativeFile>(stdin, false)),
751 m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)),
752 m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)),
753 m_input_recorder(nullptr),
754 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
755 m_terminal_state(), m_target_list(*this), m_platform_list(),
756 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
757 m_source_manager_up(), m_source_file_cache(),
758 m_command_interpreter_up(
759 std::make_unique<CommandInterpreter>(*this, false)),
760 m_io_handler_stack(), m_instance_name(), m_loaded_plugins(),
761 m_event_handler_thread(), m_io_handler_thread(),
762 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
763 m_broadcaster(m_broadcaster_manager_sp,
764 GetStaticBroadcasterClass().AsCString()),
765 m_forward_listener_sp(), m_clear_once() {
766 m_instance_name.SetString(llvm::formatv("debugger_{0}", GetID()).str());
767 if (log_callback)
768 m_callback_handler_sp =
769 std::make_shared<CallbackLogHandler>(log_callback, baton);
770 m_command_interpreter_up->Initialize();
771 // Always add our default platform to the platform list
772 PlatformSP default_platform_sp(Platform::GetHostPlatform());
773 assert(default_platform_sp);
774 m_platform_list.Append(default_platform_sp, true);
775
776 // Create the dummy target.
777 {
778 ArchSpec arch(Target::GetDefaultArchitecture());
779 if (!arch.IsValid())
780 arch = HostInfo::GetArchitecture();
781 assert(arch.IsValid() && "No valid default or host archspec");
782 const bool is_dummy_target = true;
783 m_dummy_target_sp.reset(
784 new Target(*this, arch, default_platform_sp, is_dummy_target));
785 }
786 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
787
788 m_collection_sp->Initialize(g_debugger_properties);
789 m_collection_sp->AppendProperty(
790 ConstString("target"),
791 ConstString("Settings specify to debugging targets."), true,
792 Target::GetGlobalProperties().GetValueProperties());
793 m_collection_sp->AppendProperty(
794 ConstString("platform"), ConstString("Platform settings."), true,
795 Platform::GetGlobalPlatformProperties().GetValueProperties());
796 m_collection_sp->AppendProperty(
797 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
798 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
799 if (m_command_interpreter_up) {
800 m_collection_sp->AppendProperty(
801 ConstString("interpreter"),
802 ConstString("Settings specify to the debugger's command interpreter."),
803 true, m_command_interpreter_up->GetValueProperties());
804 }
805 OptionValueSInt64 *term_width =
806 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
807 nullptr, ePropertyTerminalWidth);
808 term_width->SetMinimumValue(10);
809 term_width->SetMaximumValue(1024);
810
811 // Turn off use-color if this is a dumb terminal.
812 const char *term = getenv("TERM");
813 if (term && !strcmp(term, "dumb"))
814 SetUseColor(false);
815 // Turn off use-color if we don't write to a terminal with color support.
816 if (!GetOutputFile().GetIsTerminalWithColors())
817 SetUseColor(false);
818
819#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
820 // Enabling use of ANSI color codes because LLDB is using them to highlight
821 // text.
822 llvm::sys::Process::UseANSIEscapeCodes(true);
823#endif
824}
825
826Debugger::~Debugger() { Clear(); }
827
828void Debugger::Clear() {
829 // Make sure we call this function only once. With the C++ global destructor
830 // chain having a list of debuggers and with code that can be running on
831 // other threads, we need to ensure this doesn't happen multiple times.
832 //
833 // The following functions call Debugger::Clear():
834 // Debugger::~Debugger();
835 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
836 // static void Debugger::Terminate();
837 llvm::call_once(m_clear_once, [this]() {
838 ClearIOHandlers();
839 StopIOHandlerThread();
840 StopEventHandlerThread();
841 m_listener_sp->Clear();
842 for (TargetSP target_sp : m_target_list.Targets()) {
843 if (target_sp) {
844 if (ProcessSP process_sp = target_sp->GetProcessSP())
845 process_sp->Finalize();
846 target_sp->Destroy();
847 }
848 }
849 m_broadcaster_manager_sp->Clear();
850
851 // Close the input file _before_ we close the input read communications
852 // class as it does NOT own the input file, our m_input_file does.
853 m_terminal_state.Clear();
854 GetInputFile().Close();
855
856 m_command_interpreter_up->Clear();
857 });
858}
859
860bool Debugger::GetCloseInputOnEOF() const {
861 // return m_input_comm.GetCloseOnEOF();
862 return false;
863}
864
865void Debugger::SetCloseInputOnEOF(bool b) {
866 // m_input_comm.SetCloseOnEOF(b);
867}
868
869bool Debugger::GetAsyncExecution() {
870 return !m_command_interpreter_up->GetSynchronous();
871}
872
873void Debugger::SetAsyncExecution(bool async_execution) {
874 m_command_interpreter_up->SetSynchronous(!async_execution);
875}
876
877repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
878
879static inline int OpenPipe(int fds[2], std::size_t size) {
880#ifdef _WIN32
881 return _pipe(fds, size, O_BINARY);
882#else
883 (void)size;
884 return pipe(fds);
885#endif
886}
887
888Status Debugger::SetInputString(const char *data) {
889 Status result;
890 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
891 int fds[2] = {-1, -1};
892
893 if (data == nullptr) {
894 result.SetErrorString("String data is null");
895 return result;
896 }
897
898 size_t size = strlen(data);
899 if (size == 0) {
900 result.SetErrorString("String data is empty");
901 return result;
902 }
903
904 if (OpenPipe(fds, size) != 0) {
905 result.SetErrorString(
906 "can't create pipe file descriptors for LLDB commands");
907 return result;
908 }
909
910 int r = write(fds[WRITE], data, size);
911 (void)r;
912 // Close the write end of the pipe, so that the command interpreter will exit
913 // when it consumes all the data.
914 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
915
916 // Open the read file descriptor as a FILE * that we can return as an input
917 // handle.
918 FILE *commands_file = fdopen(fds[READ], "rb");
919 if (commands_file == nullptr) {
920 result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) "
921 "when trying to open LLDB commands pipe",
922 fds[READ], errno);
923 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
924 return result;
925 }
926
927 return SetInputFile(
928 (FileSP)std::make_shared<NativeFile>(commands_file, true));
929}
930
931Status Debugger::SetInputFile(FileSP file_sp) {
932 Status error;
933 repro::DataRecorder *recorder = nullptr;
934 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator())
935 recorder = g->GetOrCreate<repro::CommandProvider>().GetNewRecorder();
936
937 static std::unique_ptr<repro::MultiLoader<repro::CommandProvider>> loader =
938 repro::MultiLoader<repro::CommandProvider>::Create(
939 repro::Reproducer::Instance().GetLoader());
940 if (loader) {
941 llvm::Optional<std::string> nextfile = loader->GetNextFile();
942 FILE *fh = nextfile ? FileSystem::Instance().Fopen(nextfile->c_str(), "r")
943 : nullptr;
944 // FIXME Jonas Devlieghere: shouldn't this error be propagated out to the
945 // reproducer somehow if fh is NULL?
946 if (fh) {
947 file_sp = std::make_shared<NativeFile>(fh, true);
948 }
949 }
950
951 if (!file_sp || !file_sp->IsValid()) {
952 error.SetErrorString("invalid file");
953 return error;
954 }
955
956 SetInputFile(file_sp, recorder);
957 return error;
958}
959
960void Debugger::SetInputFile(FileSP file_sp, repro::DataRecorder *recorder) {
961 assert(file_sp && file_sp->IsValid());
962 m_input_recorder = recorder;
963 m_input_file_sp = std::move(file_sp);
964 // Save away the terminal state if that is relevant, so that we can restore
965 // it in RestoreInputState.
966 SaveInputTerminalState();
967}
968
969void Debugger::SetOutputFile(FileSP file_sp) {
970 assert(file_sp && file_sp->IsValid());
971 m_output_stream_sp = std::make_shared<StreamFile>(file_sp);
972}
973
974void Debugger::SetErrorFile(FileSP file_sp) {
975 assert(file_sp && file_sp->IsValid());
976 m_error_stream_sp = std::make_shared<StreamFile>(file_sp);
977}
978
979void Debugger::SaveInputTerminalState() {
980 int fd = GetInputFile().GetDescriptor();
981 if (fd != File::kInvalidDescriptor)
982 m_terminal_state.Save(fd, true);
983}
984
985void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
986
987ExecutionContext Debugger::GetSelectedExecutionContext() {
988 bool adopt_selected = true;
989 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected);
990 return ExecutionContext(exe_ctx_ref);
991}
992
993void Debugger::DispatchInputInterrupt() {
994 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
995 IOHandlerSP reader_sp(m_io_handler_stack.Top());
996 if (reader_sp)
997 reader_sp->Interrupt();
998}
999
1000void Debugger::DispatchInputEndOfFile() {
1001 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1002 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1003 if (reader_sp)
1004 reader_sp->GotEOF();
1005}
1006
1007void Debugger::ClearIOHandlers() {
1008 // The bottom input reader should be the main debugger input reader. We do
1009 // not want to close that one here.
1010 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1011 while (m_io_handler_stack.GetSize() > 1) {
1012 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1013 if (reader_sp)
1014 PopIOHandler(reader_sp);
1015 }
1016}
1017
1018void Debugger::RunIOHandlers() {
1019 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1020 while (true) {
1021 if (!reader_sp)
1022 break;
1023
1024 reader_sp->Run();
1025 {
1026 std::lock_guard<std::recursive_mutex> guard(
1027 m_io_handler_synchronous_mutex);
1028
1029 // Remove all input readers that are done from the top of the stack
1030 while (true) {
1031 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1032 if (top_reader_sp && top_reader_sp->GetIsDone())
1033 PopIOHandler(top_reader_sp);
1034 else
1035 break;
1036 }
1037 reader_sp = m_io_handler_stack.Top();
1038 }
1039 }
1040 ClearIOHandlers();
1041}
1042
1043void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) {
1044 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1045
1046 PushIOHandler(reader_sp);
1047 IOHandlerSP top_reader_sp = reader_sp;
1048
1049 while (top_reader_sp) {
1050 if (!top_reader_sp)
1051 break;
1052
1053 top_reader_sp->Run();
1054
1055 // Don't unwind past the starting point.
1056 if (top_reader_sp.get() == reader_sp.get()) {
1057 if (PopIOHandler(reader_sp))
1058 break;
1059 }
1060
1061 // If we pushed new IO handlers, pop them if they're done or restart the
1062 // loop to run them if they're not.
1063 while (true) {
1064 top_reader_sp = m_io_handler_stack.Top();
1065 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1066 PopIOHandler(top_reader_sp);
1067 // Don't unwind past the starting point.
1068 if (top_reader_sp.get() == reader_sp.get())
1069 return;
1070 } else {
1071 break;
1072 }
1073 }
1074 }
1075}
1076
1077bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
1078 return m_io_handler_stack.IsTop(reader_sp);
1079}
1080
1081bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
1082 IOHandler::Type second_top_type) {
1083 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1084}
1085
1086void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1087 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1088 if (!printed) {
1089 lldb::StreamFileSP stream =
1090 is_stdout ? m_output_stream_sp : m_error_stream_sp;
1091 stream->Write(s, len);
1092 }
1093}
1094
1095ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1096 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1097}
1098
1099const char *Debugger::GetIOHandlerCommandPrefix() {
1100 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1101}
1102
1103const char *Debugger::GetIOHandlerHelpPrologue() {
1104 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1105}
1106
1107bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) {
1108 return PopIOHandler(reader_sp);
1109}
1110
1111void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp,
1112 bool cancel_top_handler) {
1113 PushIOHandler(reader_sp, cancel_top_handler);
1114}
1115
1116void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out,
1117 StreamFileSP &err) {
1118 // Before an IOHandler runs, it must have in/out/err streams. This function
1119 // is called when one ore more of the streams are nullptr. We use the top
1120 // input reader's in/out/err streams, or fall back to the debugger file
1121 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1122
1123 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1124 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1125 // If no STDIN has been set, then set it appropriately
1126 if (!in || !in->IsValid()) {
1127 if (top_reader_sp)
1128 in = top_reader_sp->GetInputFileSP();
1129 else
1130 in = GetInputFileSP();
1131 // If there is nothing, use stdin
1132 if (!in)
1133 in = std::make_shared<NativeFile>(stdin, false);
1134 }
1135 // If no STDOUT has been set, then set it appropriately
1136 if (!out || !out->GetFile().IsValid()) {
1137 if (top_reader_sp)
1138 out = top_reader_sp->GetOutputStreamFileSP();
1139 else
1140 out = GetOutputStreamSP();
1141 // If there is nothing, use stdout
1142 if (!out)
1143 out = std::make_shared<StreamFile>(stdout, false);
1144 }
1145 // If no STDERR has been set, then set it appropriately
1146 if (!err || !err->GetFile().IsValid()) {
1147 if (top_reader_sp)
1148 err = top_reader_sp->GetErrorStreamFileSP();
1149 else
1150 err = GetErrorStreamSP();
1151 // If there is nothing, use stderr
1152 if (!err)
1153 err = std::make_shared<StreamFile>(stderr, false);
1154 }
1155}
1156
1157void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1158 bool cancel_top_handler) {
1159 if (!reader_sp)
1160 return;
1161
1162 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1163
1164 // Get the current top input reader...
1165 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1166
1167 // Don't push the same IO handler twice...
1168 if (reader_sp == top_reader_sp)
1169 return;
1170
1171 // Push our new input reader
1172 m_io_handler_stack.Push(reader_sp);
1173 reader_sp->Activate();
1174
1175 // Interrupt the top input reader to it will exit its Run() function and let
1176 // this new input reader take over
1177 if (top_reader_sp) {
1178 top_reader_sp->Deactivate();
1179 if (cancel_top_handler)
1180 top_reader_sp->Cancel();
1181 }
1182}
1183
1184bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1185 if (!pop_reader_sp)
1186 return false;
1187
1188 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1189
1190 // The reader on the stop of the stack is done, so let the next read on the
1191 // stack refresh its prompt and if there is one...
1192 if (m_io_handler_stack.IsEmpty())
1193 return false;
1194
1195 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1196
1197 if (pop_reader_sp != reader_sp)
1198 return false;
1199
1200 reader_sp->Deactivate();
1201 reader_sp->Cancel();
1202 m_io_handler_stack.Pop();
1203
1204 reader_sp = m_io_handler_stack.Top();
1205 if (reader_sp)
1206 reader_sp->Activate();
1207
1208 return true;
1209}
1210
1211StreamSP Debugger::GetAsyncOutputStream() {
1212 return std::make_shared<StreamAsynchronousIO>(*this, true, GetUseColor());
1213}
1214
1215StreamSP Debugger::GetAsyncErrorStream() {
1216 return std::make_shared<StreamAsynchronousIO>(*this, false, GetUseColor());
1217}
1218
1219size_t Debugger::GetNumDebuggers() {
1220 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1221 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1222 return g_debugger_list_ptr->size();
1223 }
1224 return 0;
1225}
1226
1227lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1228 DebuggerSP debugger_sp;
1229
1230 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1231 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1232 if (index < g_debugger_list_ptr->size())
1233 debugger_sp = g_debugger_list_ptr->at(index);
1234 }
1235
1236 return debugger_sp;
1237}
1238
1239DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1240 DebuggerSP debugger_sp;
1241
1242 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1243 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1244 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1245 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1246 if ((*pos)->GetID() == id) {
1247 debugger_sp = *pos;
1248 break;
1249 }
1250 }
1251 }
1252 return debugger_sp;
1253}
1254
1255bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1256 const SymbolContext *sc,
1257 const SymbolContext *prev_sc,
1258 const ExecutionContext *exe_ctx,
1259 const Address *addr, Stream &s) {
1260 FormatEntity::Entry format_entry;
1261
1262 if (format == nullptr) {
1263 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1264 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1265 if (format == nullptr) {
1266 FormatEntity::Parse("${addr}: ", format_entry);
1267 format = &format_entry;
1268 }
1269 }
1270 bool function_changed = false;
1271 bool initial_function = false;
1272 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1273 if (sc && (sc->function || sc->symbol)) {
1274 if (prev_sc->symbol && sc->symbol) {
1275 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1276 prev_sc->symbol->GetType())) {
1277 function_changed = true;
1278 }
1279 } else if (prev_sc->function && sc->function) {
1280 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1281 function_changed = true;
1282 }
1283 }
1284 }
1285 }
1286 // The first context on a list of instructions will have a prev_sc that has
1287 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1288 // would return false. But we do get a prev_sc pointer.
1289 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1290 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1291 initial_function = true;
1292 }
1293 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1294 function_changed, initial_function);
1295}
1296
1297void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1298 void *baton) {
1299 // For simplicity's sake, I am not going to deal with how to close down any
1300 // open logging streams, I just redirect everything from here on out to the
1301 // callback.
1302 m_callback_handler_sp =
1303 std::make_shared<CallbackLogHandler>(log_callback, baton);
1304}
1305
1306static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1307 const std::string &message,
1308 uint64_t completed, uint64_t total,
1309 bool is_debugger_specific) {
1310 // Only deliver progress events if we have any progress listeners.
1311 const uint32_t event_type = Debugger::eBroadcastBitProgress;
1312 if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type))
1313 return;
1314 EventSP event_sp(new Event(
1315 event_type, new ProgressEventData(progress_id, message, completed, total,
1316 is_debugger_specific)));
1317 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1318}
1319
1320void Debugger::ReportProgress(uint64_t progress_id, const std::string &message,
1321 uint64_t completed, uint64_t total,
1322 llvm::Optional<lldb::user_id_t> debugger_id) {
1323 // Check if this progress is for a specific debugger.
1324 if (debugger_id) {
1325 // It is debugger specific, grab it and deliver the event if the debugger
1326 // still exists.
1327 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1328 if (debugger_sp)
1329 PrivateReportProgress(*debugger_sp, progress_id, message, completed,
1330 total, /*is_debugger_specific*/ true);
1331 return;
1332 }
1333 // The progress event is not debugger specific, iterate over all debuggers
1334 // and deliver a progress event to each one.
1335 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1336 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1337 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1338 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1339 PrivateReportProgress(*(*pos), progress_id, message, completed, total,
1340 /*is_debugger_specific*/ false);
1341 }
1342}
1343
1344static void PrivateReportDiagnostic(Debugger &debugger,
1345 DiagnosticEventData::Type type,
1346 std::string message,
1347 bool debugger_specific) {
1348 uint32_t event_type = 0;
1349 switch (type) {
1350 case DiagnosticEventData::Type::Warning:
1351 event_type = Debugger::eBroadcastBitWarning;
1352 break;
1353 case DiagnosticEventData::Type::Error:
1354 event_type = Debugger::eBroadcastBitError;
1355 break;
1356 }
1357
1358 Broadcaster &broadcaster = debugger.GetBroadcaster();
1359 if (!broadcaster.EventTypeHasListeners(event_type)) {
1360 // Diagnostics are too important to drop. If nobody is listening, print the
1361 // diagnostic directly to the debugger's error stream.
1362 DiagnosticEventData event_data(type, std::move(message), debugger_specific);
1363 StreamSP stream = debugger.GetAsyncErrorStream();
1364 event_data.Dump(stream.get());
1365 return;
1366 }
1367 EventSP event_sp = std::make_shared<Event>(
1368 event_type,
1369 new DiagnosticEventData(type, std::move(message), debugger_specific));
1370 broadcaster.BroadcastEvent(event_sp);
1371}
1372
1373void Debugger::ReportDiagnosticImpl(DiagnosticEventData::Type type,
1374 std::string message,
1375 llvm::Optional<lldb::user_id_t> debugger_id,
1376 std::once_flag *once) {
1377 auto ReportDiagnosticLambda = [&]() {
1378 // Check if this progress is for a specific debugger.
1379 if (debugger_id) {
1380 // It is debugger specific, grab it and deliver the event if the debugger
1381 // still exists.
1382 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1383 if (debugger_sp)
1384 PrivateReportDiagnostic(*debugger_sp, type, std::move(message), true);
1385 return;
1386 }
1387 // The progress event is not debugger specific, iterate over all debuggers
1388 // and deliver a progress event to each one.
1389 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1390 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1391 for (const auto &debugger : *g_debugger_list_ptr)
1392 PrivateReportDiagnostic(*debugger, type, message, false);
1393 }
1394 };
1395
1396 if (once)
1397 std::call_once(*once, ReportDiagnosticLambda);
1398 else
1399 ReportDiagnosticLambda();
1400}
1401
1402void Debugger::ReportWarning(std::string message,
1403 llvm::Optional<lldb::user_id_t> debugger_id,
1404 std::once_flag *once) {
1405 ReportDiagnosticImpl(DiagnosticEventData::Type::Warning, std::move(message),
1406 debugger_id, once);
1407}
1408
1409void Debugger::ReportError(std::string message,
1410 llvm::Optional<lldb::user_id_t> debugger_id,
1411 std::once_flag *once) {
1412
1413 ReportDiagnosticImpl(DiagnosticEventData::Type::Error, std::move(message),
1414 debugger_id, once);
1415}
1416
1417void Debugger::ReportSymbolChange(const ModuleSpec &module_spec) {
1418 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1419 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1420 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) {
1421 EventSP event_sp = std::make_shared<Event>(
1422 Debugger::eBroadcastSymbolChange,
1423 new SymbolChangeEventData(debugger_sp, module_spec));
1424 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp);
1425 }
1426 }
1427}
1428
1429static std::shared_ptr<LogHandler>
1430CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close,
1431 size_t buffer_size) {
1432 switch (log_handler_kind) {
1433 case eLogHandlerStream:
1434 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size);
1435 case eLogHandlerCircular:
1436 return std::make_shared<RotatingLogHandler>(buffer_size);
1437 case eLogHandlerSystem:
1438 return std::make_shared<SystemLogHandler>();
1439 case eLogHandlerCallback:
1440 return {};
1441 }
1442 return {};
1443}
1444
1445bool Debugger::EnableLog(llvm::StringRef channel,
1446 llvm::ArrayRef<const char *> categories,
1447 llvm::StringRef log_file, uint32_t log_options,
1448 size_t buffer_size, LogHandlerKind log_handler_kind,
1449 llvm::raw_ostream &error_stream) {
1450
1451 std::shared_ptr<LogHandler> log_handler_sp;
1452 if (m_callback_handler_sp) {
1453 log_handler_sp = m_callback_handler_sp;
1454 // For now when using the callback mode you always get thread & timestamp.
1455 log_options |=
1456 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1457 } else if (log_file.empty()) {
1458 log_handler_sp =
1459 CreateLogHandler(log_handler_kind, GetOutputFile().GetDescriptor(),
1460 /*should_close=*/false, buffer_size);
1461 } else {
1462 auto pos = m_stream_handlers.find(log_file);
1463 if (pos != m_stream_handlers.end())
1464 log_handler_sp = pos->second.lock();
1465 if (!log_handler_sp) {
1466 File::OpenOptions flags =
1467 File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate;
1468 if (log_options & LLDB_LOG_OPTION_APPEND)
1469 flags |= File::eOpenOptionAppend;
1470 else
1471 flags |= File::eOpenOptionTruncate;
1472 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1473 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1474 if (!file) {
1475 error_stream << "Unable to open log file '" << log_file
1476 << "': " << llvm::toString(file.takeError()) << "\n";
1477 return false;
1478 }
1479
1480 log_handler_sp =
1481 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(),
1482 /*should_close=*/true, buffer_size);
1483 m_stream_handlers[log_file] = log_handler_sp;
1484 }
1485 }
1486 assert(log_handler_sp);
1487
1488 if (log_options == 0)
1489 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1490
1491 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories,
1492 error_stream);
1493}
1494
1495ScriptInterpreter *
1496Debugger::GetScriptInterpreter(bool can_create,
1497 llvm::Optional<lldb::ScriptLanguage> language) {
1498 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1499 lldb::ScriptLanguage script_language =
1500 language ? *language : GetScriptLanguage();
1501
1502 if (!m_script_interpreters[script_language]) {
1503 if (!can_create)
1504 return nullptr;
1505 m_script_interpreters[script_language] =
1506 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1507 }
1508
1509 return m_script_interpreters[script_language].get();
1510}
1511
1512SourceManager &Debugger::GetSourceManager() {
1513 if (!m_source_manager_up)
1514 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1515 return *m_source_manager_up;
1516}
1517
1518// This function handles events that were broadcast by the process.
1519void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1520 using namespace lldb;
1521 const uint32_t event_type =
1522 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1523 event_sp);
1524
1525 // if (event_type & eBreakpointEventTypeAdded
1526 // || event_type & eBreakpointEventTypeRemoved
1527 // || event_type & eBreakpointEventTypeEnabled
1528 // || event_type & eBreakpointEventTypeDisabled
1529 // || event_type & eBreakpointEventTypeCommandChanged
1530 // || event_type & eBreakpointEventTypeConditionChanged
1531 // || event_type & eBreakpointEventTypeIgnoreChanged
1532 // || event_type & eBreakpointEventTypeLocationsResolved)
1533 // {
1534 // // Don't do anything about these events, since the breakpoint
1535 // commands already echo these actions.
1536 // }
1537 //
1538 if (event_type & eBreakpointEventTypeLocationsAdded) {
1539 uint32_t num_new_locations =
1540 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1541 event_sp);
1542 if (num_new_locations > 0) {
1543 BreakpointSP breakpoint =
1544 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1545 StreamSP output_sp(GetAsyncOutputStream());
1546 if (output_sp) {
1547 output_sp->Printf("%d location%s added to breakpoint %d\n",
1548 num_new_locations, num_new_locations == 1 ? "" : "s",
1549 breakpoint->GetID());
1550 output_sp->Flush();
1551 }
1552 }
1553 }
1554 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1555 // {
1556 // // These locations just get disabled, not sure it is worth spamming
1557 // folks about this on the command line.
1558 // }
1559 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1560 // {
1561 // // This might be an interesting thing to note, but I'm going to
1562 // leave it quiet for now, it just looked noisy.
1563 // }
1564}
1565
1566void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1567 bool flush_stderr) {
1568 const auto &flush = [&](Stream &stream,
1569 size_t (Process::*get)(char *, size_t, Status &)) {
1570 Status error;
1571 size_t len;
1572 char buffer[1024];
1573 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1574 stream.Write(buffer, len);
1575 stream.Flush();
1576 };
1577
1578 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1579 if (flush_stdout)
1580 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT);
1581 if (flush_stderr)
1582 flush(*GetAsyncErrorStream(), &Process::GetSTDERR);
1583}
1584
1585// This function handles events that were broadcast by the process.
1586void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1587 using namespace lldb;
1588 const uint32_t event_type = event_sp->GetType();
1589 ProcessSP process_sp =
1590 (event_type == Process::eBroadcastBitStructuredData)
1591 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1592 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1593
1594 StreamSP output_stream_sp = GetAsyncOutputStream();
1595 StreamSP error_stream_sp = GetAsyncErrorStream();
1596 const bool gui_enabled = IsForwardingEvents();
1597
1598 if (!gui_enabled) {
1599 bool pop_process_io_handler = false;
1600 assert(process_sp);
1601
1602 bool state_is_stopped = false;
1603 const bool got_state_changed =
1604 (event_type & Process::eBroadcastBitStateChanged) != 0;
1605 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1606 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1607 const bool got_structured_data =
1608 (event_type & Process::eBroadcastBitStructuredData) != 0;
1609
1610 if (got_state_changed) {
1611 StateType event_state =
1612 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1613 state_is_stopped = StateIsStoppedState(event_state, false);
1614 }
1615
1616 // Display running state changes first before any STDIO
1617 if (got_state_changed && !state_is_stopped) {
1618 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1619 pop_process_io_handler);
1620 }
1621
1622 // Now display STDOUT and STDERR
1623 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
1624 got_stderr || got_state_changed);
1625
1626 // Give structured data events an opportunity to display.
1627 if (got_structured_data) {
1628 StructuredDataPluginSP plugin_sp =
1629 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1630 if (plugin_sp) {
1631 auto structured_data_sp =
1632 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1633 if (output_stream_sp) {
1634 StreamString content_stream;
1635 Status error =
1636 plugin_sp->GetDescription(structured_data_sp, content_stream);
1637 if (error.Success()) {
1638 if (!content_stream.GetString().empty()) {
1639 // Add newline.
1640 content_stream.PutChar('\n');
1641 content_stream.Flush();
1642
1643 // Print it.
1644 output_stream_sp->PutCString(content_stream.GetString());
1645 }
1646 } else {
1647 error_stream_sp->Format("Failed to print structured "
1648 "data with plugin {0}: {1}",
1649 plugin_sp->GetPluginName(), error);
1650 }
1651 }
1652 }
1653 }
1654
1655 // Now display any stopped state changes after any STDIO
1656 if (got_state_changed && state_is_stopped) {
1657 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1658 pop_process_io_handler);
1659 }
1660
1661 output_stream_sp->Flush();
1662 error_stream_sp->Flush();
1663
1664 if (pop_process_io_handler)
1665 process_sp->PopProcessIOHandler();
1666 }
1667}
1668
1669void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1670 // At present the only thread event we handle is the Frame Changed event, and
1671 // all we do for that is just reprint the thread status for that thread.
1672 using namespace lldb;
1673 const uint32_t event_type = event_sp->GetType();
1674 const bool stop_format = true;
1675 if (event_type == Thread::eBroadcastBitStackChanged ||
1676 event_type == Thread::eBroadcastBitThreadSelected) {
1677 ThreadSP thread_sp(
1678 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1679 if (thread_sp) {
1680 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1681 }
1682 }
1683}
1684
1685bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1686
1687void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1688 m_forward_listener_sp = listener_sp;
1689}
1690
1691void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1692 m_forward_listener_sp.reset();
1693}
1694
1695lldb::thread_result_t Debugger::DefaultEventHandler() {
1696 ListenerSP listener_sp(GetListener());
1697 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1698 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1699 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1700 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1701 Target::eBroadcastBitBreakpointChanged);
1702
1703 BroadcastEventSpec process_event_spec(
1704 broadcaster_class_process,
1705 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1706 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1707
1708 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1709 Thread::eBroadcastBitStackChanged |
1710 Thread::eBroadcastBitThreadSelected);
1711
1712 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1713 target_event_spec);
1714 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1715 process_event_spec);
1716 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1717 thread_event_spec);
1718 listener_sp->StartListeningForEvents(
1719 m_command_interpreter_up.get(),
1720 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1721 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1722 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1723
1724 listener_sp->StartListeningForEvents(
1725 &m_broadcaster, eBroadcastBitProgress | eBroadcastBitWarning |
1726 eBroadcastBitError | eBroadcastSymbolChange);
1727
1728 // Let the thread that spawned us know that we have started up and that we
1729 // are now listening to all required events so no events get missed
1730 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1731
1732 bool done = false;
1733 while (!done) {
1734 EventSP event_sp;
1735 if (listener_sp->GetEvent(event_sp, llvm::None)) {
1736 if (event_sp) {
1737 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1738 if (broadcaster) {
1739 uint32_t event_type = event_sp->GetType();
1740 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1741 if (broadcaster_class == broadcaster_class_process) {
1742 HandleProcessEvent(event_sp);
1743 } else if (broadcaster_class == broadcaster_class_target) {
1744 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1745 event_sp.get())) {
1746 HandleBreakpointEvent(event_sp);
1747 }
1748 } else if (broadcaster_class == broadcaster_class_thread) {
1749 HandleThreadEvent(event_sp);
1750 } else if (broadcaster == m_command_interpreter_up.get()) {
1751 if (event_type &
1752 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1753 done = true;
1754 } else if (event_type &
1755 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1756 const char *data = static_cast<const char *>(
1757 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1758 if (data && data[0]) {
1759 StreamSP error_sp(GetAsyncErrorStream());
1760 if (error_sp) {
1761 error_sp->PutCString(data);
1762 error_sp->Flush();
1763 }
1764 }
1765 } else if (event_type & CommandInterpreter::
1766 eBroadcastBitAsynchronousOutputData) {
1767 const char *data = static_cast<const char *>(
1768 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1769 if (data && data[0]) {
1770 StreamSP output_sp(GetAsyncOutputStream());
1771 if (output_sp) {
1772 output_sp->PutCString(data);
1773 output_sp->Flush();
1774 }
1775 }
1776 }
1777 } else if (broadcaster == &m_broadcaster) {
1778 if (event_type & Debugger::eBroadcastBitProgress)
1779 HandleProgressEvent(event_sp);
1780 else if (event_type & Debugger::eBroadcastBitWarning)
1781 HandleDiagnosticEvent(event_sp);
1782 else if (event_type & Debugger::eBroadcastBitError)
1783 HandleDiagnosticEvent(event_sp);
1784 }
1785 }
1786
1787 if (m_forward_listener_sp)
1788 m_forward_listener_sp->AddEvent(event_sp);
1789 }
1790 }
1791 }
1792 return {};
1793}
1794
1795bool Debugger::StartEventHandlerThread() {
1796 if (!m_event_handler_thread.IsJoinable()) {
1797 // We must synchronize with the DefaultEventHandler() thread to ensure it
1798 // is up and running and listening to events before we return from this
1799 // function. We do this by listening to events for the
1800 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1801 ConstString full_name("lldb.debugger.event-handler");
1802 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
1803 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1804 eBroadcastBitEventThreadIsListening);
1805
1806 llvm::StringRef thread_name =
1807 full_name.GetLength() < llvm::get_max_thread_name_length()
1808 ? full_name.GetStringRef()
1809 : "dbg.evt-handler";
1810
1811 // Use larger 8MB stack for this thread
1812 llvm::Expected<HostThread> event_handler_thread =
1813 ThreadLauncher::LaunchThread(
1814 thread_name, [this] { return DefaultEventHandler(); },
1815 g_debugger_event_thread_stack_bytes);
1816
1817 if (event_handler_thread) {
1818 m_event_handler_thread = *event_handler_thread;
1819 } else {
1820 LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}",
1821 llvm::toString(event_handler_thread.takeError()));
1822 }
1823
1824 // Make sure DefaultEventHandler() is running and listening to events
1825 // before we return from this function. We are only listening for events of
1826 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1827 // event, we just need to wait an infinite amount of time for it (nullptr
1828 // timeout as the first parameter)
1829 lldb::EventSP event_sp;
1830 listener_sp->GetEvent(event_sp, llvm::None);
1831 }
1832 return m_event_handler_thread.IsJoinable();
1833}
1834
1835void Debugger::StopEventHandlerThread() {
1836 if (m_event_handler_thread.IsJoinable()) {
1837 GetCommandInterpreter().BroadcastEvent(
1838 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1839 m_event_handler_thread.Join(nullptr);
1840 }
1841}
1842
1843lldb::thread_result_t Debugger::IOHandlerThread() {
1844 RunIOHandlers();
1845 StopEventHandlerThread();
1846 return {};
1847}
1848
1849void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) {
1850 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get());
1851 if (!data)
1852 return;
1853
1854 // Do some bookkeeping for the current event, regardless of whether we're
1855 // going to show the progress.
1856 const uint64_t id = data->GetID();
1857 if (m_current_event_id) {
1858 Log *log = GetLog(LLDBLog::Events);
1859 if (log && log->GetVerbose()) {
1860 StreamString log_stream;
1861 log_stream.AsRawOstream()
1862 << static_cast<void *>(this) << " Debugger(" << GetID()
1863 << ")::HandleProgressEvent( m_current_event_id = "
1864 << *m_current_event_id << ", data = { ";
1865 data->Dump(&log_stream);
1866 log_stream << " } )";
1867 log->PutString(log_stream.GetString());
1868 }
1869 if (id != *m_current_event_id)
1870 return;
1871 if (data->GetCompleted() == data->GetTotal())
1872 m_current_event_id.reset();
1873 } else {
1874 m_current_event_id = id;
1875 }
1876
1877 // Decide whether we actually are going to show the progress. This decision
1878 // can change between iterations so check it inside the loop.
1879 if (!GetShowProgress())
1880 return;
1881
1882 // Determine whether the current output file is an interactive terminal with
1883 // color support. We assume that if we support ANSI escape codes we support
1884 // vt100 escape codes.
1885 File &file = GetOutputFile();
1886 if (!file.GetIsInteractive() || !file.GetIsTerminalWithColors())
1887 return;
1888
1889 StreamSP output = GetAsyncOutputStream();
1890
1891 // Print over previous line, if any.
1892 output->Printf("\r");
1893
1894 if (data->GetCompleted() == data->GetTotal()) {
1895 // Clear the current line.
1896 output->Printf("\x1B[2K");
1897 output->Flush();
1898 return;
1899 }
1900
1901 // Trim the progress message if it exceeds the window's width and print it.
1902 std::string message = data->GetMessage();
1903 if (data->IsFinite())
1904 message = llvm::formatv("[{0}/{1}] {2}", data->GetCompleted(),
1905 data->GetTotal(), message)
1906 .str();
1907
1908 // Trim the progress message if it exceeds the window's width and print it.
1909 const uint32_t term_width = GetTerminalWidth();
1910 const uint32_t ellipsis = 3;
1911 if (message.size() + ellipsis >= term_width)
1912 message = message.substr(0, term_width - ellipsis);
1913
1914 const bool use_color = GetUseColor();
1915 llvm::StringRef ansi_prefix = GetShowProgressAnsiPrefix();
1916 if (!ansi_prefix.empty())
1917 output->Printf(
1918 "%s", ansi::FormatAnsiTerminalCodes(ansi_prefix, use_color).c_str());
1919
1920 output->Printf("%s...", message.c_str());
1921
1922 llvm::StringRef ansi_suffix = GetShowProgressAnsiSuffix();
1923 if (!ansi_suffix.empty())
1924 output->Printf(
1925 "%s", ansi::FormatAnsiTerminalCodes(ansi_suffix, use_color).c_str());
1926
1927 // Clear until the end of the line.
1928 output->Printf("\x1B[K\r");
1929
1930 // Flush the output.
1931 output->Flush();
1932}
1933
1934void Debugger::HandleDiagnosticEvent(const lldb::EventSP &event_sp) {
1935 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get());
1936 if (!data)
1937 return;
1938
1939 StreamSP stream = GetAsyncErrorStream();
1940 data->Dump(stream.get());
1941}
1942
1943bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1944
1945bool Debugger::StartIOHandlerThread() {
1946 if (!m_io_handler_thread.IsJoinable()) {
1947 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1948 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); },
1949 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1950 if (io_handler_thread) {
1951 m_io_handler_thread = *io_handler_thread;
1952 } else {
1953 LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}",
1954 llvm::toString(io_handler_thread.takeError()));
1955 }
1956 }
1957 return m_io_handler_thread.IsJoinable();
1958}
1959
1960void Debugger::StopIOHandlerThread() {
1961 if (m_io_handler_thread.IsJoinable()) {
1962 GetInputFile().Close();
1963 m_io_handler_thread.Join(nullptr);
1964 }
1965}
1966
1967void Debugger::JoinIOHandlerThread() {
1968 if (HasIOHandlerThread()) {
1969 thread_result_t result;
1970 m_io_handler_thread.Join(&result);
1971 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1972 }
1973}
1974
1975Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1976 if (!prefer_dummy) {
1977 if (TargetSP target = m_target_list.GetSelectedTarget())
1978 return *target;
1979 }
1980 return GetDummyTarget();
1981}
1982
1983Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1984 Status err;
1985 FileSpec repl_executable;
1986
1987 if (language == eLanguageTypeUnknown)
1988 language = GetREPLLanguage();
1989
1990 if (language == eLanguageTypeUnknown) {
1991 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
1992
1993 if (auto single_lang = repl_languages.GetSingularLanguage()) {
1994 language = *single_lang;
1995 } else if (repl_languages.Empty()) {
1996 err.SetErrorString(
1997 "LLDB isn't configured with REPL support for any languages.");
1998 return err;
1999 } else {
2000 err.SetErrorString(
2001 "Multiple possible REPL languages. Please specify a language.");
2002 return err;
2003 }
2004 }
2005
2006 Target *const target =
2007 nullptr; // passing in an empty target means the REPL must create one
2008
2009 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
2010
2011 if (!err.Success()) {
2012 return err;
2013 }
2014
2015 if (!repl_sp) {
2016 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
2017 Language::GetNameForLanguageType(language));
2018 return err;
2019 }
2020
2021 repl_sp->SetCompilerOptions(repl_options);
2022 repl_sp->RunLoop();
2023
2024 return err;
2025}
2026
2027llvm::ThreadPool &Debugger::GetThreadPool() {
2028 assert(g_thread_pool &&
2029 "Debugger::GetThreadPool called before Debugger::Initialize");
2030 return *g_thread_pool;
2031}
2032

source code of lldb/source/Core/Debugger.cpp