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