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