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