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