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