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