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