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