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