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 #endif 54 55 #include "llvm/ADT/None.h" // for None 56 #include "llvm/ADT/STLExtras.h" // for make_unique 57 #include "llvm/ADT/StringRef.h" 58 #include "llvm/ADT/iterator.h" // for iterator_facade_... 59 #include "llvm/Support/DynamicLibrary.h" 60 #include "llvm/Support/FileSystem.h" 61 #include "llvm/Support/Threading.h" 62 #include "llvm/Support/raw_ostream.h" // for raw_fd_ostream 63 64 #include <list> // for list 65 #include <memory> // for make_shared 66 #include <mutex> 67 #include <set> // for set 68 #include <stdio.h> // for size_t, NULL 69 #include <stdlib.h> // for getenv 70 #include <string.h> // for strcmp 71 #include <string> // for string 72 #include <system_error> // for error_code 73 74 namespace lldb_private { 75 class Address; 76 } 77 78 using namespace lldb; 79 using namespace lldb_private; 80 81 static lldb::user_id_t g_unique_id = 1; 82 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024; 83 84 #pragma mark Static Functions 85 86 typedef std::vector<DebuggerSP> DebuggerList; 87 static std::recursive_mutex *g_debugger_list_mutex_ptr = 88 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 89 static DebuggerList *g_debugger_list_ptr = 90 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 91 92 OptionEnumValueElement g_show_disassembly_enum_values[] = { 93 {Debugger::eStopDisassemblyTypeNever, "never", 94 "Never show disassembly when displaying a stop context."}, 95 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo", 96 "Show disassembly when there is no debug information."}, 97 {Debugger::eStopDisassemblyTypeNoSource, "no-source", 98 "Show disassembly when there is no source information, or the source file " 99 "is missing when displaying a stop context."}, 100 {Debugger::eStopDisassemblyTypeAlways, "always", 101 "Always show disassembly when displaying a stop context."}, 102 {0, nullptr, nullptr}}; 103 104 OptionEnumValueElement g_language_enumerators[] = { 105 {eScriptLanguageNone, "none", "Disable scripting languages."}, 106 {eScriptLanguagePython, "python", 107 "Select python as the default scripting language."}, 108 {eScriptLanguageDefault, "default", 109 "Select the lldb default as the default scripting language."}, 110 {0, nullptr, nullptr}}; 111 112 #define MODULE_WITH_FUNC \ 113 "{ " \ 114 "${module.file.basename}{`${function.name-with-args}" \ 115 "{${frame.no-debug}${function.pc-offset}}}}" 116 117 #define MODULE_WITH_FUNC_NO_ARGS \ 118 "{ " \ 119 "${module.file.basename}{`${function.name-without-args}" \ 120 "{${frame.no-debug}${function.pc-offset}}}}" 121 122 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}" 123 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}" 124 125 #define DEFAULT_THREAD_FORMAT \ 126 "thread #${thread.index}: tid = ${thread.id%tid}" \ 127 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \ 128 "{, name = '${thread.name}'}" \ 129 "{, queue = '${thread.queue}'}" \ 130 "{, activity = '${thread.info.activity.name}'}" \ 131 "{, ${thread.info.trace_messages} messages}" \ 132 "{, stop reason = ${thread.stop-reason}}" \ 133 "{\\nReturn value: ${thread.return-value}}" \ 134 "{\\nCompleted expression: ${thread.completed-expression}}" \ 135 "\\n" 136 137 #define DEFAULT_THREAD_STOP_FORMAT \ 138 "thread #${thread.index}{, name = '${thread.name}'}" \ 139 "{, queue = '${thread.queue}'}" \ 140 "{, activity = '${thread.info.activity.name}'}" \ 141 "{, ${thread.info.trace_messages} messages}" \ 142 "{, stop reason = ${thread.stop-reason}}" \ 143 "{\\nReturn value: ${thread.return-value}}" \ 144 "{\\nCompleted expression: ${thread.completed-expression}}" \ 145 "\\n" 146 147 #define DEFAULT_FRAME_FORMAT \ 148 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \ 149 IS_OPTIMIZED "\\n" 150 151 #define DEFAULT_FRAME_FORMAT_NO_ARGS \ 152 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \ 153 IS_OPTIMIZED "\\n" 154 155 // Three parts to this disassembly format specification: 156 // 1. If this is a new function/symbol (no previous symbol/function), print 157 // dylib`funcname:\n 158 // 2. If this is a symbol context change (different from previous 159 // symbol/function), print 160 // dylib`funcname:\n 161 // 3. print 162 // address <+offset>: 163 #define DEFAULT_DISASSEMBLY_FORMAT \ 164 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \ 165 "without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${" \ 166 "function.name-without-args}}:\n}{${current-pc-arrow} " \ 167 "}${addr-file-or-load}{ " \ 168 "<${function.concrete-only-addr-offset-no-padding}>}: " 169 170 // gdb's disassembly format can be emulated with ${current-pc-arrow}${addr- 171 // file-or-load}{ <${function.name-without-args}${function.concrete-only-addr- 172 // offset-no-padding}>}: 173 174 // lldb's original format for disassembly would look like this format string - 175 // {${function.initial-function}{${module.file.basename}`}{${function.name- 176 // without- 177 // args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name- 178 // without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}: 179 180 #define DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX "${ansi.underline}" 181 #define DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX "${ansi.normal}" 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::eTypeFormatEntity, true, 0, 243 DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX, 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::eTypeFormatEntity, true, 0, 248 DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX, 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 const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiPrefix() const { 489 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix; 490 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 491 } 492 493 const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiSuffix() const { 494 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix; 495 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(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 } 808 809 Debugger::~Debugger() { Clear(); } 810 811 void Debugger::Clear() { 812 //---------------------------------------------------------------------- 813 // Make sure we call this function only once. With the C++ global destructor 814 // chain having a list of debuggers and with code that can be running on 815 // other threads, we need to ensure this doesn't happen multiple times. 816 // 817 // The following functions call Debugger::Clear(): 818 // Debugger::~Debugger(); 819 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); 820 // static void Debugger::Terminate(); 821 //---------------------------------------------------------------------- 822 llvm::call_once(m_clear_once, [this]() { 823 ClearIOHandlers(); 824 StopIOHandlerThread(); 825 StopEventHandlerThread(); 826 m_listener_sp->Clear(); 827 int num_targets = m_target_list.GetNumTargets(); 828 for (int i = 0; i < num_targets; i++) { 829 TargetSP target_sp(m_target_list.GetTargetAtIndex(i)); 830 if (target_sp) { 831 ProcessSP process_sp(target_sp->GetProcessSP()); 832 if (process_sp) 833 process_sp->Finalize(); 834 target_sp->Destroy(); 835 } 836 } 837 m_broadcaster_manager_sp->Clear(); 838 839 // Close the input file _before_ we close the input read communications 840 // class as it does NOT own the input file, our m_input_file does. 841 m_terminal_state.Clear(); 842 if (m_input_file_sp) 843 m_input_file_sp->GetFile().Close(); 844 845 m_command_interpreter_ap->Clear(); 846 }); 847 } 848 849 bool Debugger::GetCloseInputOnEOF() const { 850 // return m_input_comm.GetCloseOnEOF(); 851 return false; 852 } 853 854 void Debugger::SetCloseInputOnEOF(bool b) { 855 // m_input_comm.SetCloseOnEOF(b); 856 } 857 858 bool Debugger::GetAsyncExecution() { 859 return !m_command_interpreter_ap->GetSynchronous(); 860 } 861 862 void Debugger::SetAsyncExecution(bool async_execution) { 863 m_command_interpreter_ap->SetSynchronous(!async_execution); 864 } 865 866 void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) { 867 if (m_input_file_sp) 868 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership); 869 else 870 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership); 871 872 File &in_file = m_input_file_sp->GetFile(); 873 if (!in_file.IsValid()) 874 in_file.SetStream(stdin, true); 875 876 // Save away the terminal state if that is relevant, so that we can restore 877 // it in RestoreInputState. 878 SaveInputTerminalState(); 879 } 880 881 void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) { 882 if (m_output_file_sp) 883 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership); 884 else 885 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership); 886 887 File &out_file = m_output_file_sp->GetFile(); 888 if (!out_file.IsValid()) 889 out_file.SetStream(stdout, false); 890 891 // do not create the ScriptInterpreter just for setting the output file 892 // handle as the constructor will know how to do the right thing on its own 893 const bool can_create = false; 894 ScriptInterpreter *script_interpreter = 895 GetCommandInterpreter().GetScriptInterpreter(can_create); 896 if (script_interpreter) 897 script_interpreter->ResetOutputFileHandle(fh); 898 } 899 900 void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) { 901 if (m_error_file_sp) 902 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership); 903 else 904 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership); 905 906 File &err_file = m_error_file_sp->GetFile(); 907 if (!err_file.IsValid()) 908 err_file.SetStream(stderr, false); 909 } 910 911 void Debugger::SaveInputTerminalState() { 912 if (m_input_file_sp) { 913 File &in_file = m_input_file_sp->GetFile(); 914 if (in_file.GetDescriptor() != File::kInvalidDescriptor) 915 m_terminal_state.Save(in_file.GetDescriptor(), true); 916 } 917 } 918 919 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); } 920 921 ExecutionContext Debugger::GetSelectedExecutionContext() { 922 ExecutionContext exe_ctx; 923 TargetSP target_sp(GetSelectedTarget()); 924 exe_ctx.SetTargetSP(target_sp); 925 926 if (target_sp) { 927 ProcessSP process_sp(target_sp->GetProcessSP()); 928 exe_ctx.SetProcessSP(process_sp); 929 if (process_sp && !process_sp->IsRunning()) { 930 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread()); 931 if (thread_sp) { 932 exe_ctx.SetThreadSP(thread_sp); 933 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame()); 934 if (exe_ctx.GetFramePtr() == nullptr) 935 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0)); 936 } 937 } 938 } 939 return exe_ctx; 940 } 941 942 void Debugger::DispatchInputInterrupt() { 943 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 944 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 945 if (reader_sp) 946 reader_sp->Interrupt(); 947 } 948 949 void Debugger::DispatchInputEndOfFile() { 950 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 951 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 952 if (reader_sp) 953 reader_sp->GotEOF(); 954 } 955 956 void Debugger::ClearIOHandlers() { 957 // The bottom input reader should be the main debugger input reader. We do 958 // not want to close that one here. 959 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 960 while (m_input_reader_stack.GetSize() > 1) { 961 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 962 if (reader_sp) 963 PopIOHandler(reader_sp); 964 } 965 } 966 967 void Debugger::ExecuteIOHandlers() { 968 while (true) { 969 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 970 if (!reader_sp) 971 break; 972 973 reader_sp->Run(); 974 975 // Remove all input readers that are done from the top of the stack 976 while (true) { 977 IOHandlerSP top_reader_sp = m_input_reader_stack.Top(); 978 if (top_reader_sp && top_reader_sp->GetIsDone()) 979 PopIOHandler(top_reader_sp); 980 else 981 break; 982 } 983 } 984 ClearIOHandlers(); 985 } 986 987 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) { 988 return m_input_reader_stack.IsTop(reader_sp); 989 } 990 991 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type, 992 IOHandler::Type second_top_type) { 993 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type); 994 } 995 996 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) { 997 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile(); 998 m_input_reader_stack.PrintAsync(stream.get(), s, len); 999 } 1000 1001 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) { 1002 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch); 1003 } 1004 1005 const char *Debugger::GetIOHandlerCommandPrefix() { 1006 return m_input_reader_stack.GetTopIOHandlerCommandPrefix(); 1007 } 1008 1009 const char *Debugger::GetIOHandlerHelpPrologue() { 1010 return m_input_reader_stack.GetTopIOHandlerHelpPrologue(); 1011 } 1012 1013 void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) { 1014 PushIOHandler(reader_sp); 1015 1016 IOHandlerSP top_reader_sp = reader_sp; 1017 while (top_reader_sp) { 1018 top_reader_sp->Run(); 1019 1020 if (top_reader_sp.get() == reader_sp.get()) { 1021 if (PopIOHandler(reader_sp)) 1022 break; 1023 } 1024 1025 while (true) { 1026 top_reader_sp = m_input_reader_stack.Top(); 1027 if (top_reader_sp && top_reader_sp->GetIsDone()) 1028 PopIOHandler(top_reader_sp); 1029 else 1030 break; 1031 } 1032 } 1033 } 1034 1035 void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in, 1036 StreamFileSP &out, 1037 StreamFileSP &err) { 1038 // Before an IOHandler runs, it must have in/out/err streams. This function 1039 // is called when one ore more of the streams are nullptr. We use the top 1040 // input reader's in/out/err streams, or fall back to the debugger file 1041 // handles, or we fall back onto stdin/stdout/stderr as a last resort. 1042 1043 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 1044 IOHandlerSP top_reader_sp(m_input_reader_stack.Top()); 1045 // If no STDIN has been set, then set it appropriately 1046 if (!in) { 1047 if (top_reader_sp) 1048 in = top_reader_sp->GetInputStreamFile(); 1049 else 1050 in = GetInputFile(); 1051 1052 // If there is nothing, use stdin 1053 if (!in) 1054 in = std::make_shared<StreamFile>(stdin, false); 1055 } 1056 // If no STDOUT has been set, then set it appropriately 1057 if (!out) { 1058 if (top_reader_sp) 1059 out = top_reader_sp->GetOutputStreamFile(); 1060 else 1061 out = GetOutputFile(); 1062 1063 // If there is nothing, use stdout 1064 if (!out) 1065 out = std::make_shared<StreamFile>(stdout, false); 1066 } 1067 // If no STDERR has been set, then set it appropriately 1068 if (!err) { 1069 if (top_reader_sp) 1070 err = top_reader_sp->GetErrorStreamFile(); 1071 else 1072 err = GetErrorFile(); 1073 1074 // If there is nothing, use stderr 1075 if (!err) 1076 err = std::make_shared<StreamFile>(stdout, false); 1077 } 1078 } 1079 1080 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp) { 1081 if (!reader_sp) 1082 return; 1083 1084 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 1085 1086 // Get the current top input reader... 1087 IOHandlerSP top_reader_sp(m_input_reader_stack.Top()); 1088 1089 // Don't push the same IO handler twice... 1090 if (reader_sp == top_reader_sp) 1091 return; 1092 1093 // Push our new input reader 1094 m_input_reader_stack.Push(reader_sp); 1095 reader_sp->Activate(); 1096 1097 // Interrupt the top input reader to it will exit its Run() function and let 1098 // this new input reader take over 1099 if (top_reader_sp) { 1100 top_reader_sp->Deactivate(); 1101 top_reader_sp->Cancel(); 1102 } 1103 } 1104 1105 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) { 1106 if (!pop_reader_sp) 1107 return false; 1108 1109 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 1110 1111 // The reader on the stop of the stack is done, so let the next read on the 1112 // stack refresh its prompt and if there is one... 1113 if (m_input_reader_stack.IsEmpty()) 1114 return false; 1115 1116 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 1117 1118 if (pop_reader_sp != reader_sp) 1119 return false; 1120 1121 reader_sp->Deactivate(); 1122 reader_sp->Cancel(); 1123 m_input_reader_stack.Pop(); 1124 1125 reader_sp = m_input_reader_stack.Top(); 1126 if (reader_sp) 1127 reader_sp->Activate(); 1128 1129 return true; 1130 } 1131 1132 StreamSP Debugger::GetAsyncOutputStream() { 1133 return std::make_shared<StreamAsynchronousIO>(*this, true); 1134 } 1135 1136 StreamSP Debugger::GetAsyncErrorStream() { 1137 return std::make_shared<StreamAsynchronousIO>(*this, false); 1138 } 1139 1140 size_t Debugger::GetNumDebuggers() { 1141 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1142 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1143 return g_debugger_list_ptr->size(); 1144 } 1145 return 0; 1146 } 1147 1148 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) { 1149 DebuggerSP debugger_sp; 1150 1151 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1152 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1153 if (index < g_debugger_list_ptr->size()) 1154 debugger_sp = g_debugger_list_ptr->at(index); 1155 } 1156 1157 return debugger_sp; 1158 } 1159 1160 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) { 1161 DebuggerSP debugger_sp; 1162 1163 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1164 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1165 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1166 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 1167 if ((*pos)->GetID() == id) { 1168 debugger_sp = *pos; 1169 break; 1170 } 1171 } 1172 } 1173 return debugger_sp; 1174 } 1175 1176 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format, 1177 const SymbolContext *sc, 1178 const SymbolContext *prev_sc, 1179 const ExecutionContext *exe_ctx, 1180 const Address *addr, Stream &s) { 1181 FormatEntity::Entry format_entry; 1182 1183 if (format == nullptr) { 1184 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) 1185 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat(); 1186 if (format == nullptr) { 1187 FormatEntity::Parse("${addr}: ", format_entry); 1188 format = &format_entry; 1189 } 1190 } 1191 bool function_changed = false; 1192 bool initial_function = false; 1193 if (prev_sc && (prev_sc->function || prev_sc->symbol)) { 1194 if (sc && (sc->function || sc->symbol)) { 1195 if (prev_sc->symbol && sc->symbol) { 1196 if (!sc->symbol->Compare(prev_sc->symbol->GetName(), 1197 prev_sc->symbol->GetType())) { 1198 function_changed = true; 1199 } 1200 } else if (prev_sc->function && sc->function) { 1201 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) { 1202 function_changed = true; 1203 } 1204 } 1205 } 1206 } 1207 // The first context on a list of instructions will have a prev_sc that has 1208 // no Function or Symbol -- if SymbolContext had an IsValid() method, it 1209 // would return false. But we do get a prev_sc pointer. 1210 if ((sc && (sc->function || sc->symbol)) && prev_sc && 1211 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) { 1212 initial_function = true; 1213 } 1214 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr, 1215 function_changed, initial_function); 1216 } 1217 1218 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, 1219 void *baton) { 1220 // For simplicity's sake, I am not going to deal with how to close down any 1221 // open logging streams, I just redirect everything from here on out to the 1222 // callback. 1223 m_log_callback_stream_sp = 1224 std::make_shared<StreamCallback>(log_callback, baton); 1225 } 1226 1227 bool Debugger::EnableLog(llvm::StringRef channel, 1228 llvm::ArrayRef<const char *> categories, 1229 llvm::StringRef log_file, uint32_t log_options, 1230 llvm::raw_ostream &error_stream) { 1231 const bool should_close = true; 1232 const bool unbuffered = true; 1233 1234 std::shared_ptr<llvm::raw_ostream> log_stream_sp; 1235 if (m_log_callback_stream_sp) { 1236 log_stream_sp = m_log_callback_stream_sp; 1237 // For now when using the callback mode you always get thread & timestamp. 1238 log_options |= 1239 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1240 } else if (log_file.empty()) { 1241 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>( 1242 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered); 1243 } else { 1244 auto pos = m_log_streams.find(log_file); 1245 if (pos != m_log_streams.end()) 1246 log_stream_sp = pos->second.lock(); 1247 if (!log_stream_sp) { 1248 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text; 1249 if (log_options & LLDB_LOG_OPTION_APPEND) 1250 flags |= llvm::sys::fs::F_Append; 1251 int FD; 1252 if (std::error_code ec = llvm::sys::fs::openFileForWrite( 1253 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) { 1254 error_stream << "Unable to open log file: " << ec.message(); 1255 return false; 1256 } 1257 log_stream_sp = 1258 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered); 1259 m_log_streams[log_file] = log_stream_sp; 1260 } 1261 } 1262 assert(log_stream_sp); 1263 1264 if (log_options == 0) 1265 log_options = 1266 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE; 1267 1268 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, 1269 error_stream); 1270 } 1271 1272 SourceManager &Debugger::GetSourceManager() { 1273 if (!m_source_manager_ap) 1274 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this()); 1275 return *m_source_manager_ap; 1276 } 1277 1278 // This function handles events that were broadcast by the process. 1279 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) { 1280 using namespace lldb; 1281 const uint32_t event_type = 1282 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( 1283 event_sp); 1284 1285 // if (event_type & eBreakpointEventTypeAdded 1286 // || event_type & eBreakpointEventTypeRemoved 1287 // || event_type & eBreakpointEventTypeEnabled 1288 // || event_type & eBreakpointEventTypeDisabled 1289 // || event_type & eBreakpointEventTypeCommandChanged 1290 // || event_type & eBreakpointEventTypeConditionChanged 1291 // || event_type & eBreakpointEventTypeIgnoreChanged 1292 // || event_type & eBreakpointEventTypeLocationsResolved) 1293 // { 1294 // // Don't do anything about these events, since the breakpoint 1295 // commands already echo these actions. 1296 // } 1297 // 1298 if (event_type & eBreakpointEventTypeLocationsAdded) { 1299 uint32_t num_new_locations = 1300 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( 1301 event_sp); 1302 if (num_new_locations > 0) { 1303 BreakpointSP breakpoint = 1304 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); 1305 StreamSP output_sp(GetAsyncOutputStream()); 1306 if (output_sp) { 1307 output_sp->Printf("%d location%s added to breakpoint %d\n", 1308 num_new_locations, num_new_locations == 1 ? "" : "s", 1309 breakpoint->GetID()); 1310 output_sp->Flush(); 1311 } 1312 } 1313 } 1314 // else if (event_type & eBreakpointEventTypeLocationsRemoved) 1315 // { 1316 // // These locations just get disabled, not sure it is worth spamming 1317 // folks about this on the command line. 1318 // } 1319 // else if (event_type & eBreakpointEventTypeLocationsResolved) 1320 // { 1321 // // This might be an interesting thing to note, but I'm going to 1322 // leave it quiet for now, it just looked noisy. 1323 // } 1324 } 1325 1326 size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) { 1327 size_t total_bytes = 0; 1328 if (stream == nullptr) 1329 stream = GetOutputFile().get(); 1330 1331 if (stream) { 1332 // The process has stuff waiting for stdout; get it and write it out to the 1333 // appropriate place. 1334 if (process == nullptr) { 1335 TargetSP target_sp = GetTargetList().GetSelectedTarget(); 1336 if (target_sp) 1337 process = target_sp->GetProcessSP().get(); 1338 } 1339 if (process) { 1340 Status error; 1341 size_t len; 1342 char stdio_buffer[1024]; 1343 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer), 1344 error)) > 0) { 1345 stream->Write(stdio_buffer, len); 1346 total_bytes += len; 1347 } 1348 } 1349 stream->Flush(); 1350 } 1351 return total_bytes; 1352 } 1353 1354 size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) { 1355 size_t total_bytes = 0; 1356 if (stream == nullptr) 1357 stream = GetOutputFile().get(); 1358 1359 if (stream) { 1360 // The process has stuff waiting for stderr; get it and write it out to the 1361 // appropriate place. 1362 if (process == nullptr) { 1363 TargetSP target_sp = GetTargetList().GetSelectedTarget(); 1364 if (target_sp) 1365 process = target_sp->GetProcessSP().get(); 1366 } 1367 if (process) { 1368 Status error; 1369 size_t len; 1370 char stdio_buffer[1024]; 1371 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer), 1372 error)) > 0) { 1373 stream->Write(stdio_buffer, len); 1374 total_bytes += len; 1375 } 1376 } 1377 stream->Flush(); 1378 } 1379 return total_bytes; 1380 } 1381 1382 // This function handles events that were broadcast by the process. 1383 void Debugger::HandleProcessEvent(const EventSP &event_sp) { 1384 using namespace lldb; 1385 const uint32_t event_type = event_sp->GetType(); 1386 ProcessSP process_sp = 1387 (event_type == Process::eBroadcastBitStructuredData) 1388 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) 1389 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 1390 1391 StreamSP output_stream_sp = GetAsyncOutputStream(); 1392 StreamSP error_stream_sp = GetAsyncErrorStream(); 1393 const bool gui_enabled = IsForwardingEvents(); 1394 1395 if (!gui_enabled) { 1396 bool pop_process_io_handler = false; 1397 assert(process_sp); 1398 1399 bool state_is_stopped = false; 1400 const bool got_state_changed = 1401 (event_type & Process::eBroadcastBitStateChanged) != 0; 1402 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; 1403 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; 1404 const bool got_structured_data = 1405 (event_type & Process::eBroadcastBitStructuredData) != 0; 1406 1407 if (got_state_changed) { 1408 StateType event_state = 1409 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1410 state_is_stopped = StateIsStoppedState(event_state, false); 1411 } 1412 1413 // Display running state changes first before any STDIO 1414 if (got_state_changed && !state_is_stopped) { 1415 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1416 pop_process_io_handler); 1417 } 1418 1419 // Now display and STDOUT 1420 if (got_stdout || got_state_changed) { 1421 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get()); 1422 } 1423 1424 // Now display and STDERR 1425 if (got_stderr || got_state_changed) { 1426 GetProcessSTDERR(process_sp.get(), error_stream_sp.get()); 1427 } 1428 1429 // Give structured data events an opportunity to display. 1430 if (got_structured_data) { 1431 StructuredDataPluginSP plugin_sp = 1432 EventDataStructuredData::GetPluginFromEvent(event_sp.get()); 1433 if (plugin_sp) { 1434 auto structured_data_sp = 1435 EventDataStructuredData::GetObjectFromEvent(event_sp.get()); 1436 if (output_stream_sp) { 1437 StreamString content_stream; 1438 Status error = 1439 plugin_sp->GetDescription(structured_data_sp, content_stream); 1440 if (error.Success()) { 1441 if (!content_stream.GetString().empty()) { 1442 // Add newline. 1443 content_stream.PutChar('\n'); 1444 content_stream.Flush(); 1445 1446 // Print it. 1447 output_stream_sp->PutCString(content_stream.GetString()); 1448 } 1449 } else { 1450 error_stream_sp->Printf("Failed to print structured " 1451 "data with plugin %s: %s", 1452 plugin_sp->GetPluginName().AsCString(), 1453 error.AsCString()); 1454 } 1455 } 1456 } 1457 } 1458 1459 // Now display any stopped state changes after any STDIO 1460 if (got_state_changed && state_is_stopped) { 1461 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1462 pop_process_io_handler); 1463 } 1464 1465 output_stream_sp->Flush(); 1466 error_stream_sp->Flush(); 1467 1468 if (pop_process_io_handler) 1469 process_sp->PopProcessIOHandler(); 1470 } 1471 } 1472 1473 void Debugger::HandleThreadEvent(const EventSP &event_sp) { 1474 // At present the only thread event we handle is the Frame Changed event, and 1475 // all we do for that is just reprint the thread status for that thread. 1476 using namespace lldb; 1477 const uint32_t event_type = event_sp->GetType(); 1478 const bool stop_format = true; 1479 if (event_type == Thread::eBroadcastBitStackChanged || 1480 event_type == Thread::eBroadcastBitThreadSelected) { 1481 ThreadSP thread_sp( 1482 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get())); 1483 if (thread_sp) { 1484 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format); 1485 } 1486 } 1487 } 1488 1489 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; } 1490 1491 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) { 1492 m_forward_listener_sp = listener_sp; 1493 } 1494 1495 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { 1496 m_forward_listener_sp.reset(); 1497 } 1498 1499 void Debugger::DefaultEventHandler() { 1500 ListenerSP listener_sp(GetListener()); 1501 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); 1502 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); 1503 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); 1504 BroadcastEventSpec target_event_spec(broadcaster_class_target, 1505 Target::eBroadcastBitBreakpointChanged); 1506 1507 BroadcastEventSpec process_event_spec( 1508 broadcaster_class_process, 1509 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | 1510 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData); 1511 1512 BroadcastEventSpec thread_event_spec(broadcaster_class_thread, 1513 Thread::eBroadcastBitStackChanged | 1514 Thread::eBroadcastBitThreadSelected); 1515 1516 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1517 target_event_spec); 1518 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1519 process_event_spec); 1520 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1521 thread_event_spec); 1522 listener_sp->StartListeningForEvents( 1523 m_command_interpreter_ap.get(), 1524 CommandInterpreter::eBroadcastBitQuitCommandReceived | 1525 CommandInterpreter::eBroadcastBitAsynchronousOutputData | 1526 CommandInterpreter::eBroadcastBitAsynchronousErrorData); 1527 1528 // Let the thread that spawned us know that we have started up and that we 1529 // are now listening to all required events so no events get missed 1530 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening); 1531 1532 bool done = false; 1533 while (!done) { 1534 EventSP event_sp; 1535 if (listener_sp->GetEvent(event_sp, llvm::None)) { 1536 if (event_sp) { 1537 Broadcaster *broadcaster = event_sp->GetBroadcaster(); 1538 if (broadcaster) { 1539 uint32_t event_type = event_sp->GetType(); 1540 ConstString broadcaster_class(broadcaster->GetBroadcasterClass()); 1541 if (broadcaster_class == broadcaster_class_process) { 1542 HandleProcessEvent(event_sp); 1543 } else if (broadcaster_class == broadcaster_class_target) { 1544 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent( 1545 event_sp.get())) { 1546 HandleBreakpointEvent(event_sp); 1547 } 1548 } else if (broadcaster_class == broadcaster_class_thread) { 1549 HandleThreadEvent(event_sp); 1550 } else if (broadcaster == m_command_interpreter_ap.get()) { 1551 if (event_type & 1552 CommandInterpreter::eBroadcastBitQuitCommandReceived) { 1553 done = true; 1554 } else if (event_type & 1555 CommandInterpreter::eBroadcastBitAsynchronousErrorData) { 1556 const char *data = reinterpret_cast<const char *>( 1557 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1558 if (data && data[0]) { 1559 StreamSP error_sp(GetAsyncErrorStream()); 1560 if (error_sp) { 1561 error_sp->PutCString(data); 1562 error_sp->Flush(); 1563 } 1564 } 1565 } else if (event_type & CommandInterpreter:: 1566 eBroadcastBitAsynchronousOutputData) { 1567 const char *data = reinterpret_cast<const char *>( 1568 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1569 if (data && data[0]) { 1570 StreamSP output_sp(GetAsyncOutputStream()); 1571 if (output_sp) { 1572 output_sp->PutCString(data); 1573 output_sp->Flush(); 1574 } 1575 } 1576 } 1577 } 1578 } 1579 1580 if (m_forward_listener_sp) 1581 m_forward_listener_sp->AddEvent(event_sp); 1582 } 1583 } 1584 } 1585 } 1586 1587 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) { 1588 ((Debugger *)arg)->DefaultEventHandler(); 1589 return NULL; 1590 } 1591 1592 bool Debugger::StartEventHandlerThread() { 1593 if (!m_event_handler_thread.IsJoinable()) { 1594 // We must synchronize with the DefaultEventHandler() thread to ensure it 1595 // is up and running and listening to events before we return from this 1596 // function. We do this by listening to events for the 1597 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster 1598 ConstString full_name("lldb.debugger.event-handler"); 1599 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString())); 1600 listener_sp->StartListeningForEvents(&m_sync_broadcaster, 1601 eBroadcastBitEventThreadIsListening); 1602 1603 auto thread_name = 1604 full_name.GetLength() < llvm::get_max_thread_name_length() ? 1605 full_name.AsCString() : "dbg.evt-handler"; 1606 1607 // Use larger 8MB stack for this thread 1608 m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name, 1609 EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes); 1610 1611 // Make sure DefaultEventHandler() is running and listening to events 1612 // before we return from this function. We are only listening for events of 1613 // type eBroadcastBitEventThreadIsListening so we don't need to check the 1614 // event, we just need to wait an infinite amount of time for it (nullptr 1615 // timeout as the first parameter) 1616 lldb::EventSP event_sp; 1617 listener_sp->GetEvent(event_sp, llvm::None); 1618 } 1619 return m_event_handler_thread.IsJoinable(); 1620 } 1621 1622 void Debugger::StopEventHandlerThread() { 1623 if (m_event_handler_thread.IsJoinable()) { 1624 GetCommandInterpreter().BroadcastEvent( 1625 CommandInterpreter::eBroadcastBitQuitCommandReceived); 1626 m_event_handler_thread.Join(nullptr); 1627 } 1628 } 1629 1630 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) { 1631 Debugger *debugger = (Debugger *)arg; 1632 debugger->ExecuteIOHandlers(); 1633 debugger->StopEventHandlerThread(); 1634 return NULL; 1635 } 1636 1637 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); } 1638 1639 bool Debugger::StartIOHandlerThread() { 1640 if (!m_io_handler_thread.IsJoinable()) 1641 m_io_handler_thread = ThreadLauncher::LaunchThread( 1642 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr, 1643 8 * 1024 * 1024); // Use larger 8MB stack for this thread 1644 return m_io_handler_thread.IsJoinable(); 1645 } 1646 1647 void Debugger::StopIOHandlerThread() { 1648 if (m_io_handler_thread.IsJoinable()) { 1649 if (m_input_file_sp) 1650 m_input_file_sp->GetFile().Close(); 1651 m_io_handler_thread.Join(nullptr); 1652 } 1653 } 1654 1655 void Debugger::JoinIOHandlerThread() { 1656 if (HasIOHandlerThread()) { 1657 thread_result_t result; 1658 m_io_handler_thread.Join(&result); 1659 m_io_handler_thread = LLDB_INVALID_HOST_THREAD; 1660 } 1661 } 1662 1663 Target *Debugger::GetDummyTarget() { 1664 return m_target_list.GetDummyTarget(*this).get(); 1665 } 1666 1667 Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { 1668 Target *target = nullptr; 1669 if (!prefer_dummy) { 1670 target = m_target_list.GetSelectedTarget().get(); 1671 if (target) 1672 return target; 1673 } 1674 1675 return GetDummyTarget(); 1676 } 1677 1678 Status Debugger::RunREPL(LanguageType language, const char *repl_options) { 1679 Status err; 1680 FileSpec repl_executable; 1681 1682 if (language == eLanguageTypeUnknown) { 1683 std::set<LanguageType> repl_languages; 1684 1685 Language::GetLanguagesSupportingREPLs(repl_languages); 1686 1687 if (repl_languages.size() == 1) { 1688 language = *repl_languages.begin(); 1689 } else if (repl_languages.empty()) { 1690 err.SetErrorStringWithFormat( 1691 "LLDB isn't configured with REPL support for any languages."); 1692 return err; 1693 } else { 1694 err.SetErrorStringWithFormat( 1695 "Multiple possible REPL languages. Please specify a language."); 1696 return err; 1697 } 1698 } 1699 1700 Target *const target = 1701 nullptr; // passing in an empty target means the REPL must create one 1702 1703 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options)); 1704 1705 if (!err.Success()) { 1706 return err; 1707 } 1708 1709 if (!repl_sp) { 1710 err.SetErrorStringWithFormat("couldn't find a REPL for %s", 1711 Language::GetNameForLanguageType(language)); 1712 return err; 1713 } 1714 1715 repl_sp->SetCompilerOptions(repl_options); 1716 repl_sp->RunLoop(); 1717 1718 return err; 1719 } 1720