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