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 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 {0, nullptr, nullptr}}; 105 106 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 {0, nullptr, nullptr}}; 113 114 #define MODULE_WITH_FUNC \ 115 "{ " \ 116 "${module.file.basename}{`${function.name-with-args}" \ 117 "{${frame.no-debug}${function.pc-offset}}}}" 118 119 #define MODULE_WITH_FUNC_NO_ARGS \ 120 "{ " \ 121 "${module.file.basename}{`${function.name-without-args}" \ 122 "{${frame.no-debug}${function.pc-offset}}}}" 123 124 #define FILE_AND_LINE \ 125 "{ at ${line.file.basename}:${line.number}{:${line.column}}}" 126 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}" 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 "\\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 "\\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 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 {0, nullptr, nullptr}}; 197 198 static PropertyDefinition g_properties[] = { 199 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, 200 "If true all confirmation prompts will receive their default reply."}, 201 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0, 202 DEFAULT_DISASSEMBLY_FORMAT, nullptr, 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, nullptr, 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, nullptr, 212 "Notify the user explicitly if an expression returns void (default: " 213 "false)."}, 214 {"prompt", OptionValue::eTypeString, true, 215 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", 216 nullptr, "The debugger command line prompt displayed for the user."}, 217 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython, 218 nullptr, 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 nullptr, 222 "The number of disassembly lines to show when displaying a " 223 "stopped context."}, 224 {"stop-disassembly-display", OptionValue::eTypeEnum, true, 225 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr, 226 g_show_disassembly_enum_values, 227 "Control when to display disassembly when displaying a stopped context."}, 228 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr, 229 nullptr, 230 "The number of sources lines to display that come after the " 231 "current source line when displaying a stopped context."}, 232 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr, 233 nullptr, 234 "The number of sources lines to display that come before the " 235 "current source line when displaying a stopped context."}, 236 {"highlight-source", OptionValue::eTypeBoolean, true, true, nullptr, 237 nullptr, "If true, LLDB will highlight the displayed source code."}, 238 {"stop-show-column", OptionValue::eTypeEnum, false, 239 eStopShowColumnAnsiOrCaret, nullptr, s_stop_show_column_values, 240 "If true, LLDB will use the column information from the debug info to " 241 "mark the current position when displaying a stopped context."}, 242 {"stop-show-column-ansi-prefix", OptionValue::eTypeString, true, 0, 243 "${ansi.underline}", nullptr, 244 "When displaying the column marker in a color-enabled (i.e. ANSI) " 245 "terminal, use the ANSI terminal code specified in this format at the " 246 "immediately before the column to be marked."}, 247 {"stop-show-column-ansi-suffix", OptionValue::eTypeString, true, 0, 248 "${ansi.normal}", nullptr, 249 "When displaying the column marker in a color-enabled (i.e. ANSI) " 250 "terminal, use the ANSI terminal code specified in this format " 251 "immediately after the column to be marked."}, 252 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, nullptr, 253 "The maximum number of columns to use for displaying text."}, 254 {"thread-format", OptionValue::eTypeFormatEntity, true, 0, 255 DEFAULT_THREAD_FORMAT, nullptr, 256 "The default thread format string to use " 257 "when displaying thread information."}, 258 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0, 259 DEFAULT_THREAD_STOP_FORMAT, nullptr, 260 "The default thread format " 261 "string to use when displaying thread " 262 "information as part of the stop display."}, 263 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr, 264 nullptr, "Whether to use an external editor or not."}, 265 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, 266 "Whether to use Ansi color codes or not."}, 267 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr, 268 nullptr, 269 "If true, LLDB will automatically display small structs in " 270 "one-liner format (default: true)."}, 271 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, 272 "If true, LLDB will auto indent/outdent code. Currently only supported in " 273 "the REPL (default: true)."}, 274 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, 275 "If true, LLDB will print the values of variables declared in an " 276 "expression. Currently only supported in the REPL (default: true)."}, 277 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, nullptr, 278 "The tab size to use when indenting code in multi-line input mode " 279 "(default: 4)."}, 280 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr, 281 nullptr, 282 "If true, LLDB will automatically escape non-printable and " 283 "escape characters when formatting strings."}, 284 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0, 285 DEFAULT_FRAME_FORMAT_NO_ARGS, nullptr, 286 "The default frame format string to use when displaying stack frame" 287 "information for threads from thread backtrace unique."}, 288 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}}; 289 290 enum { 291 ePropertyAutoConfirm = 0, 292 ePropertyDisassemblyFormat, 293 ePropertyFrameFormat, 294 ePropertyNotiftVoid, 295 ePropertyPrompt, 296 ePropertyScriptLanguage, 297 ePropertyStopDisassemblyCount, 298 ePropertyStopDisassemblyDisplay, 299 ePropertyStopLineCountAfter, 300 ePropertyStopLineCountBefore, 301 ePropertyHighlightSource, 302 ePropertyStopShowColumn, 303 ePropertyStopShowColumnAnsiPrefix, 304 ePropertyStopShowColumnAnsiSuffix, 305 ePropertyTerminalWidth, 306 ePropertyThreadFormat, 307 ePropertyThreadStopFormat, 308 ePropertyUseExternalEditor, 309 ePropertyUseColor, 310 ePropertyAutoOneLineSummaries, 311 ePropertyAutoIndent, 312 ePropertyPrintDecls, 313 ePropertyTabSize, 314 ePropertyEscapeNonPrintables, 315 ePropertyFrameFormatUnique, 316 }; 317 318 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr; 319 320 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, 321 VarSetOperationType op, 322 llvm::StringRef property_path, 323 llvm::StringRef value) { 324 bool is_load_script = (property_path == "target.load-script-from-symbol-file"); 325 bool is_escape_non_printables = (property_path == "escape-non-printables"); 326 TargetSP target_sp; 327 LoadScriptFromSymFile load_script_old_value; 328 if (is_load_script && exe_ctx->GetTargetSP()) { 329 target_sp = exe_ctx->GetTargetSP(); 330 load_script_old_value = 331 target_sp->TargetProperties::GetLoadScriptFromSymbolFile(); 332 } 333 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value)); 334 if (error.Success()) { 335 // FIXME it would be nice to have "on-change" callbacks for properties 336 if (property_path == g_properties[ePropertyPrompt].name) { 337 llvm::StringRef new_prompt = GetPrompt(); 338 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes( 339 new_prompt, GetUseColor()); 340 if (str.length()) 341 new_prompt = str; 342 GetCommandInterpreter().UpdatePrompt(new_prompt); 343 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt); 344 auto prompt_change_event_sp = std::make_shared<Event>( 345 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release()); 346 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp); 347 } else if (property_path == g_properties[ePropertyUseColor].name) { 348 // use-color changed. Ping the prompt so it can reset the ansi terminal 349 // codes. 350 SetPrompt(GetPrompt()); 351 } else if (is_load_script && target_sp && 352 load_script_old_value == eLoadScriptFromSymFileWarn) { 353 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == 354 eLoadScriptFromSymFileTrue) { 355 std::list<Status> errors; 356 StreamString feedback_stream; 357 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) { 358 StreamFileSP stream_sp(GetErrorFile()); 359 if (stream_sp) { 360 for (auto error : errors) { 361 stream_sp->Printf("%s\n", error.AsCString()); 362 } 363 if (feedback_stream.GetSize()) 364 stream_sp->PutCString(feedback_stream.GetString()); 365 } 366 } 367 } 368 } else if (is_escape_non_printables) { 369 DataVisualization::ForceUpdate(); 370 } 371 } 372 return error; 373 } 374 375 bool Debugger::GetAutoConfirm() const { 376 const uint32_t idx = ePropertyAutoConfirm; 377 return m_collection_sp->GetPropertyAtIndexAsBoolean( 378 nullptr, idx, g_properties[idx].default_uint_value != 0); 379 } 380 381 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const { 382 const uint32_t idx = ePropertyDisassemblyFormat; 383 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 384 } 385 386 const FormatEntity::Entry *Debugger::GetFrameFormat() const { 387 const uint32_t idx = ePropertyFrameFormat; 388 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 389 } 390 391 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const { 392 const uint32_t idx = ePropertyFrameFormatUnique; 393 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 394 } 395 396 bool Debugger::GetNotifyVoid() const { 397 const uint32_t idx = ePropertyNotiftVoid; 398 return m_collection_sp->GetPropertyAtIndexAsBoolean( 399 nullptr, idx, g_properties[idx].default_uint_value != 0); 400 } 401 402 llvm::StringRef Debugger::GetPrompt() const { 403 const uint32_t idx = ePropertyPrompt; 404 return m_collection_sp->GetPropertyAtIndexAsString( 405 nullptr, idx, g_properties[idx].default_cstr_value); 406 } 407 408 void Debugger::SetPrompt(llvm::StringRef p) { 409 const uint32_t idx = ePropertyPrompt; 410 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p); 411 llvm::StringRef new_prompt = GetPrompt(); 412 std::string str = 413 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor()); 414 if (str.length()) 415 new_prompt = str; 416 GetCommandInterpreter().UpdatePrompt(new_prompt); 417 } 418 419 const FormatEntity::Entry *Debugger::GetThreadFormat() const { 420 const uint32_t idx = ePropertyThreadFormat; 421 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 422 } 423 424 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const { 425 const uint32_t idx = ePropertyThreadStopFormat; 426 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 427 } 428 429 lldb::ScriptLanguage Debugger::GetScriptLanguage() const { 430 const uint32_t idx = ePropertyScriptLanguage; 431 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration( 432 nullptr, idx, g_properties[idx].default_uint_value); 433 } 434 435 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) { 436 const uint32_t idx = ePropertyScriptLanguage; 437 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, 438 script_lang); 439 } 440 441 uint32_t Debugger::GetTerminalWidth() const { 442 const uint32_t idx = ePropertyTerminalWidth; 443 return m_collection_sp->GetPropertyAtIndexAsSInt64( 444 nullptr, idx, g_properties[idx].default_uint_value); 445 } 446 447 bool Debugger::SetTerminalWidth(uint32_t term_width) { 448 const uint32_t idx = ePropertyTerminalWidth; 449 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width); 450 } 451 452 bool Debugger::GetUseExternalEditor() const { 453 const uint32_t idx = ePropertyUseExternalEditor; 454 return m_collection_sp->GetPropertyAtIndexAsBoolean( 455 nullptr, idx, g_properties[idx].default_uint_value != 0); 456 } 457 458 bool Debugger::SetUseExternalEditor(bool b) { 459 const uint32_t idx = ePropertyUseExternalEditor; 460 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 461 } 462 463 bool Debugger::GetUseColor() const { 464 const uint32_t idx = ePropertyUseColor; 465 return m_collection_sp->GetPropertyAtIndexAsBoolean( 466 nullptr, idx, g_properties[idx].default_uint_value != 0); 467 } 468 469 bool Debugger::SetUseColor(bool b) { 470 const uint32_t idx = ePropertyUseColor; 471 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 472 SetPrompt(GetPrompt()); 473 return ret; 474 } 475 476 bool Debugger::GetHighlightSource() const { 477 const uint32_t idx = ePropertyHighlightSource; 478 return m_collection_sp->GetPropertyAtIndexAsBoolean( 479 nullptr, idx, g_properties[idx].default_uint_value); 480 } 481 482 StopShowColumn Debugger::GetStopShowColumn() const { 483 const uint32_t idx = ePropertyStopShowColumn; 484 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration( 485 nullptr, idx, g_properties[idx].default_uint_value); 486 } 487 488 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const { 489 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix; 490 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, ""); 491 } 492 493 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const { 494 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix; 495 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, ""); 496 } 497 498 uint32_t Debugger::GetStopSourceLineCount(bool before) const { 499 const uint32_t idx = 500 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter; 501 return m_collection_sp->GetPropertyAtIndexAsSInt64( 502 nullptr, idx, g_properties[idx].default_uint_value); 503 } 504 505 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const { 506 const uint32_t idx = ePropertyStopDisassemblyDisplay; 507 return (Debugger::StopDisassemblyType) 508 m_collection_sp->GetPropertyAtIndexAsEnumeration( 509 nullptr, idx, g_properties[idx].default_uint_value); 510 } 511 512 uint32_t Debugger::GetDisassemblyLineCount() const { 513 const uint32_t idx = ePropertyStopDisassemblyCount; 514 return m_collection_sp->GetPropertyAtIndexAsSInt64( 515 nullptr, idx, g_properties[idx].default_uint_value); 516 } 517 518 bool Debugger::GetAutoOneLineSummaries() const { 519 const uint32_t idx = ePropertyAutoOneLineSummaries; 520 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 521 } 522 523 bool Debugger::GetEscapeNonPrintables() const { 524 const uint32_t idx = ePropertyEscapeNonPrintables; 525 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 526 } 527 528 bool Debugger::GetAutoIndent() const { 529 const uint32_t idx = ePropertyAutoIndent; 530 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 531 } 532 533 bool Debugger::SetAutoIndent(bool b) { 534 const uint32_t idx = ePropertyAutoIndent; 535 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 536 } 537 538 bool Debugger::GetPrintDecls() const { 539 const uint32_t idx = ePropertyPrintDecls; 540 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 541 } 542 543 bool Debugger::SetPrintDecls(bool b) { 544 const uint32_t idx = ePropertyPrintDecls; 545 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 546 } 547 548 uint32_t Debugger::GetTabSize() const { 549 const uint32_t idx = ePropertyTabSize; 550 return m_collection_sp->GetPropertyAtIndexAsUInt64( 551 nullptr, idx, g_properties[idx].default_uint_value); 552 } 553 554 bool Debugger::SetTabSize(uint32_t tab_size) { 555 const uint32_t idx = ePropertyTabSize; 556 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size); 557 } 558 559 #pragma mark Debugger 560 561 // const DebuggerPropertiesSP & 562 // Debugger::GetSettings() const 563 //{ 564 // return m_properties_sp; 565 //} 566 // 567 568 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) { 569 assert(g_debugger_list_ptr == nullptr && 570 "Debugger::Initialize called more than once!"); 571 g_debugger_list_mutex_ptr = new std::recursive_mutex(); 572 g_debugger_list_ptr = new DebuggerList(); 573 g_load_plugin_callback = load_plugin_callback; 574 } 575 576 void Debugger::Terminate() { 577 assert(g_debugger_list_ptr && 578 "Debugger::Terminate called without a matching Debugger::Initialize!"); 579 580 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 581 // Clear our master list of debugger objects 582 { 583 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 584 for (const auto &debugger : *g_debugger_list_ptr) 585 debugger->Clear(); 586 g_debugger_list_ptr->clear(); 587 } 588 } 589 } 590 591 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); } 592 593 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); } 594 595 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) { 596 if (g_load_plugin_callback) { 597 llvm::sys::DynamicLibrary dynlib = 598 g_load_plugin_callback(shared_from_this(), spec, error); 599 if (dynlib.isValid()) { 600 m_loaded_plugins.push_back(dynlib); 601 return true; 602 } 603 } else { 604 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and 605 // if the public API layer isn't available (code is linking against all of 606 // the internal LLDB static libraries), then we can't load plugins 607 error.SetErrorString("Public API layer is not available"); 608 } 609 return false; 610 } 611 612 static FileSpec::EnumerateDirectoryResult 613 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, 614 const FileSpec &file_spec) { 615 Status error; 616 617 static ConstString g_dylibext(".dylib"); 618 static ConstString g_solibext(".so"); 619 620 if (!baton) 621 return FileSpec::eEnumerateDirectoryResultQuit; 622 623 Debugger *debugger = (Debugger *)baton; 624 625 namespace fs = llvm::sys::fs; 626 // If we have a regular file, a symbolic link or unknown file type, try and 627 // process the file. We must handle unknown as sometimes the directory 628 // enumeration might be enumerating a file system that doesn't have correct 629 // file type information. 630 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file || 631 ft == fs::file_type::type_unknown) { 632 FileSpec plugin_file_spec(file_spec); 633 plugin_file_spec.ResolvePath(); 634 635 if (plugin_file_spec.GetFileNameExtension() != g_dylibext && 636 plugin_file_spec.GetFileNameExtension() != g_solibext) { 637 return FileSpec::eEnumerateDirectoryResultNext; 638 } 639 640 Status plugin_load_error; 641 debugger->LoadPlugin(plugin_file_spec, plugin_load_error); 642 643 return FileSpec::eEnumerateDirectoryResultNext; 644 } else if (ft == fs::file_type::directory_file || 645 ft == fs::file_type::symlink_file || 646 ft == fs::file_type::type_unknown) { 647 // Try and recurse into anything that a directory or symbolic link. We must 648 // also do this for unknown as sometimes the directory enumeration might be 649 // enumerating a file system that doesn't have correct file type 650 // information. 651 return FileSpec::eEnumerateDirectoryResultEnter; 652 } 653 654 return FileSpec::eEnumerateDirectoryResultNext; 655 } 656 657 void Debugger::InstanceInitialize() { 658 const bool find_directories = true; 659 const bool find_files = true; 660 const bool find_other = true; 661 char dir_path[PATH_MAX]; 662 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) { 663 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) { 664 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files, 665 find_other, LoadPluginCallback, this); 666 } 667 } 668 669 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) { 670 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) { 671 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files, 672 find_other, 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