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/Diagnostics.h"
48 #include "lldb/Utility/Event.h"
49 #include "lldb/Utility/LLDBLog.h"
50 #include "lldb/Utility/Listener.h"
51 #include "lldb/Utility/Log.h"
52 #include "lldb/Utility/State.h"
53 #include "lldb/Utility/Stream.h"
54 #include "lldb/Utility/StreamString.h"
55 #include "lldb/lldb-enumerations.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/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 <optional>
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
91 namespace lldb_private {
92 class Address;
93 }
94
95 using namespace lldb;
96 using namespace lldb_private;
97
98 static lldb::user_id_t g_unique_id = 1;
99 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
100
101 #pragma mark Static Functions
102
103 typedef std::vector<DebuggerSP> DebuggerList;
104 static std::recursive_mutex *g_debugger_list_mutex_ptr =
105 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
106 static DebuggerList *g_debugger_list_ptr =
107 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
108 static llvm::ThreadPool *g_thread_pool = nullptr;
109
110 static 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
135 static 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
153 static constexpr OptionEnumValueElement g_dwim_print_verbosities[] = {
154 {eDWIMPrintVerbosityNone, "none",
155 "Use no verbosity when running dwim-print."},
156 {eDWIMPrintVerbosityExpression, "expression",
157 "Use partial verbosity when running dwim-print - display a message when "
158 "`expression` evaluation is used."},
159 {eDWIMPrintVerbosityFull, "full",
160 "Use full verbosity when running dwim-print."},
161 };
162
163 static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
164 {
165 eStopShowColumnAnsiOrCaret,
166 "ansi-or-caret",
167 "Highlight the stop column with ANSI terminal codes when color/ANSI "
168 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
169 "as if \"caret-only\" mode was selected.",
170 },
171 {
172 eStopShowColumnAnsi,
173 "ansi",
174 "Highlight the stop column with ANSI terminal codes when running LLDB "
175 "with color/ANSI enabled.",
176 },
177 {
178 eStopShowColumnCaret,
179 "caret",
180 "Highlight the stop column with a caret character (^) underneath the "
181 "stop column. This method introduces a new line in source listings "
182 "that display thread stop locations.",
183 },
184 {
185 eStopShowColumnNone,
186 "none",
187 "Do not highlight the stop column.",
188 },
189 };
190
191 #define LLDB_PROPERTIES_debugger
192 #include "CoreProperties.inc"
193
194 enum {
195 #define LLDB_PROPERTIES_debugger
196 #include "CorePropertiesEnum.inc"
197 };
198
199 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
200
SetPropertyValue(const ExecutionContext * exe_ctx,VarSetOperationType op,llvm::StringRef property_path,llvm::StringRef value)201 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
202 VarSetOperationType op,
203 llvm::StringRef property_path,
204 llvm::StringRef value) {
205 bool is_load_script =
206 (property_path == "target.load-script-from-symbol-file");
207 // These properties might change how we visualize data.
208 bool invalidate_data_vis = (property_path == "escape-non-printables");
209 invalidate_data_vis |=
210 (property_path == "target.max-zero-padding-in-float-format");
211 if (invalidate_data_vis) {
212 DataVisualization::ForceUpdate();
213 }
214
215 TargetSP target_sp;
216 LoadScriptFromSymFile load_script_old_value = eLoadScriptFromSymFileFalse;
217 if (is_load_script && exe_ctx->GetTargetSP()) {
218 target_sp = exe_ctx->GetTargetSP();
219 load_script_old_value =
220 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
221 }
222 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
223 if (error.Success()) {
224 // FIXME it would be nice to have "on-change" callbacks for properties
225 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
226 llvm::StringRef new_prompt = GetPrompt();
227 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes(
228 new_prompt, GetUseColor());
229 if (str.length())
230 new_prompt = str;
231 GetCommandInterpreter().UpdatePrompt(new_prompt);
232 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
233 auto prompt_change_event_sp = std::make_shared<Event>(
234 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
235 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
236 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
237 // use-color changed. Ping the prompt so it can reset the ansi terminal
238 // codes.
239 SetPrompt(GetPrompt());
240 } else if (property_path == g_debugger_properties[ePropertyUseSourceCache].name) {
241 // use-source-cache changed. Wipe out the cache contents if it was disabled.
242 if (!GetUseSourceCache()) {
243 m_source_file_cache.Clear();
244 }
245 } else if (is_load_script && target_sp &&
246 load_script_old_value == eLoadScriptFromSymFileWarn) {
247 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
248 eLoadScriptFromSymFileTrue) {
249 std::list<Status> errors;
250 StreamString feedback_stream;
251 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
252 Stream &s = GetErrorStream();
253 for (auto error : errors) {
254 s.Printf("%s\n", error.AsCString());
255 }
256 if (feedback_stream.GetSize())
257 s.PutCString(feedback_stream.GetString());
258 }
259 }
260 }
261 }
262 return error;
263 }
264
GetAutoConfirm() const265 bool Debugger::GetAutoConfirm() const {
266 const uint32_t idx = ePropertyAutoConfirm;
267 return m_collection_sp->GetPropertyAtIndexAsBoolean(
268 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
269 }
270
GetDisassemblyFormat() const271 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
272 const uint32_t idx = ePropertyDisassemblyFormat;
273 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
274 }
275
GetFrameFormat() const276 const FormatEntity::Entry *Debugger::GetFrameFormat() const {
277 const uint32_t idx = ePropertyFrameFormat;
278 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
279 }
280
GetFrameFormatUnique() const281 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
282 const uint32_t idx = ePropertyFrameFormatUnique;
283 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
284 }
285
GetStopDisassemblyMaxSize() const286 uint32_t Debugger::GetStopDisassemblyMaxSize() const {
287 const uint32_t idx = ePropertyStopDisassemblyMaxSize;
288 return m_collection_sp->GetPropertyAtIndexAsUInt64(
289 nullptr, idx, g_debugger_properties[idx].default_uint_value);
290 }
291
GetNotifyVoid() const292 bool Debugger::GetNotifyVoid() const {
293 const uint32_t idx = ePropertyNotiftVoid;
294 return m_collection_sp->GetPropertyAtIndexAsBoolean(
295 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
296 }
297
GetPrompt() const298 llvm::StringRef Debugger::GetPrompt() const {
299 const uint32_t idx = ePropertyPrompt;
300 return m_collection_sp->GetPropertyAtIndexAsString(
301 nullptr, idx, g_debugger_properties[idx].default_cstr_value);
302 }
303
SetPrompt(llvm::StringRef p)304 void Debugger::SetPrompt(llvm::StringRef p) {
305 const uint32_t idx = ePropertyPrompt;
306 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
307 llvm::StringRef new_prompt = GetPrompt();
308 std::string str =
309 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
310 if (str.length())
311 new_prompt = str;
312 GetCommandInterpreter().UpdatePrompt(new_prompt);
313 }
314
GetThreadFormat() const315 const FormatEntity::Entry *Debugger::GetThreadFormat() const {
316 const uint32_t idx = ePropertyThreadFormat;
317 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
318 }
319
GetThreadStopFormat() const320 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
321 const uint32_t idx = ePropertyThreadStopFormat;
322 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
323 }
324
GetScriptLanguage() const325 lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
326 const uint32_t idx = ePropertyScriptLanguage;
327 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
328 nullptr, idx, g_debugger_properties[idx].default_uint_value);
329 }
330
SetScriptLanguage(lldb::ScriptLanguage script_lang)331 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
332 const uint32_t idx = ePropertyScriptLanguage;
333 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
334 script_lang);
335 }
336
GetREPLLanguage() const337 lldb::LanguageType Debugger::GetREPLLanguage() const {
338 const uint32_t idx = ePropertyREPLLanguage;
339 OptionValueLanguage *value =
340 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(nullptr, idx);
341 if (value)
342 return value->GetCurrentValue();
343 return LanguageType();
344 }
345
SetREPLLanguage(lldb::LanguageType repl_lang)346 bool Debugger::SetREPLLanguage(lldb::LanguageType repl_lang) {
347 const uint32_t idx = ePropertyREPLLanguage;
348 return m_collection_sp->SetPropertyAtIndexAsLanguage(nullptr, idx, repl_lang);
349 }
350
GetTerminalWidth() const351 uint32_t Debugger::GetTerminalWidth() const {
352 const uint32_t idx = ePropertyTerminalWidth;
353 return m_collection_sp->GetPropertyAtIndexAsSInt64(
354 nullptr, idx, g_debugger_properties[idx].default_uint_value);
355 }
356
SetTerminalWidth(uint32_t term_width)357 bool Debugger::SetTerminalWidth(uint32_t term_width) {
358 if (auto handler_sp = m_io_handler_stack.Top())
359 handler_sp->TerminalSizeChanged();
360
361 const uint32_t idx = ePropertyTerminalWidth;
362 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
363 }
364
GetUseExternalEditor() const365 bool Debugger::GetUseExternalEditor() const {
366 const uint32_t idx = ePropertyUseExternalEditor;
367 return m_collection_sp->GetPropertyAtIndexAsBoolean(
368 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
369 }
370
SetUseExternalEditor(bool b)371 bool Debugger::SetUseExternalEditor(bool b) {
372 const uint32_t idx = ePropertyUseExternalEditor;
373 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
374 }
375
GetUseColor() const376 bool Debugger::GetUseColor() const {
377 const uint32_t idx = ePropertyUseColor;
378 return m_collection_sp->GetPropertyAtIndexAsBoolean(
379 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
380 }
381
SetUseColor(bool b)382 bool Debugger::SetUseColor(bool b) {
383 const uint32_t idx = ePropertyUseColor;
384 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
385 SetPrompt(GetPrompt());
386 return ret;
387 }
388
GetShowProgress() const389 bool Debugger::GetShowProgress() const {
390 const uint32_t idx = ePropertyShowProgress;
391 return m_collection_sp->GetPropertyAtIndexAsBoolean(
392 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
393 }
394
SetShowProgress(bool show_progress)395 bool Debugger::SetShowProgress(bool show_progress) {
396 const uint32_t idx = ePropertyShowProgress;
397 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx,
398 show_progress);
399 }
400
GetShowProgressAnsiPrefix() const401 llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const {
402 const uint32_t idx = ePropertyShowProgressAnsiPrefix;
403 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
404 }
405
GetShowProgressAnsiSuffix() const406 llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const {
407 const uint32_t idx = ePropertyShowProgressAnsiSuffix;
408 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
409 }
410
GetUseAutosuggestion() const411 bool Debugger::GetUseAutosuggestion() const {
412 const uint32_t idx = ePropertyShowAutosuggestion;
413 return m_collection_sp->GetPropertyAtIndexAsBoolean(
414 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
415 }
416
GetAutosuggestionAnsiPrefix() const417 llvm::StringRef Debugger::GetAutosuggestionAnsiPrefix() const {
418 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix;
419 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
420 }
421
GetAutosuggestionAnsiSuffix() const422 llvm::StringRef Debugger::GetAutosuggestionAnsiSuffix() const {
423 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix;
424 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
425 }
426
GetUseSourceCache() const427 bool Debugger::GetUseSourceCache() const {
428 const uint32_t idx = ePropertyUseSourceCache;
429 return m_collection_sp->GetPropertyAtIndexAsBoolean(
430 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
431 }
432
SetUseSourceCache(bool b)433 bool Debugger::SetUseSourceCache(bool b) {
434 const uint32_t idx = ePropertyUseSourceCache;
435 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
436 if (!ret) {
437 m_source_file_cache.Clear();
438 }
439 return ret;
440 }
GetHighlightSource() const441 bool Debugger::GetHighlightSource() const {
442 const uint32_t idx = ePropertyHighlightSource;
443 return m_collection_sp->GetPropertyAtIndexAsBoolean(
444 nullptr, idx, g_debugger_properties[idx].default_uint_value);
445 }
446
GetStopShowColumn() const447 StopShowColumn Debugger::GetStopShowColumn() const {
448 const uint32_t idx = ePropertyStopShowColumn;
449 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
450 nullptr, idx, g_debugger_properties[idx].default_uint_value);
451 }
452
GetStopShowColumnAnsiPrefix() const453 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
454 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
455 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
456 }
457
GetStopShowColumnAnsiSuffix() const458 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
459 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
460 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
461 }
462
GetStopShowLineMarkerAnsiPrefix() const463 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const {
464 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
465 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
466 }
467
GetStopShowLineMarkerAnsiSuffix() const468 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const {
469 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
470 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
471 }
472
GetStopSourceLineCount(bool before) const473 uint32_t Debugger::GetStopSourceLineCount(bool before) const {
474 const uint32_t idx =
475 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
476 return m_collection_sp->GetPropertyAtIndexAsSInt64(
477 nullptr, idx, g_debugger_properties[idx].default_uint_value);
478 }
479
GetStopDisassemblyDisplay() const480 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
481 const uint32_t idx = ePropertyStopDisassemblyDisplay;
482 return (Debugger::StopDisassemblyType)
483 m_collection_sp->GetPropertyAtIndexAsEnumeration(
484 nullptr, idx, g_debugger_properties[idx].default_uint_value);
485 }
486
GetDisassemblyLineCount() const487 uint32_t Debugger::GetDisassemblyLineCount() const {
488 const uint32_t idx = ePropertyStopDisassemblyCount;
489 return m_collection_sp->GetPropertyAtIndexAsSInt64(
490 nullptr, idx, g_debugger_properties[idx].default_uint_value);
491 }
492
GetAutoOneLineSummaries() const493 bool Debugger::GetAutoOneLineSummaries() const {
494 const uint32_t idx = ePropertyAutoOneLineSummaries;
495 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
496 }
497
GetEscapeNonPrintables() const498 bool Debugger::GetEscapeNonPrintables() const {
499 const uint32_t idx = ePropertyEscapeNonPrintables;
500 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
501 }
502
GetAutoIndent() const503 bool Debugger::GetAutoIndent() const {
504 const uint32_t idx = ePropertyAutoIndent;
505 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
506 }
507
SetAutoIndent(bool b)508 bool Debugger::SetAutoIndent(bool b) {
509 const uint32_t idx = ePropertyAutoIndent;
510 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
511 }
512
GetPrintDecls() const513 bool Debugger::GetPrintDecls() const {
514 const uint32_t idx = ePropertyPrintDecls;
515 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
516 }
517
SetPrintDecls(bool b)518 bool Debugger::SetPrintDecls(bool b) {
519 const uint32_t idx = ePropertyPrintDecls;
520 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
521 }
522
GetTabSize() const523 uint32_t Debugger::GetTabSize() const {
524 const uint32_t idx = ePropertyTabSize;
525 return m_collection_sp->GetPropertyAtIndexAsUInt64(
526 nullptr, idx, g_debugger_properties[idx].default_uint_value);
527 }
528
SetTabSize(uint32_t tab_size)529 bool Debugger::SetTabSize(uint32_t tab_size) {
530 const uint32_t idx = ePropertyTabSize;
531 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
532 }
533
GetDWIMPrintVerbosity() const534 lldb::DWIMPrintVerbosity Debugger::GetDWIMPrintVerbosity() const {
535 const uint32_t idx = ePropertyDWIMPrintVerbosity;
536 return (lldb::DWIMPrintVerbosity)
537 m_collection_sp->GetPropertyAtIndexAsEnumeration(
538 nullptr, idx, g_debugger_properties[idx].default_uint_value);
539 }
540
541 #pragma mark Debugger
542
543 // const DebuggerPropertiesSP &
544 // Debugger::GetSettings() const
545 //{
546 // return m_properties_sp;
547 //}
548 //
549
Initialize(LoadPluginCallbackType load_plugin_callback)550 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
551 assert(g_debugger_list_ptr == nullptr &&
552 "Debugger::Initialize called more than once!");
553 g_debugger_list_mutex_ptr = new std::recursive_mutex();
554 g_debugger_list_ptr = new DebuggerList();
555 g_thread_pool = new llvm::ThreadPool(llvm::optimal_concurrency());
556 g_load_plugin_callback = load_plugin_callback;
557 }
558
Terminate()559 void Debugger::Terminate() {
560 assert(g_debugger_list_ptr &&
561 "Debugger::Terminate called without a matching Debugger::Initialize!");
562
563 if (g_thread_pool) {
564 // The destructor will wait for all the threads to complete.
565 delete g_thread_pool;
566 }
567
568 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
569 // Clear our global list of debugger objects
570 {
571 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
572 for (const auto &debugger : *g_debugger_list_ptr)
573 debugger->Clear();
574 g_debugger_list_ptr->clear();
575 }
576 }
577 }
578
SettingsInitialize()579 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
580
SettingsTerminate()581 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
582
LoadPlugin(const FileSpec & spec,Status & error)583 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
584 if (g_load_plugin_callback) {
585 llvm::sys::DynamicLibrary dynlib =
586 g_load_plugin_callback(shared_from_this(), spec, error);
587 if (dynlib.isValid()) {
588 m_loaded_plugins.push_back(dynlib);
589 return true;
590 }
591 } else {
592 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
593 // if the public API layer isn't available (code is linking against all of
594 // the internal LLDB static libraries), then we can't load plugins
595 error.SetErrorString("Public API layer is not available");
596 }
597 return false;
598 }
599
600 static FileSystem::EnumerateDirectoryResult
LoadPluginCallback(void * baton,llvm::sys::fs::file_type ft,llvm::StringRef path)601 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
602 llvm::StringRef path) {
603 Status error;
604
605 static ConstString g_dylibext(".dylib");
606 static ConstString g_solibext(".so");
607
608 if (!baton)
609 return FileSystem::eEnumerateDirectoryResultQuit;
610
611 Debugger *debugger = (Debugger *)baton;
612
613 namespace fs = llvm::sys::fs;
614 // If we have a regular file, a symbolic link or unknown file type, try and
615 // process the file. We must handle unknown as sometimes the directory
616 // enumeration might be enumerating a file system that doesn't have correct
617 // file type information.
618 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
619 ft == fs::file_type::type_unknown) {
620 FileSpec plugin_file_spec(path);
621 FileSystem::Instance().Resolve(plugin_file_spec);
622
623 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
624 plugin_file_spec.GetFileNameExtension() != g_solibext) {
625 return FileSystem::eEnumerateDirectoryResultNext;
626 }
627
628 Status plugin_load_error;
629 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
630
631 return FileSystem::eEnumerateDirectoryResultNext;
632 } else if (ft == fs::file_type::directory_file ||
633 ft == fs::file_type::symlink_file ||
634 ft == fs::file_type::type_unknown) {
635 // Try and recurse into anything that a directory or symbolic link. We must
636 // also do this for unknown as sometimes the directory enumeration might be
637 // enumerating a file system that doesn't have correct file type
638 // information.
639 return FileSystem::eEnumerateDirectoryResultEnter;
640 }
641
642 return FileSystem::eEnumerateDirectoryResultNext;
643 }
644
InstanceInitialize()645 void Debugger::InstanceInitialize() {
646 const bool find_directories = true;
647 const bool find_files = true;
648 const bool find_other = true;
649 char dir_path[PATH_MAX];
650 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
651 if (FileSystem::Instance().Exists(dir_spec) &&
652 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
653 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
654 find_files, find_other,
655 LoadPluginCallback, this);
656 }
657 }
658
659 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
660 if (FileSystem::Instance().Exists(dir_spec) &&
661 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
662 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
663 find_files, find_other,
664 LoadPluginCallback, this);
665 }
666 }
667
668 PluginManager::DebuggerInitialize(*this);
669 }
670
CreateInstance(lldb::LogOutputCallback log_callback,void * baton)671 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
672 void *baton) {
673 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
674 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
675 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
676 g_debugger_list_ptr->push_back(debugger_sp);
677 }
678 debugger_sp->InstanceInitialize();
679 return debugger_sp;
680 }
681
Destroy(DebuggerSP & debugger_sp)682 void Debugger::Destroy(DebuggerSP &debugger_sp) {
683 if (!debugger_sp)
684 return;
685
686 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
687
688 if (cmd_interpreter.GetSaveSessionOnQuit()) {
689 CommandReturnObject result(debugger_sp->GetUseColor());
690 cmd_interpreter.SaveTranscript(result);
691 if (result.Succeeded())
692 (*debugger_sp->GetAsyncOutputStream()) << result.GetOutputData() << '\n';
693 else
694 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorData() << '\n';
695 }
696
697 debugger_sp->Clear();
698
699 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
700 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
701 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
702 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
703 if ((*pos).get() == debugger_sp.get()) {
704 g_debugger_list_ptr->erase(pos);
705 return;
706 }
707 }
708 }
709 }
710
FindDebuggerWithInstanceName(ConstString instance_name)711 DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
712 DebuggerSP debugger_sp;
713 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
714 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
715 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
716 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
717 if ((*pos)->m_instance_name == instance_name) {
718 debugger_sp = *pos;
719 break;
720 }
721 }
722 }
723 return debugger_sp;
724 }
725
FindTargetWithProcessID(lldb::pid_t pid)726 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
727 TargetSP target_sp;
728 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
729 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
730 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
731 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
732 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
733 if (target_sp)
734 break;
735 }
736 }
737 return target_sp;
738 }
739
FindTargetWithProcess(Process * process)740 TargetSP Debugger::FindTargetWithProcess(Process *process) {
741 TargetSP target_sp;
742 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
743 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
744 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
745 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
746 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
747 if (target_sp)
748 break;
749 }
750 }
751 return target_sp;
752 }
753
GetStaticBroadcasterClass()754 ConstString Debugger::GetStaticBroadcasterClass() {
755 static ConstString class_name("lldb.debugger");
756 return class_name;
757 }
758
Debugger(lldb::LogOutputCallback log_callback,void * baton)759 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
760 : UserID(g_unique_id++),
761 Properties(std::make_shared<OptionValueProperties>()),
762 m_input_file_sp(std::make_shared<NativeFile>(stdin, false)),
763 m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)),
764 m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)),
765 m_input_recorder(nullptr),
766 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
767 m_terminal_state(), m_target_list(*this), m_platform_list(),
768 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
769 m_source_manager_up(), m_source_file_cache(),
770 m_command_interpreter_up(
771 std::make_unique<CommandInterpreter>(*this, false)),
772 m_io_handler_stack(), m_instance_name(), m_loaded_plugins(),
773 m_event_handler_thread(), m_io_handler_thread(),
774 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
775 m_broadcaster(m_broadcaster_manager_sp,
776 GetStaticBroadcasterClass().AsCString()),
777 m_forward_listener_sp(), m_clear_once() {
778 m_instance_name.SetString(llvm::formatv("debugger_{0}", GetID()).str());
779 if (log_callback)
780 m_callback_handler_sp =
781 std::make_shared<CallbackLogHandler>(log_callback, baton);
782 m_command_interpreter_up->Initialize();
783 // Always add our default platform to the platform list
784 PlatformSP default_platform_sp(Platform::GetHostPlatform());
785 assert(default_platform_sp);
786 m_platform_list.Append(default_platform_sp, true);
787
788 // Create the dummy target.
789 {
790 ArchSpec arch(Target::GetDefaultArchitecture());
791 if (!arch.IsValid())
792 arch = HostInfo::GetArchitecture();
793 assert(arch.IsValid() && "No valid default or host archspec");
794 const bool is_dummy_target = true;
795 m_dummy_target_sp.reset(
796 new Target(*this, arch, default_platform_sp, is_dummy_target));
797 }
798 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
799
800 m_collection_sp->Initialize(g_debugger_properties);
801 m_collection_sp->AppendProperty(
802 ConstString("target"),
803 ConstString("Settings specify to debugging targets."), true,
804 Target::GetGlobalProperties().GetValueProperties());
805 m_collection_sp->AppendProperty(
806 ConstString("platform"), ConstString("Platform settings."), true,
807 Platform::GetGlobalPlatformProperties().GetValueProperties());
808 m_collection_sp->AppendProperty(
809 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
810 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
811 if (m_command_interpreter_up) {
812 m_collection_sp->AppendProperty(
813 ConstString("interpreter"),
814 ConstString("Settings specify to the debugger's command interpreter."),
815 true, m_command_interpreter_up->GetValueProperties());
816 }
817 OptionValueSInt64 *term_width =
818 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
819 nullptr, ePropertyTerminalWidth);
820 term_width->SetMinimumValue(10);
821 term_width->SetMaximumValue(1024);
822
823 // Turn off use-color if this is a dumb terminal.
824 const char *term = getenv("TERM");
825 if (term && !strcmp(term, "dumb"))
826 SetUseColor(false);
827 // Turn off use-color if we don't write to a terminal with color support.
828 if (!GetOutputFile().GetIsTerminalWithColors())
829 SetUseColor(false);
830
831 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
832 // Enabling use of ANSI color codes because LLDB is using them to highlight
833 // text.
834 llvm::sys::Process::UseANSIEscapeCodes(true);
835 #endif
836 }
837
~Debugger()838 Debugger::~Debugger() { Clear(); }
839
Clear()840 void Debugger::Clear() {
841 // Make sure we call this function only once. With the C++ global destructor
842 // chain having a list of debuggers and with code that can be running on
843 // other threads, we need to ensure this doesn't happen multiple times.
844 //
845 // The following functions call Debugger::Clear():
846 // Debugger::~Debugger();
847 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
848 // static void Debugger::Terminate();
849 llvm::call_once(m_clear_once, [this]() {
850 ClearIOHandlers();
851 StopIOHandlerThread();
852 StopEventHandlerThread();
853 m_listener_sp->Clear();
854 for (TargetSP target_sp : m_target_list.Targets()) {
855 if (target_sp) {
856 if (ProcessSP process_sp = target_sp->GetProcessSP())
857 process_sp->Finalize();
858 target_sp->Destroy();
859 }
860 }
861 m_broadcaster_manager_sp->Clear();
862
863 // Close the input file _before_ we close the input read communications
864 // class as it does NOT own the input file, our m_input_file does.
865 m_terminal_state.Clear();
866 GetInputFile().Close();
867
868 m_command_interpreter_up->Clear();
869 });
870 }
871
GetCloseInputOnEOF() const872 bool Debugger::GetCloseInputOnEOF() const {
873 // return m_input_comm.GetCloseOnEOF();
874 return false;
875 }
876
SetCloseInputOnEOF(bool b)877 void Debugger::SetCloseInputOnEOF(bool b) {
878 // m_input_comm.SetCloseOnEOF(b);
879 }
880
GetAsyncExecution()881 bool Debugger::GetAsyncExecution() {
882 return !m_command_interpreter_up->GetSynchronous();
883 }
884
SetAsyncExecution(bool async_execution)885 void Debugger::SetAsyncExecution(bool async_execution) {
886 m_command_interpreter_up->SetSynchronous(!async_execution);
887 }
888
GetInputRecorder()889 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
890
OpenPipe(int fds[2],std::size_t size)891 static inline int OpenPipe(int fds[2], std::size_t size) {
892 #ifdef _WIN32
893 return _pipe(fds, size, O_BINARY);
894 #else
895 (void)size;
896 return pipe(fds);
897 #endif
898 }
899
SetInputString(const char * data)900 Status Debugger::SetInputString(const char *data) {
901 Status result;
902 enum PIPES { READ, WRITE }; // Indexes for the read and write fds
903 int fds[2] = {-1, -1};
904
905 if (data == nullptr) {
906 result.SetErrorString("String data is null");
907 return result;
908 }
909
910 size_t size = strlen(data);
911 if (size == 0) {
912 result.SetErrorString("String data is empty");
913 return result;
914 }
915
916 if (OpenPipe(fds, size) != 0) {
917 result.SetErrorString(
918 "can't create pipe file descriptors for LLDB commands");
919 return result;
920 }
921
922 int r = write(fds[WRITE], data, size);
923 (void)r;
924 // Close the write end of the pipe, so that the command interpreter will exit
925 // when it consumes all the data.
926 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
927
928 // Open the read file descriptor as a FILE * that we can return as an input
929 // handle.
930 FILE *commands_file = fdopen(fds[READ], "rb");
931 if (commands_file == nullptr) {
932 result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) "
933 "when trying to open LLDB commands pipe",
934 fds[READ], errno);
935 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
936 return result;
937 }
938
939 SetInputFile((FileSP)std::make_shared<NativeFile>(commands_file, true));
940 return result;
941 }
942
SetInputFile(FileSP file_sp)943 void Debugger::SetInputFile(FileSP file_sp) {
944 assert(file_sp && file_sp->IsValid());
945 m_input_file_sp = std::move(file_sp);
946 // Save away the terminal state if that is relevant, so that we can restore
947 // it in RestoreInputState.
948 SaveInputTerminalState();
949 }
950
SetOutputFile(FileSP file_sp)951 void Debugger::SetOutputFile(FileSP file_sp) {
952 assert(file_sp && file_sp->IsValid());
953 m_output_stream_sp = std::make_shared<StreamFile>(file_sp);
954 }
955
SetErrorFile(FileSP file_sp)956 void Debugger::SetErrorFile(FileSP file_sp) {
957 assert(file_sp && file_sp->IsValid());
958 m_error_stream_sp = std::make_shared<StreamFile>(file_sp);
959 }
960
SaveInputTerminalState()961 void Debugger::SaveInputTerminalState() {
962 int fd = GetInputFile().GetDescriptor();
963 if (fd != File::kInvalidDescriptor)
964 m_terminal_state.Save(fd, true);
965 }
966
RestoreInputTerminalState()967 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
968
GetSelectedExecutionContext()969 ExecutionContext Debugger::GetSelectedExecutionContext() {
970 bool adopt_selected = true;
971 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected);
972 return ExecutionContext(exe_ctx_ref);
973 }
974
DispatchInputInterrupt()975 void Debugger::DispatchInputInterrupt() {
976 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
977 IOHandlerSP reader_sp(m_io_handler_stack.Top());
978 if (reader_sp)
979 reader_sp->Interrupt();
980 }
981
DispatchInputEndOfFile()982 void Debugger::DispatchInputEndOfFile() {
983 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
984 IOHandlerSP reader_sp(m_io_handler_stack.Top());
985 if (reader_sp)
986 reader_sp->GotEOF();
987 }
988
ClearIOHandlers()989 void Debugger::ClearIOHandlers() {
990 // The bottom input reader should be the main debugger input reader. We do
991 // not want to close that one here.
992 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
993 while (m_io_handler_stack.GetSize() > 1) {
994 IOHandlerSP reader_sp(m_io_handler_stack.Top());
995 if (reader_sp)
996 PopIOHandler(reader_sp);
997 }
998 }
999
RunIOHandlers()1000 void Debugger::RunIOHandlers() {
1001 IOHandlerSP reader_sp = m_io_handler_stack.Top();
1002 while (true) {
1003 if (!reader_sp)
1004 break;
1005
1006 reader_sp->Run();
1007 {
1008 std::lock_guard<std::recursive_mutex> guard(
1009 m_io_handler_synchronous_mutex);
1010
1011 // Remove all input readers that are done from the top of the stack
1012 while (true) {
1013 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
1014 if (top_reader_sp && top_reader_sp->GetIsDone())
1015 PopIOHandler(top_reader_sp);
1016 else
1017 break;
1018 }
1019 reader_sp = m_io_handler_stack.Top();
1020 }
1021 }
1022 ClearIOHandlers();
1023 }
1024
RunIOHandlerSync(const IOHandlerSP & reader_sp)1025 void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) {
1026 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1027
1028 PushIOHandler(reader_sp);
1029 IOHandlerSP top_reader_sp = reader_sp;
1030
1031 while (top_reader_sp) {
1032 if (!top_reader_sp)
1033 break;
1034
1035 top_reader_sp->Run();
1036
1037 // Don't unwind past the starting point.
1038 if (top_reader_sp.get() == reader_sp.get()) {
1039 if (PopIOHandler(reader_sp))
1040 break;
1041 }
1042
1043 // If we pushed new IO handlers, pop them if they're done or restart the
1044 // loop to run them if they're not.
1045 while (true) {
1046 top_reader_sp = m_io_handler_stack.Top();
1047 if (top_reader_sp && top_reader_sp->GetIsDone()) {
1048 PopIOHandler(top_reader_sp);
1049 // Don't unwind past the starting point.
1050 if (top_reader_sp.get() == reader_sp.get())
1051 return;
1052 } else {
1053 break;
1054 }
1055 }
1056 }
1057 }
1058
IsTopIOHandler(const lldb::IOHandlerSP & reader_sp)1059 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
1060 return m_io_handler_stack.IsTop(reader_sp);
1061 }
1062
CheckTopIOHandlerTypes(IOHandler::Type top_type,IOHandler::Type second_top_type)1063 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
1064 IOHandler::Type second_top_type) {
1065 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1066 }
1067
PrintAsync(const char * s,size_t len,bool is_stdout)1068 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1069 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout);
1070 if (!printed) {
1071 lldb::StreamFileSP stream =
1072 is_stdout ? m_output_stream_sp : m_error_stream_sp;
1073 stream->Write(s, len);
1074 }
1075 }
1076
GetTopIOHandlerControlSequence(char ch)1077 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1078 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1079 }
1080
GetIOHandlerCommandPrefix()1081 const char *Debugger::GetIOHandlerCommandPrefix() {
1082 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1083 }
1084
GetIOHandlerHelpPrologue()1085 const char *Debugger::GetIOHandlerHelpPrologue() {
1086 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1087 }
1088
RemoveIOHandler(const IOHandlerSP & reader_sp)1089 bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) {
1090 return PopIOHandler(reader_sp);
1091 }
1092
RunIOHandlerAsync(const IOHandlerSP & reader_sp,bool cancel_top_handler)1093 void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp,
1094 bool cancel_top_handler) {
1095 PushIOHandler(reader_sp, cancel_top_handler);
1096 }
1097
AdoptTopIOHandlerFilesIfInvalid(FileSP & in,StreamFileSP & out,StreamFileSP & err)1098 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out,
1099 StreamFileSP &err) {
1100 // Before an IOHandler runs, it must have in/out/err streams. This function
1101 // is called when one ore more of the streams are nullptr. We use the top
1102 // input reader's in/out/err streams, or fall back to the debugger file
1103 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1104
1105 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1106 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1107 // If no STDIN has been set, then set it appropriately
1108 if (!in || !in->IsValid()) {
1109 if (top_reader_sp)
1110 in = top_reader_sp->GetInputFileSP();
1111 else
1112 in = GetInputFileSP();
1113 // If there is nothing, use stdin
1114 if (!in)
1115 in = std::make_shared<NativeFile>(stdin, false);
1116 }
1117 // If no STDOUT has been set, then set it appropriately
1118 if (!out || !out->GetFile().IsValid()) {
1119 if (top_reader_sp)
1120 out = top_reader_sp->GetOutputStreamFileSP();
1121 else
1122 out = GetOutputStreamSP();
1123 // If there is nothing, use stdout
1124 if (!out)
1125 out = std::make_shared<StreamFile>(stdout, false);
1126 }
1127 // If no STDERR has been set, then set it appropriately
1128 if (!err || !err->GetFile().IsValid()) {
1129 if (top_reader_sp)
1130 err = top_reader_sp->GetErrorStreamFileSP();
1131 else
1132 err = GetErrorStreamSP();
1133 // If there is nothing, use stderr
1134 if (!err)
1135 err = std::make_shared<StreamFile>(stderr, false);
1136 }
1137 }
1138
PushIOHandler(const IOHandlerSP & reader_sp,bool cancel_top_handler)1139 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1140 bool cancel_top_handler) {
1141 if (!reader_sp)
1142 return;
1143
1144 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1145
1146 // Get the current top input reader...
1147 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1148
1149 // Don't push the same IO handler twice...
1150 if (reader_sp == top_reader_sp)
1151 return;
1152
1153 // Push our new input reader
1154 m_io_handler_stack.Push(reader_sp);
1155 reader_sp->Activate();
1156
1157 // Interrupt the top input reader to it will exit its Run() function and let
1158 // this new input reader take over
1159 if (top_reader_sp) {
1160 top_reader_sp->Deactivate();
1161 if (cancel_top_handler)
1162 top_reader_sp->Cancel();
1163 }
1164 }
1165
PopIOHandler(const IOHandlerSP & pop_reader_sp)1166 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1167 if (!pop_reader_sp)
1168 return false;
1169
1170 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1171
1172 // The reader on the stop of the stack is done, so let the next read on the
1173 // stack refresh its prompt and if there is one...
1174 if (m_io_handler_stack.IsEmpty())
1175 return false;
1176
1177 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1178
1179 if (pop_reader_sp != reader_sp)
1180 return false;
1181
1182 reader_sp->Deactivate();
1183 reader_sp->Cancel();
1184 m_io_handler_stack.Pop();
1185
1186 reader_sp = m_io_handler_stack.Top();
1187 if (reader_sp)
1188 reader_sp->Activate();
1189
1190 return true;
1191 }
1192
GetAsyncOutputStream()1193 StreamSP Debugger::GetAsyncOutputStream() {
1194 return std::make_shared<StreamAsynchronousIO>(*this, true, GetUseColor());
1195 }
1196
GetAsyncErrorStream()1197 StreamSP Debugger::GetAsyncErrorStream() {
1198 return std::make_shared<StreamAsynchronousIO>(*this, false, GetUseColor());
1199 }
1200
GetNumDebuggers()1201 size_t Debugger::GetNumDebuggers() {
1202 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1203 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1204 return g_debugger_list_ptr->size();
1205 }
1206 return 0;
1207 }
1208
GetDebuggerAtIndex(size_t index)1209 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1210 DebuggerSP debugger_sp;
1211
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 if (index < g_debugger_list_ptr->size())
1215 debugger_sp = g_debugger_list_ptr->at(index);
1216 }
1217
1218 return debugger_sp;
1219 }
1220
FindDebuggerWithID(lldb::user_id_t id)1221 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1222 DebuggerSP debugger_sp;
1223
1224 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1225 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1226 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1227 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1228 if ((*pos)->GetID() == id) {
1229 debugger_sp = *pos;
1230 break;
1231 }
1232 }
1233 }
1234 return debugger_sp;
1235 }
1236
FormatDisassemblerAddress(const FormatEntity::Entry * format,const SymbolContext * sc,const SymbolContext * prev_sc,const ExecutionContext * exe_ctx,const Address * addr,Stream & s)1237 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1238 const SymbolContext *sc,
1239 const SymbolContext *prev_sc,
1240 const ExecutionContext *exe_ctx,
1241 const Address *addr, Stream &s) {
1242 FormatEntity::Entry format_entry;
1243
1244 if (format == nullptr) {
1245 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1246 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1247 if (format == nullptr) {
1248 FormatEntity::Parse("${addr}: ", format_entry);
1249 format = &format_entry;
1250 }
1251 }
1252 bool function_changed = false;
1253 bool initial_function = false;
1254 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1255 if (sc && (sc->function || sc->symbol)) {
1256 if (prev_sc->symbol && sc->symbol) {
1257 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1258 prev_sc->symbol->GetType())) {
1259 function_changed = true;
1260 }
1261 } else if (prev_sc->function && sc->function) {
1262 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1263 function_changed = true;
1264 }
1265 }
1266 }
1267 }
1268 // The first context on a list of instructions will have a prev_sc that has
1269 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1270 // would return false. But we do get a prev_sc pointer.
1271 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1272 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1273 initial_function = true;
1274 }
1275 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1276 function_changed, initial_function);
1277 }
1278
SetLoggingCallback(lldb::LogOutputCallback log_callback,void * baton)1279 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1280 void *baton) {
1281 // For simplicity's sake, I am not going to deal with how to close down any
1282 // open logging streams, I just redirect everything from here on out to the
1283 // callback.
1284 m_callback_handler_sp =
1285 std::make_shared<CallbackLogHandler>(log_callback, baton);
1286 }
1287
PrivateReportProgress(Debugger & debugger,uint64_t progress_id,const std::string & message,uint64_t completed,uint64_t total,bool is_debugger_specific)1288 static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1289 const std::string &message,
1290 uint64_t completed, uint64_t total,
1291 bool is_debugger_specific) {
1292 // Only deliver progress events if we have any progress listeners.
1293 const uint32_t event_type = Debugger::eBroadcastBitProgress;
1294 if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type))
1295 return;
1296 EventSP event_sp(new Event(
1297 event_type, new ProgressEventData(progress_id, message, completed, total,
1298 is_debugger_specific)));
1299 debugger.GetBroadcaster().BroadcastEvent(event_sp);
1300 }
1301
ReportProgress(uint64_t progress_id,const std::string & message,uint64_t completed,uint64_t total,std::optional<lldb::user_id_t> debugger_id)1302 void Debugger::ReportProgress(uint64_t progress_id, const std::string &message,
1303 uint64_t completed, uint64_t total,
1304 std::optional<lldb::user_id_t> debugger_id) {
1305 // Check if this progress is for a specific debugger.
1306 if (debugger_id) {
1307 // It is debugger specific, grab it and deliver the event if the debugger
1308 // still exists.
1309 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1310 if (debugger_sp)
1311 PrivateReportProgress(*debugger_sp, progress_id, message, completed,
1312 total, /*is_debugger_specific*/ true);
1313 return;
1314 }
1315 // The progress event is not debugger specific, iterate over all debuggers
1316 // and deliver a progress event to each one.
1317 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1318 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1319 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1320 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos)
1321 PrivateReportProgress(*(*pos), progress_id, message, completed, total,
1322 /*is_debugger_specific*/ false);
1323 }
1324 }
1325
PrivateReportDiagnostic(Debugger & debugger,DiagnosticEventData::Type type,std::string message,bool debugger_specific)1326 static void PrivateReportDiagnostic(Debugger &debugger,
1327 DiagnosticEventData::Type type,
1328 std::string message,
1329 bool debugger_specific) {
1330 uint32_t event_type = 0;
1331 switch (type) {
1332 case DiagnosticEventData::Type::Info:
1333 assert(false && "DiagnosticEventData::Type::Info should not be broadcast");
1334 return;
1335 case DiagnosticEventData::Type::Warning:
1336 event_type = Debugger::eBroadcastBitWarning;
1337 break;
1338 case DiagnosticEventData::Type::Error:
1339 event_type = Debugger::eBroadcastBitError;
1340 break;
1341 }
1342
1343 Broadcaster &broadcaster = debugger.GetBroadcaster();
1344 if (!broadcaster.EventTypeHasListeners(event_type)) {
1345 // Diagnostics are too important to drop. If nobody is listening, print the
1346 // diagnostic directly to the debugger's error stream.
1347 DiagnosticEventData event_data(type, std::move(message), debugger_specific);
1348 StreamSP stream = debugger.GetAsyncErrorStream();
1349 event_data.Dump(stream.get());
1350 return;
1351 }
1352 EventSP event_sp = std::make_shared<Event>(
1353 event_type,
1354 new DiagnosticEventData(type, std::move(message), debugger_specific));
1355 broadcaster.BroadcastEvent(event_sp);
1356 }
1357
ReportDiagnosticImpl(DiagnosticEventData::Type type,std::string message,std::optional<lldb::user_id_t> debugger_id,std::once_flag * once)1358 void Debugger::ReportDiagnosticImpl(DiagnosticEventData::Type type,
1359 std::string message,
1360 std::optional<lldb::user_id_t> debugger_id,
1361 std::once_flag *once) {
1362 auto ReportDiagnosticLambda = [&]() {
1363 // The diagnostic subsystem is optional but we still want to broadcast
1364 // events when it's disabled.
1365 if (Diagnostics::Enabled())
1366 Diagnostics::Instance().Report(message);
1367
1368 // We don't broadcast info events.
1369 if (type == DiagnosticEventData::Type::Info)
1370 return;
1371
1372 // Check if this diagnostic is for a specific debugger.
1373 if (debugger_id) {
1374 // It is debugger specific, grab it and deliver the event if the debugger
1375 // still exists.
1376 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1377 if (debugger_sp)
1378 PrivateReportDiagnostic(*debugger_sp, type, std::move(message), true);
1379 return;
1380 }
1381 // The diagnostic event is not debugger specific, iterate over all debuggers
1382 // and deliver a diagnostic event to each one.
1383 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1384 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1385 for (const auto &debugger : *g_debugger_list_ptr)
1386 PrivateReportDiagnostic(*debugger, type, message, false);
1387 }
1388 };
1389
1390 if (once)
1391 std::call_once(*once, ReportDiagnosticLambda);
1392 else
1393 ReportDiagnosticLambda();
1394 }
1395
ReportWarning(std::string message,std::optional<lldb::user_id_t> debugger_id,std::once_flag * once)1396 void Debugger::ReportWarning(std::string message,
1397 std::optional<lldb::user_id_t> debugger_id,
1398 std::once_flag *once) {
1399 ReportDiagnosticImpl(DiagnosticEventData::Type::Warning, std::move(message),
1400 debugger_id, once);
1401 }
1402
ReportError(std::string message,std::optional<lldb::user_id_t> debugger_id,std::once_flag * once)1403 void Debugger::ReportError(std::string message,
1404 std::optional<lldb::user_id_t> debugger_id,
1405 std::once_flag *once) {
1406 ReportDiagnosticImpl(DiagnosticEventData::Type::Error, std::move(message),
1407 debugger_id, once);
1408 }
1409
ReportInfo(std::string message,std::optional<lldb::user_id_t> debugger_id,std::once_flag * once)1410 void Debugger::ReportInfo(std::string message,
1411 std::optional<lldb::user_id_t> debugger_id,
1412 std::once_flag *once) {
1413 ReportDiagnosticImpl(DiagnosticEventData::Type::Info, std::move(message),
1414 debugger_id, once);
1415 }
1416
ReportSymbolChange(const ModuleSpec & module_spec)1417 void 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
1429 static std::shared_ptr<LogHandler>
CreateLogHandler(LogHandlerKind log_handler_kind,int fd,bool should_close,size_t buffer_size)1430 CreateLogHandler(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
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)1445 bool 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
1495 ScriptInterpreter *
GetScriptInterpreter(bool can_create,std::optional<lldb::ScriptLanguage> language)1496 Debugger::GetScriptInterpreter(bool can_create,
1497 std::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
GetSourceManager()1512 SourceManager &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.
HandleBreakpointEvent(const EventSP & event_sp)1519 void 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
FlushProcessOutput(Process & process,bool flush_stdout,bool flush_stderr)1566 void 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.
HandleProcessEvent(const EventSP & event_sp)1586 void 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
HandleThreadEvent(const EventSP & event_sp)1669 void 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
IsForwardingEvents()1685 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1686
EnableForwardEvents(const ListenerSP & listener_sp)1687 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1688 m_forward_listener_sp = listener_sp;
1689 }
1690
CancelForwardEvents(const ListenerSP & listener_sp)1691 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1692 m_forward_listener_sp.reset();
1693 }
1694
DefaultEventHandler()1695 lldb::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, std::nullopt)) {
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
StartEventHandlerThread()1795 bool 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, std::nullopt);
1831 }
1832 return m_event_handler_thread.IsJoinable();
1833 }
1834
StopEventHandlerThread()1835 void 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
IOHandlerThread()1843 lldb::thread_result_t Debugger::IOHandlerThread() {
1844 RunIOHandlers();
1845 StopEventHandlerThread();
1846 return {};
1847 }
1848
HandleProgressEvent(const lldb::EventSP & event_sp)1849 void 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
HandleDiagnosticEvent(const lldb::EventSP & event_sp)1934 void 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
HasIOHandlerThread()1943 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1944
StartIOHandlerThread()1945 bool 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
StopIOHandlerThread()1960 void Debugger::StopIOHandlerThread() {
1961 if (m_io_handler_thread.IsJoinable()) {
1962 GetInputFile().Close();
1963 m_io_handler_thread.Join(nullptr);
1964 }
1965 }
1966
JoinIOHandlerThread()1967 void 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
GetSelectedOrDummyTarget(bool prefer_dummy)1975 Target &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
RunREPL(LanguageType language,const char * repl_options)1983 Status 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
GetThreadPool()2027 llvm::ThreadPool &Debugger::GetThreadPool() {
2028 assert(g_thread_pool &&
2029 "Debugger::GetThreadPool called before Debugger::Initialize");
2030 return *g_thread_pool;
2031 }
2032