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