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/FormatEntity.h"
13 #include "lldb/Core/Mangled.h"
14 #include "lldb/Core/ModuleList.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/Core/StreamAsynchronousIO.h"
17 #include "lldb/Core/StreamFile.h"
18 #include "lldb/DataFormatters/DataVisualization.h"
19 #include "lldb/Expression/REPL.h"
20 #include "lldb/Host/File.h"
21 #include "lldb/Host/FileSystem.h"
22 #include "lldb/Host/HostInfo.h"
23 #include "lldb/Host/Terminal.h"
24 #include "lldb/Host/ThreadLauncher.h"
25 #include "lldb/Interpreter/CommandInterpreter.h"
26 #include "lldb/Interpreter/OptionValue.h"
27 #include "lldb/Interpreter/OptionValueProperties.h"
28 #include "lldb/Interpreter/OptionValueSInt64.h"
29 #include "lldb/Interpreter/OptionValueString.h"
30 #include "lldb/Interpreter/Property.h"
31 #include "lldb/Interpreter/ScriptInterpreter.h"
32 #include "lldb/Symbol/Function.h"
33 #include "lldb/Symbol/Symbol.h"
34 #include "lldb/Symbol/SymbolContext.h"
35 #include "lldb/Target/Language.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/StructuredDataPlugin.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/TargetList.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Target/ThreadList.h"
42 #include "lldb/Utility/AnsiTerminal.h"
43 #include "lldb/Utility/Event.h"
44 #include "lldb/Utility/Listener.h"
45 #include "lldb/Utility/Log.h"
46 #include "lldb/Utility/Reproducer.h"
47 #include "lldb/Utility/State.h"
48 #include "lldb/Utility/Stream.h"
49 #include "lldb/Utility/StreamCallback.h"
50 #include "lldb/Utility/StreamString.h"
51
52 #if defined(_WIN32)
53 #include "lldb/Host/windows/PosixApi.h"
54 #include "lldb/Host/windows/windows.h"
55 #endif
56
57 #include "llvm/ADT/None.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/iterator.h"
61 #include "llvm/Support/DynamicLibrary.h"
62 #include "llvm/Support/FileSystem.h"
63 #include "llvm/Support/Process.h"
64 #include "llvm/Support/Threading.h"
65 #include "llvm/Support/raw_ostream.h"
66
67 #include <list>
68 #include <memory>
69 #include <mutex>
70 #include <set>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <string>
75 #include <system_error>
76
77 namespace lldb_private {
78 class Address;
79 }
80
81 using namespace lldb;
82 using namespace lldb_private;
83
84 static lldb::user_id_t g_unique_id = 1;
85 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
86
87 #pragma mark Static Functions
88
89 typedef std::vector<DebuggerSP> DebuggerList;
90 static std::recursive_mutex *g_debugger_list_mutex_ptr =
91 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
92 static DebuggerList *g_debugger_list_ptr =
93 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
94
95 static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
96 {
97 Debugger::eStopDisassemblyTypeNever,
98 "never",
99 "Never show disassembly when displaying a stop context.",
100 },
101 {
102 Debugger::eStopDisassemblyTypeNoDebugInfo,
103 "no-debuginfo",
104 "Show disassembly when there is no debug information.",
105 },
106 {
107 Debugger::eStopDisassemblyTypeNoSource,
108 "no-source",
109 "Show disassembly when there is no source information, or the source "
110 "file "
111 "is missing when displaying a stop context.",
112 },
113 {
114 Debugger::eStopDisassemblyTypeAlways,
115 "always",
116 "Always show disassembly when displaying a stop context.",
117 },
118 };
119
120 static constexpr OptionEnumValueElement g_language_enumerators[] = {
121 {
122 eScriptLanguageNone,
123 "none",
124 "Disable scripting languages.",
125 },
126 {
127 eScriptLanguagePython,
128 "python",
129 "Select python as the default scripting language.",
130 },
131 {
132 eScriptLanguageDefault,
133 "default",
134 "Select the lldb default as the default scripting language.",
135 },
136 };
137
138 static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
139 {
140 eStopShowColumnAnsiOrCaret,
141 "ansi-or-caret",
142 "Highlight the stop column with ANSI terminal codes when color/ANSI "
143 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
144 "as if \"caret-only\" mode was selected.",
145 },
146 {
147 eStopShowColumnAnsi,
148 "ansi",
149 "Highlight the stop column with ANSI terminal codes when running LLDB "
150 "with color/ANSI enabled.",
151 },
152 {
153 eStopShowColumnCaret,
154 "caret",
155 "Highlight the stop column with a caret character (^) underneath the "
156 "stop column. This method introduces a new line in source listings "
157 "that display thread stop locations.",
158 },
159 {
160 eStopShowColumnNone,
161 "none",
162 "Do not highlight the stop column.",
163 },
164 };
165
166 #define LLDB_PROPERTIES_debugger
167 #include "CoreProperties.inc"
168
169 enum {
170 #define LLDB_PROPERTIES_debugger
171 #include "CorePropertiesEnum.inc"
172 };
173
174 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
175
SetPropertyValue(const ExecutionContext * exe_ctx,VarSetOperationType op,llvm::StringRef property_path,llvm::StringRef value)176 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
177 VarSetOperationType op,
178 llvm::StringRef property_path,
179 llvm::StringRef value) {
180 bool is_load_script =
181 (property_path == "target.load-script-from-symbol-file");
182 // These properties might change how we visualize data.
183 bool invalidate_data_vis = (property_path == "escape-non-printables");
184 invalidate_data_vis |=
185 (property_path == "target.max-zero-padding-in-float-format");
186 if (invalidate_data_vis) {
187 DataVisualization::ForceUpdate();
188 }
189
190 TargetSP target_sp;
191 LoadScriptFromSymFile load_script_old_value;
192 if (is_load_script && exe_ctx->GetTargetSP()) {
193 target_sp = exe_ctx->GetTargetSP();
194 load_script_old_value =
195 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
196 }
197 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
198 if (error.Success()) {
199 // FIXME it would be nice to have "on-change" callbacks for properties
200 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
201 llvm::StringRef new_prompt = GetPrompt();
202 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes(
203 new_prompt, GetUseColor());
204 if (str.length())
205 new_prompt = str;
206 GetCommandInterpreter().UpdatePrompt(new_prompt);
207 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
208 auto prompt_change_event_sp = std::make_shared<Event>(
209 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
210 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
211 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
212 // use-color changed. Ping the prompt so it can reset the ansi terminal
213 // codes.
214 SetPrompt(GetPrompt());
215 } else if (property_path == g_debugger_properties[ePropertyUseSourceCache].name) {
216 // use-source-cache changed. Wipe out the cache contents if it was disabled.
217 if (!GetUseSourceCache()) {
218 m_source_file_cache.Clear();
219 }
220 } else if (is_load_script && target_sp &&
221 load_script_old_value == eLoadScriptFromSymFileWarn) {
222 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
223 eLoadScriptFromSymFileTrue) {
224 std::list<Status> errors;
225 StreamString feedback_stream;
226 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
227 Stream &s = GetErrorStream();
228 for (auto error : errors) {
229 s.Printf("%s\n", error.AsCString());
230 }
231 if (feedback_stream.GetSize())
232 s.PutCString(feedback_stream.GetString());
233 }
234 }
235 }
236 }
237 return error;
238 }
239
GetAutoConfirm() const240 bool Debugger::GetAutoConfirm() const {
241 const uint32_t idx = ePropertyAutoConfirm;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean(
243 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
244 }
245
GetDisassemblyFormat() const246 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
247 const uint32_t idx = ePropertyDisassemblyFormat;
248 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
249 }
250
GetFrameFormat() const251 const FormatEntity::Entry *Debugger::GetFrameFormat() const {
252 const uint32_t idx = ePropertyFrameFormat;
253 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
254 }
255
GetFrameFormatUnique() const256 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
257 const uint32_t idx = ePropertyFrameFormatUnique;
258 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
259 }
260
GetNotifyVoid() const261 bool Debugger::GetNotifyVoid() const {
262 const uint32_t idx = ePropertyNotiftVoid;
263 return m_collection_sp->GetPropertyAtIndexAsBoolean(
264 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
265 }
266
GetPrompt() const267 llvm::StringRef Debugger::GetPrompt() const {
268 const uint32_t idx = ePropertyPrompt;
269 return m_collection_sp->GetPropertyAtIndexAsString(
270 nullptr, idx, g_debugger_properties[idx].default_cstr_value);
271 }
272
SetPrompt(llvm::StringRef p)273 void Debugger::SetPrompt(llvm::StringRef p) {
274 const uint32_t idx = ePropertyPrompt;
275 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
276 llvm::StringRef new_prompt = GetPrompt();
277 std::string str =
278 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
279 if (str.length())
280 new_prompt = str;
281 GetCommandInterpreter().UpdatePrompt(new_prompt);
282 }
283
GetReproducerPath() const284 llvm::StringRef Debugger::GetReproducerPath() const {
285 auto &r = repro::Reproducer::Instance();
286 return r.GetReproducerPath().GetCString();
287 }
288
GetThreadFormat() const289 const FormatEntity::Entry *Debugger::GetThreadFormat() const {
290 const uint32_t idx = ePropertyThreadFormat;
291 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
292 }
293
GetThreadStopFormat() const294 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
295 const uint32_t idx = ePropertyThreadStopFormat;
296 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
297 }
298
GetScriptLanguage() const299 lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
300 const uint32_t idx = ePropertyScriptLanguage;
301 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
302 nullptr, idx, g_debugger_properties[idx].default_uint_value);
303 }
304
SetScriptLanguage(lldb::ScriptLanguage script_lang)305 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
306 const uint32_t idx = ePropertyScriptLanguage;
307 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
308 script_lang);
309 }
310
GetTerminalWidth() const311 uint32_t Debugger::GetTerminalWidth() const {
312 const uint32_t idx = ePropertyTerminalWidth;
313 return m_collection_sp->GetPropertyAtIndexAsSInt64(
314 nullptr, idx, g_debugger_properties[idx].default_uint_value);
315 }
316
SetTerminalWidth(uint32_t term_width)317 bool Debugger::SetTerminalWidth(uint32_t term_width) {
318 if (auto handler_sp = m_io_handler_stack.Top())
319 handler_sp->TerminalSizeChanged();
320
321 const uint32_t idx = ePropertyTerminalWidth;
322 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
323 }
324
GetUseExternalEditor() const325 bool Debugger::GetUseExternalEditor() const {
326 const uint32_t idx = ePropertyUseExternalEditor;
327 return m_collection_sp->GetPropertyAtIndexAsBoolean(
328 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
329 }
330
SetUseExternalEditor(bool b)331 bool Debugger::SetUseExternalEditor(bool b) {
332 const uint32_t idx = ePropertyUseExternalEditor;
333 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
334 }
335
GetUseColor() const336 bool Debugger::GetUseColor() const {
337 const uint32_t idx = ePropertyUseColor;
338 return m_collection_sp->GetPropertyAtIndexAsBoolean(
339 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
340 }
341
SetUseColor(bool b)342 bool Debugger::SetUseColor(bool b) {
343 const uint32_t idx = ePropertyUseColor;
344 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
345 SetPrompt(GetPrompt());
346 return ret;
347 }
348
GetUseAutosuggestion() const349 bool Debugger::GetUseAutosuggestion() const {
350 const uint32_t idx = ePropertyShowAutosuggestion;
351 return m_collection_sp->GetPropertyAtIndexAsBoolean(
352 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
353 }
354
GetUseSourceCache() const355 bool Debugger::GetUseSourceCache() const {
356 const uint32_t idx = ePropertyUseSourceCache;
357 return m_collection_sp->GetPropertyAtIndexAsBoolean(
358 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
359 }
360
SetUseSourceCache(bool b)361 bool Debugger::SetUseSourceCache(bool b) {
362 const uint32_t idx = ePropertyUseSourceCache;
363 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
364 if (!ret) {
365 m_source_file_cache.Clear();
366 }
367 return ret;
368 }
GetHighlightSource() const369 bool Debugger::GetHighlightSource() const {
370 const uint32_t idx = ePropertyHighlightSource;
371 return m_collection_sp->GetPropertyAtIndexAsBoolean(
372 nullptr, idx, g_debugger_properties[idx].default_uint_value);
373 }
374
GetStopShowColumn() const375 StopShowColumn Debugger::GetStopShowColumn() const {
376 const uint32_t idx = ePropertyStopShowColumn;
377 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
378 nullptr, idx, g_debugger_properties[idx].default_uint_value);
379 }
380
GetStopShowColumnAnsiPrefix() const381 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
382 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
383 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
384 }
385
GetStopShowColumnAnsiSuffix() const386 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
387 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
388 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
389 }
390
GetStopShowLineMarkerAnsiPrefix() const391 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const {
392 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
393 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
394 }
395
GetStopShowLineMarkerAnsiSuffix() const396 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const {
397 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
398 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
399 }
400
GetStopSourceLineCount(bool before) const401 uint32_t Debugger::GetStopSourceLineCount(bool before) const {
402 const uint32_t idx =
403 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
404 return m_collection_sp->GetPropertyAtIndexAsSInt64(
405 nullptr, idx, g_debugger_properties[idx].default_uint_value);
406 }
407
GetStopDisassemblyDisplay() const408 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
409 const uint32_t idx = ePropertyStopDisassemblyDisplay;
410 return (Debugger::StopDisassemblyType)
411 m_collection_sp->GetPropertyAtIndexAsEnumeration(
412 nullptr, idx, g_debugger_properties[idx].default_uint_value);
413 }
414
GetDisassemblyLineCount() const415 uint32_t Debugger::GetDisassemblyLineCount() const {
416 const uint32_t idx = ePropertyStopDisassemblyCount;
417 return m_collection_sp->GetPropertyAtIndexAsSInt64(
418 nullptr, idx, g_debugger_properties[idx].default_uint_value);
419 }
420
GetAutoOneLineSummaries() const421 bool Debugger::GetAutoOneLineSummaries() const {
422 const uint32_t idx = ePropertyAutoOneLineSummaries;
423 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
424 }
425
GetEscapeNonPrintables() const426 bool Debugger::GetEscapeNonPrintables() const {
427 const uint32_t idx = ePropertyEscapeNonPrintables;
428 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
429 }
430
GetAutoIndent() const431 bool Debugger::GetAutoIndent() const {
432 const uint32_t idx = ePropertyAutoIndent;
433 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
434 }
435
SetAutoIndent(bool b)436 bool Debugger::SetAutoIndent(bool b) {
437 const uint32_t idx = ePropertyAutoIndent;
438 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
439 }
440
GetPrintDecls() const441 bool Debugger::GetPrintDecls() const {
442 const uint32_t idx = ePropertyPrintDecls;
443 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
444 }
445
SetPrintDecls(bool b)446 bool Debugger::SetPrintDecls(bool b) {
447 const uint32_t idx = ePropertyPrintDecls;
448 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
449 }
450
GetTabSize() const451 uint32_t Debugger::GetTabSize() const {
452 const uint32_t idx = ePropertyTabSize;
453 return m_collection_sp->GetPropertyAtIndexAsUInt64(
454 nullptr, idx, g_debugger_properties[idx].default_uint_value);
455 }
456
SetTabSize(uint32_t tab_size)457 bool Debugger::SetTabSize(uint32_t tab_size) {
458 const uint32_t idx = ePropertyTabSize;
459 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
460 }
461
462 #pragma mark Debugger
463
464 // const DebuggerPropertiesSP &
465 // Debugger::GetSettings() const
466 //{
467 // return m_properties_sp;
468 //}
469 //
470
Initialize(LoadPluginCallbackType load_plugin_callback)471 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
472 assert(g_debugger_list_ptr == nullptr &&
473 "Debugger::Initialize called more than once!");
474 g_debugger_list_mutex_ptr = new std::recursive_mutex();
475 g_debugger_list_ptr = new DebuggerList();
476 g_load_plugin_callback = load_plugin_callback;
477 }
478
Terminate()479 void Debugger::Terminate() {
480 assert(g_debugger_list_ptr &&
481 "Debugger::Terminate called without a matching Debugger::Initialize!");
482
483 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
484 // Clear our master list of debugger objects
485 {
486 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
487 for (const auto &debugger : *g_debugger_list_ptr)
488 debugger->Clear();
489 g_debugger_list_ptr->clear();
490 }
491 }
492 }
493
SettingsInitialize()494 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
495
SettingsTerminate()496 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
497
LoadPlugin(const FileSpec & spec,Status & error)498 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
499 if (g_load_plugin_callback) {
500 llvm::sys::DynamicLibrary dynlib =
501 g_load_plugin_callback(shared_from_this(), spec, error);
502 if (dynlib.isValid()) {
503 m_loaded_plugins.push_back(dynlib);
504 return true;
505 }
506 } else {
507 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
508 // if the public API layer isn't available (code is linking against all of
509 // the internal LLDB static libraries), then we can't load plugins
510 error.SetErrorString("Public API layer is not available");
511 }
512 return false;
513 }
514
515 static FileSystem::EnumerateDirectoryResult
LoadPluginCallback(void * baton,llvm::sys::fs::file_type ft,llvm::StringRef path)516 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
517 llvm::StringRef path) {
518 Status error;
519
520 static ConstString g_dylibext(".dylib");
521 static ConstString g_solibext(".so");
522
523 if (!baton)
524 return FileSystem::eEnumerateDirectoryResultQuit;
525
526 Debugger *debugger = (Debugger *)baton;
527
528 namespace fs = llvm::sys::fs;
529 // If we have a regular file, a symbolic link or unknown file type, try and
530 // process the file. We must handle unknown as sometimes the directory
531 // enumeration might be enumerating a file system that doesn't have correct
532 // file type information.
533 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
534 ft == fs::file_type::type_unknown) {
535 FileSpec plugin_file_spec(path);
536 FileSystem::Instance().Resolve(plugin_file_spec);
537
538 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
539 plugin_file_spec.GetFileNameExtension() != g_solibext) {
540 return FileSystem::eEnumerateDirectoryResultNext;
541 }
542
543 Status plugin_load_error;
544 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
545
546 return FileSystem::eEnumerateDirectoryResultNext;
547 } else if (ft == fs::file_type::directory_file ||
548 ft == fs::file_type::symlink_file ||
549 ft == fs::file_type::type_unknown) {
550 // Try and recurse into anything that a directory or symbolic link. We must
551 // also do this for unknown as sometimes the directory enumeration might be
552 // enumerating a file system that doesn't have correct file type
553 // information.
554 return FileSystem::eEnumerateDirectoryResultEnter;
555 }
556
557 return FileSystem::eEnumerateDirectoryResultNext;
558 }
559
InstanceInitialize()560 void Debugger::InstanceInitialize() {
561 const bool find_directories = true;
562 const bool find_files = true;
563 const bool find_other = true;
564 char dir_path[PATH_MAX];
565 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
566 if (FileSystem::Instance().Exists(dir_spec) &&
567 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
568 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
569 find_files, find_other,
570 LoadPluginCallback, this);
571 }
572 }
573
574 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
575 if (FileSystem::Instance().Exists(dir_spec) &&
576 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
577 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
578 find_files, find_other,
579 LoadPluginCallback, this);
580 }
581 }
582
583 PluginManager::DebuggerInitialize(*this);
584 }
585
CreateInstance(lldb::LogOutputCallback log_callback,void * baton)586 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
587 void *baton) {
588 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
589 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
590 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
591 g_debugger_list_ptr->push_back(debugger_sp);
592 }
593 debugger_sp->InstanceInitialize();
594 return debugger_sp;
595 }
596
Destroy(DebuggerSP & debugger_sp)597 void Debugger::Destroy(DebuggerSP &debugger_sp) {
598 if (!debugger_sp)
599 return;
600
601 debugger_sp->Clear();
602
603 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
604 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
605 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
606 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
607 if ((*pos).get() == debugger_sp.get()) {
608 g_debugger_list_ptr->erase(pos);
609 return;
610 }
611 }
612 }
613 }
614
FindDebuggerWithInstanceName(ConstString instance_name)615 DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
616 DebuggerSP debugger_sp;
617 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
618 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
619 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
620 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
621 if ((*pos)->m_instance_name == instance_name) {
622 debugger_sp = *pos;
623 break;
624 }
625 }
626 }
627 return debugger_sp;
628 }
629
FindTargetWithProcessID(lldb::pid_t pid)630 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
631 TargetSP target_sp;
632 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
633 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
634 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
635 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
636 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
637 if (target_sp)
638 break;
639 }
640 }
641 return target_sp;
642 }
643
FindTargetWithProcess(Process * process)644 TargetSP Debugger::FindTargetWithProcess(Process *process) {
645 TargetSP target_sp;
646 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
647 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
648 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
649 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
650 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
651 if (target_sp)
652 break;
653 }
654 }
655 return target_sp;
656 }
657
Debugger(lldb::LogOutputCallback log_callback,void * baton)658 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
659 : UserID(g_unique_id++),
660 Properties(std::make_shared<OptionValueProperties>()),
661 m_input_file_sp(std::make_shared<NativeFile>(stdin, false)),
662 m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)),
663 m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)),
664 m_input_recorder(nullptr),
665 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
666 m_terminal_state(), m_target_list(*this), m_platform_list(),
667 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
668 m_source_manager_up(), m_source_file_cache(),
669 m_command_interpreter_up(
670 std::make_unique<CommandInterpreter>(*this, false)),
671 m_io_handler_stack(), m_instance_name(), m_loaded_plugins(),
672 m_event_handler_thread(), m_io_handler_thread(),
673 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
674 m_forward_listener_sp(), m_clear_once() {
675 m_instance_name.SetString(llvm::formatv("debugger_{0}", GetID()).str());
676 if (log_callback)
677 m_log_callback_stream_sp =
678 std::make_shared<StreamCallback>(log_callback, baton);
679 m_command_interpreter_up->Initialize();
680 // Always add our default platform to the platform list
681 PlatformSP default_platform_sp(Platform::GetHostPlatform());
682 assert(default_platform_sp);
683 m_platform_list.Append(default_platform_sp, true);
684
685 // Create the dummy target.
686 {
687 ArchSpec arch(Target::GetDefaultArchitecture());
688 if (!arch.IsValid())
689 arch = HostInfo::GetArchitecture();
690 assert(arch.IsValid() && "No valid default or host archspec");
691 const bool is_dummy_target = true;
692 m_dummy_target_sp.reset(
693 new Target(*this, arch, default_platform_sp, is_dummy_target));
694 }
695 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
696
697 m_collection_sp->Initialize(g_debugger_properties);
698 m_collection_sp->AppendProperty(
699 ConstString("target"),
700 ConstString("Settings specify to debugging targets."), true,
701 Target::GetGlobalProperties()->GetValueProperties());
702 m_collection_sp->AppendProperty(
703 ConstString("platform"), ConstString("Platform settings."), true,
704 Platform::GetGlobalPlatformProperties()->GetValueProperties());
705 m_collection_sp->AppendProperty(
706 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
707 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
708 if (m_command_interpreter_up) {
709 m_collection_sp->AppendProperty(
710 ConstString("interpreter"),
711 ConstString("Settings specify to the debugger's command interpreter."),
712 true, m_command_interpreter_up->GetValueProperties());
713 }
714 OptionValueSInt64 *term_width =
715 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
716 nullptr, ePropertyTerminalWidth);
717 term_width->SetMinimumValue(10);
718 term_width->SetMaximumValue(1024);
719
720 // Turn off use-color if this is a dumb terminal.
721 const char *term = getenv("TERM");
722 if (term && !strcmp(term, "dumb"))
723 SetUseColor(false);
724 // Turn off use-color if we don't write to a terminal with color support.
725 if (!GetOutputFile().GetIsTerminalWithColors())
726 SetUseColor(false);
727
728 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
729 // Enabling use of ANSI color codes because LLDB is using them to highlight
730 // text.
731 llvm::sys::Process::UseANSIEscapeCodes(true);
732 #endif
733 }
734
~Debugger()735 Debugger::~Debugger() { Clear(); }
736
Clear()737 void Debugger::Clear() {
738 // Make sure we call this function only once. With the C++ global destructor
739 // chain having a list of debuggers and with code that can be running on
740 // other threads, we need to ensure this doesn't happen multiple times.
741 //
742 // The following functions call Debugger::Clear():
743 // Debugger::~Debugger();
744 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
745 // static void Debugger::Terminate();
746 llvm::call_once(m_clear_once, [this]() {
747 ClearIOHandlers();
748 StopIOHandlerThread();
749 StopEventHandlerThread();
750 m_listener_sp->Clear();
751 int num_targets = m_target_list.GetNumTargets();
752 for (int i = 0; i < num_targets; i++) {
753 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
754 if (target_sp) {
755 ProcessSP process_sp(target_sp->GetProcessSP());
756 if (process_sp)
757 process_sp->Finalize();
758 target_sp->Destroy();
759 }
760 }
761 m_broadcaster_manager_sp->Clear();
762
763 // Close the input file _before_ we close the input read communications
764 // class as it does NOT own the input file, our m_input_file does.
765 m_terminal_state.Clear();
766 GetInputFile().Close();
767
768 m_command_interpreter_up->Clear();
769 });
770 }
771
GetCloseInputOnEOF() const772 bool Debugger::GetCloseInputOnEOF() const {
773 // return m_input_comm.GetCloseOnEOF();
774 return false;
775 }
776
SetCloseInputOnEOF(bool b)777 void Debugger::SetCloseInputOnEOF(bool b) {
778 // m_input_comm.SetCloseOnEOF(b);
779 }
780
GetAsyncExecution()781 bool Debugger::GetAsyncExecution() {
782 return !m_command_interpreter_up->GetSynchronous();
783 }
784
SetAsyncExecution(bool async_execution)785 void Debugger::SetAsyncExecution(bool async_execution) {
786 m_command_interpreter_up->SetSynchronous(!async_execution);
787 }
788
GetInputRecorder()789 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
790
SetInputFile(FileSP file_sp,repro::DataRecorder * recorder)791 void Debugger::SetInputFile(FileSP file_sp, repro::DataRecorder *recorder) {
792 assert(file_sp && file_sp->IsValid());
793 m_input_recorder = recorder;
794 m_input_file_sp = std::move(file_sp);
795 // Save away the terminal state if that is relevant, so that we can restore
796 // it in RestoreInputState.
797 SaveInputTerminalState();
798 }
799
SetOutputFile(FileSP file_sp)800 void Debugger::SetOutputFile(FileSP file_sp) {
801 assert(file_sp && file_sp->IsValid());
802 m_output_stream_sp = std::make_shared<StreamFile>(file_sp);
803 }
804
SetErrorFile(FileSP file_sp)805 void Debugger::SetErrorFile(FileSP file_sp) {
806 assert(file_sp && file_sp->IsValid());
807 m_error_stream_sp = std::make_shared<StreamFile>(file_sp);
808 }
809
SaveInputTerminalState()810 void Debugger::SaveInputTerminalState() {
811 int fd = GetInputFile().GetDescriptor();
812 if (fd != File::kInvalidDescriptor)
813 m_terminal_state.Save(fd, true);
814 }
815
RestoreInputTerminalState()816 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
817
GetSelectedExecutionContext()818 ExecutionContext Debugger::GetSelectedExecutionContext() {
819 ExecutionContext exe_ctx;
820 TargetSP target_sp(GetSelectedTarget());
821 exe_ctx.SetTargetSP(target_sp);
822
823 if (target_sp) {
824 ProcessSP process_sp(target_sp->GetProcessSP());
825 exe_ctx.SetProcessSP(process_sp);
826 if (process_sp && !process_sp->IsRunning()) {
827 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
828 if (thread_sp) {
829 exe_ctx.SetThreadSP(thread_sp);
830 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
831 if (exe_ctx.GetFramePtr() == nullptr)
832 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
833 }
834 }
835 }
836 return exe_ctx;
837 }
838
DispatchInputInterrupt()839 void Debugger::DispatchInputInterrupt() {
840 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
841 IOHandlerSP reader_sp(m_io_handler_stack.Top());
842 if (reader_sp)
843 reader_sp->Interrupt();
844 }
845
DispatchInputEndOfFile()846 void Debugger::DispatchInputEndOfFile() {
847 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
848 IOHandlerSP reader_sp(m_io_handler_stack.Top());
849 if (reader_sp)
850 reader_sp->GotEOF();
851 }
852
ClearIOHandlers()853 void Debugger::ClearIOHandlers() {
854 // The bottom input reader should be the main debugger input reader. We do
855 // not want to close that one here.
856 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
857 while (m_io_handler_stack.GetSize() > 1) {
858 IOHandlerSP reader_sp(m_io_handler_stack.Top());
859 if (reader_sp)
860 PopIOHandler(reader_sp);
861 }
862 }
863
RunIOHandlers()864 void Debugger::RunIOHandlers() {
865 IOHandlerSP reader_sp = m_io_handler_stack.Top();
866 while (true) {
867 if (!reader_sp)
868 break;
869
870 reader_sp->Run();
871 {
872 std::lock_guard<std::recursive_mutex> guard(
873 m_io_handler_synchronous_mutex);
874
875 // Remove all input readers that are done from the top of the stack
876 while (true) {
877 IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
878 if (top_reader_sp && top_reader_sp->GetIsDone())
879 PopIOHandler(top_reader_sp);
880 else
881 break;
882 }
883 reader_sp = m_io_handler_stack.Top();
884 }
885 }
886 ClearIOHandlers();
887 }
888
RunIOHandlerSync(const IOHandlerSP & reader_sp)889 void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) {
890 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
891
892 PushIOHandler(reader_sp);
893 IOHandlerSP top_reader_sp = reader_sp;
894
895 while (top_reader_sp) {
896 if (!top_reader_sp)
897 break;
898
899 top_reader_sp->Run();
900
901 // Don't unwind past the starting point.
902 if (top_reader_sp.get() == reader_sp.get()) {
903 if (PopIOHandler(reader_sp))
904 break;
905 }
906
907 // If we pushed new IO handlers, pop them if they're done or restart the
908 // loop to run them if they're not.
909 while (true) {
910 top_reader_sp = m_io_handler_stack.Top();
911 if (top_reader_sp && top_reader_sp->GetIsDone()) {
912 PopIOHandler(top_reader_sp);
913 // Don't unwind past the starting point.
914 if (top_reader_sp.get() == reader_sp.get())
915 return;
916 } else {
917 break;
918 }
919 }
920 }
921 }
922
IsTopIOHandler(const lldb::IOHandlerSP & reader_sp)923 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
924 return m_io_handler_stack.IsTop(reader_sp);
925 }
926
CheckTopIOHandlerTypes(IOHandler::Type top_type,IOHandler::Type second_top_type)927 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
928 IOHandler::Type second_top_type) {
929 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
930 }
931
PrintAsync(const char * s,size_t len,bool is_stdout)932 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
933 lldb_private::StreamFile &stream =
934 is_stdout ? GetOutputStream() : GetErrorStream();
935 m_io_handler_stack.PrintAsync(&stream, s, len);
936 }
937
GetTopIOHandlerControlSequence(char ch)938 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
939 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
940 }
941
GetIOHandlerCommandPrefix()942 const char *Debugger::GetIOHandlerCommandPrefix() {
943 return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
944 }
945
GetIOHandlerHelpPrologue()946 const char *Debugger::GetIOHandlerHelpPrologue() {
947 return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
948 }
949
RemoveIOHandler(const IOHandlerSP & reader_sp)950 bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) {
951 return PopIOHandler(reader_sp);
952 }
953
RunIOHandlerAsync(const IOHandlerSP & reader_sp,bool cancel_top_handler)954 void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp,
955 bool cancel_top_handler) {
956 PushIOHandler(reader_sp, cancel_top_handler);
957 }
958
AdoptTopIOHandlerFilesIfInvalid(FileSP & in,StreamFileSP & out,StreamFileSP & err)959 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out,
960 StreamFileSP &err) {
961 // Before an IOHandler runs, it must have in/out/err streams. This function
962 // is called when one ore more of the streams are nullptr. We use the top
963 // input reader's in/out/err streams, or fall back to the debugger file
964 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
965
966 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
967 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
968 // If no STDIN has been set, then set it appropriately
969 if (!in || !in->IsValid()) {
970 if (top_reader_sp)
971 in = top_reader_sp->GetInputFileSP();
972 else
973 in = GetInputFileSP();
974 // If there is nothing, use stdin
975 if (!in)
976 in = std::make_shared<NativeFile>(stdin, false);
977 }
978 // If no STDOUT has been set, then set it appropriately
979 if (!out || !out->GetFile().IsValid()) {
980 if (top_reader_sp)
981 out = top_reader_sp->GetOutputStreamFileSP();
982 else
983 out = GetOutputStreamSP();
984 // If there is nothing, use stdout
985 if (!out)
986 out = std::make_shared<StreamFile>(stdout, false);
987 }
988 // If no STDERR has been set, then set it appropriately
989 if (!err || !err->GetFile().IsValid()) {
990 if (top_reader_sp)
991 err = top_reader_sp->GetErrorStreamFileSP();
992 else
993 err = GetErrorStreamSP();
994 // If there is nothing, use stderr
995 if (!err)
996 err = std::make_shared<StreamFile>(stderr, false);
997 }
998 }
999
PushIOHandler(const IOHandlerSP & reader_sp,bool cancel_top_handler)1000 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1001 bool cancel_top_handler) {
1002 if (!reader_sp)
1003 return;
1004
1005 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1006
1007 // Get the current top input reader...
1008 IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1009
1010 // Don't push the same IO handler twice...
1011 if (reader_sp == top_reader_sp)
1012 return;
1013
1014 // Push our new input reader
1015 m_io_handler_stack.Push(reader_sp);
1016 reader_sp->Activate();
1017
1018 // Interrupt the top input reader to it will exit its Run() function and let
1019 // this new input reader take over
1020 if (top_reader_sp) {
1021 top_reader_sp->Deactivate();
1022 if (cancel_top_handler)
1023 top_reader_sp->Cancel();
1024 }
1025 }
1026
PopIOHandler(const IOHandlerSP & pop_reader_sp)1027 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1028 if (!pop_reader_sp)
1029 return false;
1030
1031 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1032
1033 // The reader on the stop of the stack is done, so let the next read on the
1034 // stack refresh its prompt and if there is one...
1035 if (m_io_handler_stack.IsEmpty())
1036 return false;
1037
1038 IOHandlerSP reader_sp(m_io_handler_stack.Top());
1039
1040 if (pop_reader_sp != reader_sp)
1041 return false;
1042
1043 reader_sp->Deactivate();
1044 reader_sp->Cancel();
1045 m_io_handler_stack.Pop();
1046
1047 reader_sp = m_io_handler_stack.Top();
1048 if (reader_sp)
1049 reader_sp->Activate();
1050
1051 return true;
1052 }
1053
GetAsyncOutputStream()1054 StreamSP Debugger::GetAsyncOutputStream() {
1055 return std::make_shared<StreamAsynchronousIO>(*this, true);
1056 }
1057
GetAsyncErrorStream()1058 StreamSP Debugger::GetAsyncErrorStream() {
1059 return std::make_shared<StreamAsynchronousIO>(*this, false);
1060 }
1061
GetNumDebuggers()1062 size_t Debugger::GetNumDebuggers() {
1063 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1064 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1065 return g_debugger_list_ptr->size();
1066 }
1067 return 0;
1068 }
1069
GetDebuggerAtIndex(size_t index)1070 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1071 DebuggerSP debugger_sp;
1072
1073 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1074 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1075 if (index < g_debugger_list_ptr->size())
1076 debugger_sp = g_debugger_list_ptr->at(index);
1077 }
1078
1079 return debugger_sp;
1080 }
1081
FindDebuggerWithID(lldb::user_id_t id)1082 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1083 DebuggerSP debugger_sp;
1084
1085 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1086 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1087 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1088 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1089 if ((*pos)->GetID() == id) {
1090 debugger_sp = *pos;
1091 break;
1092 }
1093 }
1094 }
1095 return debugger_sp;
1096 }
1097
FormatDisassemblerAddress(const FormatEntity::Entry * format,const SymbolContext * sc,const SymbolContext * prev_sc,const ExecutionContext * exe_ctx,const Address * addr,Stream & s)1098 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1099 const SymbolContext *sc,
1100 const SymbolContext *prev_sc,
1101 const ExecutionContext *exe_ctx,
1102 const Address *addr, Stream &s) {
1103 FormatEntity::Entry format_entry;
1104
1105 if (format == nullptr) {
1106 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1107 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1108 if (format == nullptr) {
1109 FormatEntity::Parse("${addr}: ", format_entry);
1110 format = &format_entry;
1111 }
1112 }
1113 bool function_changed = false;
1114 bool initial_function = false;
1115 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1116 if (sc && (sc->function || sc->symbol)) {
1117 if (prev_sc->symbol && sc->symbol) {
1118 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1119 prev_sc->symbol->GetType())) {
1120 function_changed = true;
1121 }
1122 } else if (prev_sc->function && sc->function) {
1123 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1124 function_changed = true;
1125 }
1126 }
1127 }
1128 }
1129 // The first context on a list of instructions will have a prev_sc that has
1130 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1131 // would return false. But we do get a prev_sc pointer.
1132 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1133 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1134 initial_function = true;
1135 }
1136 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1137 function_changed, initial_function);
1138 }
1139
SetLoggingCallback(lldb::LogOutputCallback log_callback,void * baton)1140 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1141 void *baton) {
1142 // For simplicity's sake, I am not going to deal with how to close down any
1143 // open logging streams, I just redirect everything from here on out to the
1144 // callback.
1145 m_log_callback_stream_sp =
1146 std::make_shared<StreamCallback>(log_callback, baton);
1147 }
1148
EnableLog(llvm::StringRef channel,llvm::ArrayRef<const char * > categories,llvm::StringRef log_file,uint32_t log_options,llvm::raw_ostream & error_stream)1149 bool Debugger::EnableLog(llvm::StringRef channel,
1150 llvm::ArrayRef<const char *> categories,
1151 llvm::StringRef log_file, uint32_t log_options,
1152 llvm::raw_ostream &error_stream) {
1153 const bool should_close = true;
1154 const bool unbuffered = true;
1155
1156 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
1157 if (m_log_callback_stream_sp) {
1158 log_stream_sp = m_log_callback_stream_sp;
1159 // For now when using the callback mode you always get thread & timestamp.
1160 log_options |=
1161 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1162 } else if (log_file.empty()) {
1163 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1164 GetOutputFile().GetDescriptor(), !should_close, unbuffered);
1165 } else {
1166 auto pos = m_log_streams.find(log_file);
1167 if (pos != m_log_streams.end())
1168 log_stream_sp = pos->second.lock();
1169 if (!log_stream_sp) {
1170 File::OpenOptions flags =
1171 File::eOpenOptionWrite | File::eOpenOptionCanCreate;
1172 if (log_options & LLDB_LOG_OPTION_APPEND)
1173 flags |= File::eOpenOptionAppend;
1174 else
1175 flags |= File::eOpenOptionTruncate;
1176 llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1177 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1178 if (!file) {
1179 error_stream << "Unable to open log file '" << log_file
1180 << "': " << llvm::toString(file.takeError()) << "\n";
1181 return false;
1182 }
1183
1184 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1185 (*file)->GetDescriptor(), should_close, unbuffered);
1186 m_log_streams[log_file] = log_stream_sp;
1187 }
1188 }
1189 assert(log_stream_sp);
1190
1191 if (log_options == 0)
1192 log_options =
1193 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1194
1195 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1196 error_stream);
1197 }
1198
1199 ScriptInterpreter *
GetScriptInterpreter(bool can_create,llvm::Optional<lldb::ScriptLanguage> language)1200 Debugger::GetScriptInterpreter(bool can_create,
1201 llvm::Optional<lldb::ScriptLanguage> language) {
1202 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1203 lldb::ScriptLanguage script_language =
1204 language ? *language : GetScriptLanguage();
1205
1206 if (!m_script_interpreters[script_language]) {
1207 if (!can_create)
1208 return nullptr;
1209 m_script_interpreters[script_language] =
1210 PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1211 }
1212
1213 return m_script_interpreters[script_language].get();
1214 }
1215
GetSourceManager()1216 SourceManager &Debugger::GetSourceManager() {
1217 if (!m_source_manager_up)
1218 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1219 return *m_source_manager_up;
1220 }
1221
1222 // This function handles events that were broadcast by the process.
HandleBreakpointEvent(const EventSP & event_sp)1223 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1224 using namespace lldb;
1225 const uint32_t event_type =
1226 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1227 event_sp);
1228
1229 // if (event_type & eBreakpointEventTypeAdded
1230 // || event_type & eBreakpointEventTypeRemoved
1231 // || event_type & eBreakpointEventTypeEnabled
1232 // || event_type & eBreakpointEventTypeDisabled
1233 // || event_type & eBreakpointEventTypeCommandChanged
1234 // || event_type & eBreakpointEventTypeConditionChanged
1235 // || event_type & eBreakpointEventTypeIgnoreChanged
1236 // || event_type & eBreakpointEventTypeLocationsResolved)
1237 // {
1238 // // Don't do anything about these events, since the breakpoint
1239 // commands already echo these actions.
1240 // }
1241 //
1242 if (event_type & eBreakpointEventTypeLocationsAdded) {
1243 uint32_t num_new_locations =
1244 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1245 event_sp);
1246 if (num_new_locations > 0) {
1247 BreakpointSP breakpoint =
1248 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1249 StreamSP output_sp(GetAsyncOutputStream());
1250 if (output_sp) {
1251 output_sp->Printf("%d location%s added to breakpoint %d\n",
1252 num_new_locations, num_new_locations == 1 ? "" : "s",
1253 breakpoint->GetID());
1254 output_sp->Flush();
1255 }
1256 }
1257 }
1258 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1259 // {
1260 // // These locations just get disabled, not sure it is worth spamming
1261 // folks about this on the command line.
1262 // }
1263 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1264 // {
1265 // // This might be an interesting thing to note, but I'm going to
1266 // leave it quiet for now, it just looked noisy.
1267 // }
1268 }
1269
FlushProcessOutput(Process & process,bool flush_stdout,bool flush_stderr)1270 void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1271 bool flush_stderr) {
1272 const auto &flush = [&](Stream &stream,
1273 size_t (Process::*get)(char *, size_t, Status &)) {
1274 Status error;
1275 size_t len;
1276 char buffer[1024];
1277 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1278 stream.Write(buffer, len);
1279 stream.Flush();
1280 };
1281
1282 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1283 if (flush_stdout)
1284 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT);
1285 if (flush_stderr)
1286 flush(*GetAsyncErrorStream(), &Process::GetSTDERR);
1287 }
1288
1289 // This function handles events that were broadcast by the process.
HandleProcessEvent(const EventSP & event_sp)1290 void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1291 using namespace lldb;
1292 const uint32_t event_type = event_sp->GetType();
1293 ProcessSP process_sp =
1294 (event_type == Process::eBroadcastBitStructuredData)
1295 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1296 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1297
1298 StreamSP output_stream_sp = GetAsyncOutputStream();
1299 StreamSP error_stream_sp = GetAsyncErrorStream();
1300 const bool gui_enabled = IsForwardingEvents();
1301
1302 if (!gui_enabled) {
1303 bool pop_process_io_handler = false;
1304 assert(process_sp);
1305
1306 bool state_is_stopped = false;
1307 const bool got_state_changed =
1308 (event_type & Process::eBroadcastBitStateChanged) != 0;
1309 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1310 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1311 const bool got_structured_data =
1312 (event_type & Process::eBroadcastBitStructuredData) != 0;
1313
1314 if (got_state_changed) {
1315 StateType event_state =
1316 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1317 state_is_stopped = StateIsStoppedState(event_state, false);
1318 }
1319
1320 // Display running state changes first before any STDIO
1321 if (got_state_changed && !state_is_stopped) {
1322 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1323 pop_process_io_handler);
1324 }
1325
1326 // Now display STDOUT and STDERR
1327 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
1328 got_stderr || got_state_changed);
1329
1330 // Give structured data events an opportunity to display.
1331 if (got_structured_data) {
1332 StructuredDataPluginSP plugin_sp =
1333 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1334 if (plugin_sp) {
1335 auto structured_data_sp =
1336 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1337 if (output_stream_sp) {
1338 StreamString content_stream;
1339 Status error =
1340 plugin_sp->GetDescription(structured_data_sp, content_stream);
1341 if (error.Success()) {
1342 if (!content_stream.GetString().empty()) {
1343 // Add newline.
1344 content_stream.PutChar('\n');
1345 content_stream.Flush();
1346
1347 // Print it.
1348 output_stream_sp->PutCString(content_stream.GetString());
1349 }
1350 } else {
1351 error_stream_sp->Printf("Failed to print structured "
1352 "data with plugin %s: %s",
1353 plugin_sp->GetPluginName().AsCString(),
1354 error.AsCString());
1355 }
1356 }
1357 }
1358 }
1359
1360 // Now display any stopped state changes after any STDIO
1361 if (got_state_changed && state_is_stopped) {
1362 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1363 pop_process_io_handler);
1364 }
1365
1366 output_stream_sp->Flush();
1367 error_stream_sp->Flush();
1368
1369 if (pop_process_io_handler)
1370 process_sp->PopProcessIOHandler();
1371 }
1372 }
1373
HandleThreadEvent(const EventSP & event_sp)1374 void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1375 // At present the only thread event we handle is the Frame Changed event, and
1376 // all we do for that is just reprint the thread status for that thread.
1377 using namespace lldb;
1378 const uint32_t event_type = event_sp->GetType();
1379 const bool stop_format = true;
1380 if (event_type == Thread::eBroadcastBitStackChanged ||
1381 event_type == Thread::eBroadcastBitThreadSelected) {
1382 ThreadSP thread_sp(
1383 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1384 if (thread_sp) {
1385 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1386 }
1387 }
1388 }
1389
IsForwardingEvents()1390 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1391
EnableForwardEvents(const ListenerSP & listener_sp)1392 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1393 m_forward_listener_sp = listener_sp;
1394 }
1395
CancelForwardEvents(const ListenerSP & listener_sp)1396 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1397 m_forward_listener_sp.reset();
1398 }
1399
DefaultEventHandler()1400 void Debugger::DefaultEventHandler() {
1401 ListenerSP listener_sp(GetListener());
1402 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1403 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1404 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1405 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1406 Target::eBroadcastBitBreakpointChanged);
1407
1408 BroadcastEventSpec process_event_spec(
1409 broadcaster_class_process,
1410 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1411 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1412
1413 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1414 Thread::eBroadcastBitStackChanged |
1415 Thread::eBroadcastBitThreadSelected);
1416
1417 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1418 target_event_spec);
1419 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1420 process_event_spec);
1421 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1422 thread_event_spec);
1423 listener_sp->StartListeningForEvents(
1424 m_command_interpreter_up.get(),
1425 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1426 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1427 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1428
1429 // Let the thread that spawned us know that we have started up and that we
1430 // are now listening to all required events so no events get missed
1431 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1432
1433 bool done = false;
1434 while (!done) {
1435 EventSP event_sp;
1436 if (listener_sp->GetEvent(event_sp, llvm::None)) {
1437 if (event_sp) {
1438 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1439 if (broadcaster) {
1440 uint32_t event_type = event_sp->GetType();
1441 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1442 if (broadcaster_class == broadcaster_class_process) {
1443 HandleProcessEvent(event_sp);
1444 } else if (broadcaster_class == broadcaster_class_target) {
1445 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1446 event_sp.get())) {
1447 HandleBreakpointEvent(event_sp);
1448 }
1449 } else if (broadcaster_class == broadcaster_class_thread) {
1450 HandleThreadEvent(event_sp);
1451 } else if (broadcaster == m_command_interpreter_up.get()) {
1452 if (event_type &
1453 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1454 done = true;
1455 } else if (event_type &
1456 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1457 const char *data = static_cast<const char *>(
1458 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1459 if (data && data[0]) {
1460 StreamSP error_sp(GetAsyncErrorStream());
1461 if (error_sp) {
1462 error_sp->PutCString(data);
1463 error_sp->Flush();
1464 }
1465 }
1466 } else if (event_type & CommandInterpreter::
1467 eBroadcastBitAsynchronousOutputData) {
1468 const char *data = static_cast<const char *>(
1469 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1470 if (data && data[0]) {
1471 StreamSP output_sp(GetAsyncOutputStream());
1472 if (output_sp) {
1473 output_sp->PutCString(data);
1474 output_sp->Flush();
1475 }
1476 }
1477 }
1478 }
1479 }
1480
1481 if (m_forward_listener_sp)
1482 m_forward_listener_sp->AddEvent(event_sp);
1483 }
1484 }
1485 }
1486 }
1487
EventHandlerThread(lldb::thread_arg_t arg)1488 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1489 ((Debugger *)arg)->DefaultEventHandler();
1490 return {};
1491 }
1492
StartEventHandlerThread()1493 bool Debugger::StartEventHandlerThread() {
1494 if (!m_event_handler_thread.IsJoinable()) {
1495 // We must synchronize with the DefaultEventHandler() thread to ensure it
1496 // is up and running and listening to events before we return from this
1497 // function. We do this by listening to events for the
1498 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1499 ConstString full_name("lldb.debugger.event-handler");
1500 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
1501 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1502 eBroadcastBitEventThreadIsListening);
1503
1504 llvm::StringRef thread_name =
1505 full_name.GetLength() < llvm::get_max_thread_name_length()
1506 ? full_name.GetStringRef()
1507 : "dbg.evt-handler";
1508
1509 // Use larger 8MB stack for this thread
1510 llvm::Expected<HostThread> event_handler_thread =
1511 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1512 g_debugger_event_thread_stack_bytes);
1513
1514 if (event_handler_thread) {
1515 m_event_handler_thread = *event_handler_thread;
1516 } else {
1517 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1518 "failed to launch host thread: {}",
1519 llvm::toString(event_handler_thread.takeError()));
1520 }
1521
1522 // Make sure DefaultEventHandler() is running and listening to events
1523 // before we return from this function. We are only listening for events of
1524 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1525 // event, we just need to wait an infinite amount of time for it (nullptr
1526 // timeout as the first parameter)
1527 lldb::EventSP event_sp;
1528 listener_sp->GetEvent(event_sp, llvm::None);
1529 }
1530 return m_event_handler_thread.IsJoinable();
1531 }
1532
StopEventHandlerThread()1533 void Debugger::StopEventHandlerThread() {
1534 if (m_event_handler_thread.IsJoinable()) {
1535 GetCommandInterpreter().BroadcastEvent(
1536 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1537 m_event_handler_thread.Join(nullptr);
1538 }
1539 }
1540
IOHandlerThread(lldb::thread_arg_t arg)1541 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1542 Debugger *debugger = (Debugger *)arg;
1543 debugger->RunIOHandlers();
1544 debugger->StopEventHandlerThread();
1545 return {};
1546 }
1547
HasIOHandlerThread()1548 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1549
StartIOHandlerThread()1550 bool Debugger::StartIOHandlerThread() {
1551 if (!m_io_handler_thread.IsJoinable()) {
1552 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1553 "lldb.debugger.io-handler", IOHandlerThread, this,
1554 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1555 if (io_handler_thread) {
1556 m_io_handler_thread = *io_handler_thread;
1557 } else {
1558 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1559 "failed to launch host thread: {}",
1560 llvm::toString(io_handler_thread.takeError()));
1561 }
1562 }
1563 return m_io_handler_thread.IsJoinable();
1564 }
1565
StopIOHandlerThread()1566 void Debugger::StopIOHandlerThread() {
1567 if (m_io_handler_thread.IsJoinable()) {
1568 GetInputFile().Close();
1569 m_io_handler_thread.Join(nullptr);
1570 }
1571 }
1572
JoinIOHandlerThread()1573 void Debugger::JoinIOHandlerThread() {
1574 if (HasIOHandlerThread()) {
1575 thread_result_t result;
1576 m_io_handler_thread.Join(&result);
1577 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1578 }
1579 }
1580
GetSelectedOrDummyTarget(bool prefer_dummy)1581 Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1582 if (!prefer_dummy) {
1583 if (TargetSP target = m_target_list.GetSelectedTarget())
1584 return *target;
1585 }
1586 return GetDummyTarget();
1587 }
1588
RunREPL(LanguageType language,const char * repl_options)1589 Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1590 Status err;
1591 FileSpec repl_executable;
1592
1593 if (language == eLanguageTypeUnknown) {
1594 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
1595
1596 if (auto single_lang = repl_languages.GetSingularLanguage()) {
1597 language = *single_lang;
1598 } else if (repl_languages.Empty()) {
1599 err.SetErrorStringWithFormat(
1600 "LLDB isn't configured with REPL support for any languages.");
1601 return err;
1602 } else {
1603 err.SetErrorStringWithFormat(
1604 "Multiple possible REPL languages. Please specify a language.");
1605 return err;
1606 }
1607 }
1608
1609 Target *const target =
1610 nullptr; // passing in an empty target means the REPL must create one
1611
1612 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1613
1614 if (!err.Success()) {
1615 return err;
1616 }
1617
1618 if (!repl_sp) {
1619 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1620 Language::GetNameForLanguageType(language));
1621 return err;
1622 }
1623
1624 repl_sp->SetCompilerOptions(repl_options);
1625 repl_sp->RunLoop();
1626
1627 return err;
1628 }
1629