blob: 835f8034cdff02e1228260cf2ab175c31cc67bfd [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Greg Clayton4a33d312011-06-23 17:59:56 +000010#include "lldb/Core/Debugger.h"
11
Eugene Zelenkodf370552016-03-02 02:18:18 +000012// C Includes
13// C++ Includes
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include <map>
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000015#include <mutex>
Greg Clayton4a33d312011-06-23 17:59:56 +000016
Eugene Zelenkodf370552016-03-02 02:18:18 +000017// Other libraries and framework includes
Jason Molenda705b1802014-06-13 02:37:02 +000018#include "llvm/ADT/StringRef.h"
Eugene Zelenkodf370552016-03-02 02:18:18 +000019#include "llvm/Support/DynamicLibrary.h"
Enrico Granata4becb372011-06-29 22:27:15 +000020
Eugene Zelenkodf370552016-03-02 02:18:18 +000021// Project includes
Greg Clayton554f68d2015-02-04 22:00:53 +000022#include "lldb/Core/FormatEntity.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Jim Ingham0d5a2bd2015-09-03 01:40:51 +000024#include "lldb/Core/PluginInterface.h"
Greg Claytone8cd0c92012-10-19 18:02:49 +000025#include "lldb/Core/PluginManager.h"
Greg Clayton7349bd92011-05-09 20:18:18 +000026#include "lldb/Core/RegisterValue.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Core/State.h"
Jim Ingham5b52f0c2011-06-02 23:58:26 +000028#include "lldb/Core/StreamAsynchronousIO.h"
Jim Ingham228063c2012-02-21 02:23:08 +000029#include "lldb/Core/StreamCallback.h"
Greg Clayton44d93782014-01-27 23:43:24 +000030#include "lldb/Core/StreamFile.h"
Greg Clayton1b654882010-09-19 02:33:57 +000031#include "lldb/Core/StreamString.h"
Jason Molenda705b1802014-06-13 02:37:02 +000032#include "lldb/Core/StructuredData.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/Timer.h"
Enrico Granata4becb372011-06-29 22:27:15 +000034#include "lldb/Core/ValueObject.h"
Greg Clayton6d3dbf52012-01-13 08:39:16 +000035#include "lldb/Core/ValueObjectVariable.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000036#include "lldb/DataFormatters/DataVisualization.h"
37#include "lldb/DataFormatters/FormatManager.h"
Enrico Granata894f7352014-03-25 22:03:52 +000038#include "lldb/DataFormatters/TypeSummary.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000039#include "lldb/Expression/REPL.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000040#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000041#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000042#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000043#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000044#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000045#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000046#include "lldb/Interpreter/OptionValueSInt64.h"
47#include "lldb/Interpreter/OptionValueString.h"
Greg Clayton1f746072012-08-29 21:13:06 +000048#include "lldb/Symbol/CompileUnit.h"
49#include "lldb/Symbol/Function.h"
50#include "lldb/Symbol/Symbol.h"
Greg Clayton6d3dbf52012-01-13 08:39:16 +000051#include "lldb/Symbol/VariableList.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000052#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/Process.h"
Greg Clayton1b654882010-09-19 02:33:57 +000054#include "lldb/Target/RegisterContext.h"
Greg Clayton5fb8f792013-12-02 19:35:49 +000055#include "lldb/Target/SectionLoadList.h"
Greg Clayton1b654882010-09-19 02:33:57 +000056#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000057#include "lldb/Target/StructuredDataPlugin.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000058#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000059#include "lldb/Target/TargetList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060#include "lldb/Target/Thread.h"
Greg Clayton5a314712011-10-14 07:41:33 +000061#include "lldb/Utility/AnsiTerminal.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000062#include "lldb/lldb-private.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063
64using namespace lldb;
65using namespace lldb_private;
66
Caroline Ticeebc1bb22010-06-30 16:22:25 +000067static lldb::user_id_t g_unique_id = 1;
Zachary Turner7c2896a2014-10-24 22:06:29 +000068static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000069
Greg Clayton1b654882010-09-19 02:33:57 +000070#pragma mark Static Functions
71
Greg Clayton1b654882010-09-19 02:33:57 +000072typedef std::vector<DebuggerSP> DebuggerList;
Kate Stoneb9c1b512016-09-06 20:57:50 +000073static std::recursive_mutex *g_debugger_list_mutex_ptr =
74 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
75static DebuggerList *g_debugger_list_ptr =
76 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
Greg Claytone372b982011-11-21 21:44:34 +000077
Kate Stoneb9c1b512016-09-06 20:57:50 +000078OptionEnumValueElement g_show_disassembly_enum_values[] = {
79 {Debugger::eStopDisassemblyTypeNever, "never",
80 "Never show disassembly when displaying a stop context."},
81 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
82 "Show disassembly when there is no debug information."},
83 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
84 "Show disassembly when there is no source information, or the source file "
85 "is missing when displaying a stop context."},
86 {Debugger::eStopDisassemblyTypeAlways, "always",
87 "Always show disassembly when displaying a stop context."},
88 {0, nullptr, nullptr}};
Greg Claytone372b982011-11-21 21:44:34 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090OptionEnumValueElement g_language_enumerators[] = {
91 {eScriptLanguageNone, "none", "Disable scripting languages."},
92 {eScriptLanguagePython, "python",
93 "Select python as the default scripting language."},
94 {eScriptLanguageDefault, "default",
95 "Select the lldb default as the default scripting language."},
96 {0, nullptr, nullptr}};
Greg Claytone372b982011-11-21 21:44:34 +000097
Kate Stoneb9c1b512016-09-06 20:57:50 +000098#define MODULE_WITH_FUNC \
99 "{ " \
100 "${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000101#define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
Jason Molenda6ab659a2015-07-29 00:42:47 +0000102#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104#define DEFAULT_THREAD_FORMAT \
105 "thread #${thread.index}: tid = ${thread.id%tid}" \
106 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
107 "{, name = '${thread.name}'}" \
108 "{, queue = '${thread.queue}'}" \
109 "{, activity = '${thread.info.activity.name}'}" \
110 "{, ${thread.info.trace_messages} messages}" \
111 "{, stop reason = ${thread.stop-reason}}" \
112 "{\\nReturn value: ${thread.return-value}}" \
113 "{\\nCompleted expression: ${thread.completed-expression}}" \
114 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116#define DEFAULT_FRAME_FORMAT \
117 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \
118 IS_OPTIMIZED "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000119
Jason Molendac980fa92015-02-13 23:24:21 +0000120// Three parts to this disassembly format specification:
121// 1. If this is a new function/symbol (no previous symbol/function), print
122// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123// 2. If this is a symbol context change (different from previous
124// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000125// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126// 3. print
127// address <+offset>:
128#define DEFAULT_DISASSEMBLY_FORMAT \
129 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
130 "without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${" \
131 "function.name-without-args}}:\n}{${current-pc-arrow} " \
132 "}${addr-file-or-load}{ " \
133 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000134
135// gdb's disassembly format can be emulated with
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136// ${current-pc-arrow}${addr-file-or-load}{
137// <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000138
139// lldb's original format for disassembly would look like this format string -
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140// {${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}
141// }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143static PropertyDefinition g_properties[] = {
144 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
145 "If true all confirmation prompts will receive their default reply."},
146 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
147 DEFAULT_DISASSEMBLY_FORMAT, nullptr, "The default disassembly format "
148 "string to use when disassembling "
149 "instruction sequences."},
150 {"frame-format", OptionValue::eTypeFormatEntity, true, 0,
151 DEFAULT_FRAME_FORMAT, nullptr, "The default frame format string to use "
152 "when displaying stack frame information "
153 "for threads."},
154 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
155 "Notify the user explicitly if an expression returns void (default: "
156 "false)."},
157 {"prompt", OptionValue::eTypeString, true,
158 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ",
159 nullptr, "The debugger command line prompt displayed for the user."},
160 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
161 nullptr, g_language_enumerators,
162 "The script language to be used for evaluating user-written scripts."},
163 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr,
164 nullptr, "The number of disassembly lines to show when displaying a "
165 "stopped context."},
166 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
167 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
168 g_show_disassembly_enum_values,
169 "Control when to display disassembly when displaying a stopped context."},
170 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr,
171 nullptr, "The number of sources lines to display that come after the "
172 "current source line when displaying a stopped context."},
173 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr,
174 nullptr, "The number of sources lines to display that come before the "
175 "current source line when displaying a stopped context."},
176 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, nullptr,
177 "The maximum number of columns to use for displaying text."},
178 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
179 DEFAULT_THREAD_FORMAT, nullptr, "The default thread format string to use "
180 "when displaying thread information."},
181 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr,
182 nullptr, "Whether to use an external editor or not."},
183 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
184 "Whether to use Ansi color codes or not."},
185 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
186 nullptr, "If true, LLDB will automatically display small structs in "
187 "one-liner format (default: true)."},
188 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
189 "If true, LLDB will auto indent/outdent code. Currently only supported in "
190 "the REPL (default: true)."},
191 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
192 "If true, LLDB will print the values of variables declared in an "
193 "expression. Currently only supported in the REPL (default: true)."},
194 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, nullptr,
195 "The tab size to use when indenting code in multi-line input mode "
196 "(default: 4)."},
197 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
198 nullptr, "If true, LLDB will automatically escape non-printable and "
199 "escape characters when formatting strings."},
200 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202enum {
203 ePropertyAutoConfirm = 0,
204 ePropertyDisassemblyFormat,
205 ePropertyFrameFormat,
206 ePropertyNotiftVoid,
207 ePropertyPrompt,
208 ePropertyScriptLanguage,
209 ePropertyStopDisassemblyCount,
210 ePropertyStopDisassemblyDisplay,
211 ePropertyStopLineCountAfter,
212 ePropertyStopLineCountBefore,
213 ePropertyTerminalWidth,
214 ePropertyThreadFormat,
215 ePropertyUseExternalEditor,
216 ePropertyUseColor,
217 ePropertyAutoOneLineSummaries,
218 ePropertyAutoIndent,
219 ePropertyPrintDecls,
220 ePropertyTabSize,
221 ePropertyEscapeNonPrintables
Greg Clayton67cc0632012-08-22 17:17:09 +0000222};
223
Eugene Zelenkodf370552016-03-02 02:18:18 +0000224LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226Error Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
227 VarSetOperationType op,
228 const char *property_path, const char *value) {
229 bool is_load_script =
230 strcmp(property_path, "target.load-script-from-symbol-file") == 0;
231 bool is_escape_non_printables =
232 strcmp(property_path, "escape-non-printables") == 0;
233 TargetSP target_sp;
234 LoadScriptFromSymFile load_script_old_value;
235 if (is_load_script && exe_ctx->GetTargetSP()) {
236 target_sp = exe_ctx->GetTargetSP();
237 load_script_old_value =
238 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
239 }
240 Error error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
241 if (error.Success()) {
242 // FIXME it would be nice to have "on-change" callbacks for properties
243 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0) {
244 const char *new_prompt = GetPrompt();
245 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
246 new_prompt, GetUseColor());
247 if (str.length())
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000248 new_prompt = str.c_str();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 GetCommandInterpreter().UpdatePrompt(new_prompt);
250 EventSP prompt_change_event_sp(
251 new Event(CommandInterpreter::eBroadcastBitResetPrompt,
252 new EventDataBytes(new_prompt)));
253 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
254 } else if (strcmp(property_path, g_properties[ePropertyUseColor].name) ==
255 0) {
256 // use-color changed. Ping the prompt so it can reset the ansi terminal
257 // codes.
258 SetPrompt(GetPrompt());
259 } else if (is_load_script && target_sp &&
260 load_script_old_value == eLoadScriptFromSymFileWarn) {
261 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
262 eLoadScriptFromSymFileTrue) {
263 std::list<Error> errors;
264 StreamString feedback_stream;
265 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
266 StreamFileSP stream_sp(GetErrorFile());
267 if (stream_sp) {
268 for (auto error : errors) {
269 stream_sp->Printf("%s\n", error.AsCString());
270 }
271 if (feedback_stream.GetSize())
272 stream_sp->Printf("%s", feedback_stream.GetData());
273 }
274 }
275 }
276 } else if (is_escape_non_printables) {
277 DataVisualization::ForceUpdate();
278 }
279 }
280 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000281}
282
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283bool Debugger::GetAutoConfirm() const {
284 const uint32_t idx = ePropertyAutoConfirm;
285 return m_collection_sp->GetPropertyAtIndexAsBoolean(
286 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000287}
288
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
290 const uint32_t idx = ePropertyDisassemblyFormat;
291 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000292}
293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294const FormatEntity::Entry *Debugger::GetFrameFormat() const {
295 const uint32_t idx = ePropertyFrameFormat;
296 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000297}
298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299bool Debugger::GetNotifyVoid() const {
300 const uint32_t idx = ePropertyNotiftVoid;
301 return m_collection_sp->GetPropertyAtIndexAsBoolean(
302 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000303}
304
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305const char *Debugger::GetPrompt() const {
306 const uint32_t idx = ePropertyPrompt;
307 return m_collection_sp->GetPropertyAtIndexAsString(
308 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000309}
310
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311void Debugger::SetPrompt(const char *p) {
312 const uint32_t idx = ePropertyPrompt;
313 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
314 const char *new_prompt = GetPrompt();
315 std::string str =
316 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
317 if (str.length())
318 new_prompt = str.c_str();
319 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000320}
321
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322const FormatEntity::Entry *Debugger::GetThreadFormat() const {
323 const uint32_t idx = ePropertyThreadFormat;
324 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000325}
326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
328 const uint32_t idx = ePropertyScriptLanguage;
329 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
330 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000331}
332
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
334 const uint32_t idx = ePropertyScriptLanguage;
335 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
336 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000337}
338
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339uint32_t Debugger::GetTerminalWidth() const {
340 const uint32_t idx = ePropertyTerminalWidth;
341 return m_collection_sp->GetPropertyAtIndexAsSInt64(
342 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000343}
344
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345bool Debugger::SetTerminalWidth(uint32_t term_width) {
346 const uint32_t idx = ePropertyTerminalWidth;
347 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000348}
349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350bool Debugger::GetUseExternalEditor() const {
351 const uint32_t idx = ePropertyUseExternalEditor;
352 return m_collection_sp->GetPropertyAtIndexAsBoolean(
353 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000354}
Greg Claytone372b982011-11-21 21:44:34 +0000355
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356bool Debugger::SetUseExternalEditor(bool b) {
357 const uint32_t idx = ePropertyUseExternalEditor;
358 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000359}
Enrico Granata553fad52013-10-25 23:09:40 +0000360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361bool Debugger::GetUseColor() const {
362 const uint32_t idx = ePropertyUseColor;
363 return m_collection_sp->GetPropertyAtIndexAsBoolean(
364 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000365}
366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367bool Debugger::SetUseColor(bool b) {
368 const uint32_t idx = ePropertyUseColor;
369 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
370 SetPrompt(GetPrompt());
371 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000372}
373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374uint32_t Debugger::GetStopSourceLineCount(bool before) const {
375 const uint32_t idx =
376 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
377 return m_collection_sp->GetPropertyAtIndexAsSInt64(
378 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000379}
380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
382 const uint32_t idx = ePropertyStopDisassemblyDisplay;
383 return (Debugger::StopDisassemblyType)
384 m_collection_sp->GetPropertyAtIndexAsEnumeration(
385 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000386}
387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388uint32_t Debugger::GetDisassemblyLineCount() const {
389 const uint32_t idx = ePropertyStopDisassemblyCount;
390 return m_collection_sp->GetPropertyAtIndexAsSInt64(
391 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000392}
393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394bool Debugger::GetAutoOneLineSummaries() const {
395 const uint32_t idx = ePropertyAutoOneLineSummaries;
396 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000397}
398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399bool Debugger::GetEscapeNonPrintables() const {
400 const uint32_t idx = ePropertyEscapeNonPrintables;
401 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
402}
403
404bool Debugger::GetAutoIndent() const {
405 const uint32_t idx = ePropertyAutoIndent;
406 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
407}
408
409bool Debugger::SetAutoIndent(bool b) {
410 const uint32_t idx = ePropertyAutoIndent;
411 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
412}
413
414bool Debugger::GetPrintDecls() const {
415 const uint32_t idx = ePropertyPrintDecls;
416 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
417}
418
419bool Debugger::SetPrintDecls(bool b) {
420 const uint32_t idx = ePropertyPrintDecls;
421 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
422}
423
424uint32_t Debugger::GetTabSize() const {
425 const uint32_t idx = ePropertyTabSize;
426 return m_collection_sp->GetPropertyAtIndexAsUInt64(
427 nullptr, idx, g_properties[idx].default_uint_value);
428}
429
430bool Debugger::SetTabSize(uint32_t tab_size) {
431 const uint32_t idx = ePropertyTabSize;
432 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000433}
434
Greg Clayton1b654882010-09-19 02:33:57 +0000435#pragma mark Debugger
436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437// const DebuggerPropertiesSP &
438// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000439//{
440// return m_properties_sp;
441//}
442//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000443
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
445 assert(g_debugger_list_ptr == nullptr &&
446 "Debugger::Initialize called more than once!");
447 g_debugger_list_mutex_ptr = new std::recursive_mutex();
448 g_debugger_list_ptr = new DebuggerList();
449 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450}
451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452void Debugger::Terminate() {
453 assert(g_debugger_list_ptr &&
454 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
457 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000458 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
460 for (const auto &debugger : *g_debugger_list_ptr)
461 debugger->Clear();
462 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000463 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465}
466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000468
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000470
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471bool Debugger::LoadPlugin(const FileSpec &spec, Error &error) {
472 if (g_load_plugin_callback) {
473 llvm::sys::DynamicLibrary dynlib =
474 g_load_plugin_callback(shared_from_this(), spec, error);
475 if (dynlib.isValid()) {
476 m_loaded_plugins.push_back(dynlib);
477 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 } else {
480 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
481 // and if the public API layer isn't available (code is linking against
482 // all of the internal LLDB static libraries), then we can't load plugins
483 error.SetErrorString("Public API layer is not available");
484 }
485 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000486}
487
488static FileSpec::EnumerateDirectoryResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489LoadPluginCallback(void *baton, FileSpec::FileType file_type,
490 const FileSpec &file_spec) {
491 Error error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 static ConstString g_dylibext("dylib");
494 static ConstString g_solibext("so");
495
496 if (!baton)
497 return FileSpec::eEnumerateDirectoryResultQuit;
498
499 Debugger *debugger = (Debugger *)baton;
500
501 // If we have a regular file, a symbolic link or unknown file type, try
502 // and process the file. We must handle unknown as sometimes the directory
503 // enumeration might be enumerating a file system that doesn't have correct
504 // file type information.
505 if (file_type == FileSpec::eFileTypeRegular ||
506 file_type == FileSpec::eFileTypeSymbolicLink ||
507 file_type == FileSpec::eFileTypeUnknown) {
508 FileSpec plugin_file_spec(file_spec);
509 plugin_file_spec.ResolvePath();
510
511 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
512 plugin_file_spec.GetFileNameExtension() != g_solibext) {
513 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515
516 Error plugin_load_error;
517 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
518
Enrico Granata21dfcd92012-09-28 23:57:51 +0000519 return FileSpec::eEnumerateDirectoryResultNext;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 } else if (file_type == FileSpec::eFileTypeUnknown ||
521 file_type == FileSpec::eFileTypeDirectory ||
522 file_type == FileSpec::eFileTypeSymbolicLink) {
523 // Try and recurse into anything that a directory or symbolic link.
524 // We must also do this for unknown as sometimes the directory enumeration
525 // might be enumerating a file system that doesn't have correct file type
526 // information.
527 return FileSpec::eEnumerateDirectoryResultEnter;
528 }
529
530 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000531}
532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533void Debugger::InstanceInitialize() {
534 FileSpec dir_spec;
535 const bool find_directories = true;
536 const bool find_files = true;
537 const bool find_other = true;
538 char dir_path[PATH_MAX];
539 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec)) {
540 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
541 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
542 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec)) {
547 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
548 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
549 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000550 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 }
552
553 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000554}
555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
557 void *baton) {
558 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
559 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
560 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
561 g_debugger_list_ptr->push_back(debugger_sp);
562 }
563 debugger_sp->InstanceInitialize();
564 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000565}
566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567void Debugger::Destroy(DebuggerSP &debugger_sp) {
568 if (!debugger_sp)
569 return;
570
571 debugger_sp->Clear();
572
573 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
574 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
575 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
576 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
577 if ((*pos).get() == debugger_sp.get()) {
578 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000579 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000583}
584
Greg Clayton4d122c42011-09-17 08:33:22 +0000585DebuggerSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
587 DebuggerSP debugger_sp;
588 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
589 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
590 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
591 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
592 if ((*pos)->m_instance_name == instance_name) {
593 debugger_sp = *pos;
594 break;
595 }
Greg Clayton6920b522012-08-22 18:39:03 +0000596 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 }
598 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000599}
Greg Clayton66111032010-06-23 01:19:29 +0000600
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
602 TargetSP target_sp;
603 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
604 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
605 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
606 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
607 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
608 if (target_sp)
609 break;
Greg Clayton66111032010-06-23 01:19:29 +0000610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 }
612 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000613}
614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615TargetSP Debugger::FindTargetWithProcess(Process *process) {
616 TargetSP target_sp;
617 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
618 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
619 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
620 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
621 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
622 if (target_sp)
623 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000624 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 }
626 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000627}
628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
630 : UserID(g_unique_id++),
631 Properties(OptionValuePropertiesSP(new OptionValueProperties())),
632 m_input_file_sp(new StreamFile(stdin, false)),
633 m_output_file_sp(new StreamFile(stdout, false)),
634 m_error_file_sp(new StreamFile(stderr, false)),
635 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
636 m_terminal_state(), m_target_list(*this), m_platform_list(),
637 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
638 m_source_manager_ap(), m_source_file_cache(),
639 m_command_interpreter_ap(
640 new CommandInterpreter(*this, eScriptLanguageDefault, false)),
641 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
642 m_event_handler_thread(), m_io_handler_thread(),
643 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
644 m_forward_listener_sp(), m_clear_once() {
645 char instance_cstr[256];
646 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
647 m_instance_name.SetCString(instance_cstr);
648 if (log_callback)
649 m_log_callback_stream_sp.reset(new StreamCallback(log_callback, baton));
650 m_command_interpreter_ap->Initialize();
651 // Always add our default platform to the platform list
652 PlatformSP default_platform_sp(Platform::GetHostPlatform());
653 assert(default_platform_sp);
654 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 m_collection_sp->Initialize(g_properties);
657 m_collection_sp->AppendProperty(
658 ConstString("target"),
659 ConstString("Settings specify to debugging targets."), true,
660 Target::GetGlobalProperties()->GetValueProperties());
661 m_collection_sp->AppendProperty(
662 ConstString("platform"), ConstString("Platform settings."), true,
663 Platform::GetGlobalPlatformProperties()->GetValueProperties());
664 if (m_command_interpreter_ap) {
665 m_collection_sp->AppendProperty(
666 ConstString("interpreter"),
667 ConstString("Settings specify to the debugger's command interpreter."),
668 true, m_command_interpreter_ap->GetValueProperties());
669 }
670 OptionValueSInt64 *term_width =
671 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
672 nullptr, ePropertyTerminalWidth);
673 term_width->SetMinimumValue(10);
674 term_width->SetMaximumValue(1024);
675
676 // Turn off use-color if this is a dumb terminal.
677 const char *term = getenv("TERM");
678 if (term && !strcmp(term, "dumb"))
679 SetUseColor(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680}
681
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684void Debugger::Clear() {
685 //----------------------------------------------------------------------
686 // Make sure we call this function only once. With the C++ global
687 // destructor chain having a list of debuggers and with code that can be
688 // running on other threads, we need to ensure this doesn't happen
689 // multiple times.
690 //
691 // The following functions call Debugger::Clear():
692 // Debugger::~Debugger();
693 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
694 // static void Debugger::Terminate();
695 //----------------------------------------------------------------------
696 std::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000697 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 StopIOHandlerThread();
699 StopEventHandlerThread();
700 m_listener_sp->Clear();
701 int num_targets = m_target_list.GetNumTargets();
702 for (int i = 0; i < num_targets; i++) {
703 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
704 if (target_sp) {
705 ProcessSP process_sp(target_sp->GetProcessSP());
706 if (process_sp)
707 process_sp->Finalize();
708 target_sp->Destroy();
709 }
Greg Clayton577508d2014-06-20 00:23:57 +0000710 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 m_broadcaster_manager_sp->Clear();
712
713 // Close the input file _before_ we close the input read communications
714 // class
715 // as it does NOT own the input file, our m_input_file does.
716 m_terminal_state.Clear();
717 if (m_input_file_sp)
718 m_input_file_sp->GetFile().Close();
719
720 m_command_interpreter_ap->Clear();
721 });
Greg Clayton44d93782014-01-27 23:43:24 +0000722}
723
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724bool Debugger::GetCloseInputOnEOF() const {
725 // return m_input_comm.GetCloseOnEOF();
726 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000727}
728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729void Debugger::SetCloseInputOnEOF(bool b) {
730 // m_input_comm.SetCloseOnEOF(b);
731}
732
733bool Debugger::GetAsyncExecution() {
734 return !m_command_interpreter_ap->GetSynchronous();
735}
736
737void Debugger::SetAsyncExecution(bool async_execution) {
738 m_command_interpreter_ap->SetSynchronous(!async_execution);
739}
740
741void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
742 if (m_input_file_sp)
743 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
744 else
745 m_input_file_sp.reset(new StreamFile(fh, tranfer_ownership));
746
747 File &in_file = m_input_file_sp->GetFile();
748 if (!in_file.IsValid())
749 in_file.SetStream(stdin, true);
750
751 // Save away the terminal state if that is relevant, so that we can restore it
752 // in RestoreInputState.
753 SaveInputTerminalState();
754}
755
756void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
757 if (m_output_file_sp)
758 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
759 else
760 m_output_file_sp.reset(new StreamFile(fh, tranfer_ownership));
761
762 File &out_file = m_output_file_sp->GetFile();
763 if (!out_file.IsValid())
764 out_file.SetStream(stdout, false);
765
766 // do not create the ScriptInterpreter just for setting the output file handle
767 // as the constructor will know how to do the right thing on its own
768 const bool can_create = false;
769 ScriptInterpreter *script_interpreter =
770 GetCommandInterpreter().GetScriptInterpreter(can_create);
771 if (script_interpreter)
772 script_interpreter->ResetOutputFileHandle(fh);
773}
774
775void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
776 if (m_error_file_sp)
777 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
778 else
779 m_error_file_sp.reset(new StreamFile(fh, tranfer_ownership));
780
781 File &err_file = m_error_file_sp->GetFile();
782 if (!err_file.IsValid())
783 err_file.SetStream(stderr, false);
784}
785
786void Debugger::SaveInputTerminalState() {
787 if (m_input_file_sp) {
788 File &in_file = m_input_file_sp->GetFile();
789 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
790 m_terminal_state.Save(in_file.GetDescriptor(), true);
791 }
792}
793
794void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
795
796ExecutionContext Debugger::GetSelectedExecutionContext() {
797 ExecutionContext exe_ctx;
798 TargetSP target_sp(GetSelectedTarget());
799 exe_ctx.SetTargetSP(target_sp);
800
801 if (target_sp) {
802 ProcessSP process_sp(target_sp->GetProcessSP());
803 exe_ctx.SetProcessSP(process_sp);
804 if (process_sp && !process_sp->IsRunning()) {
805 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
806 if (thread_sp) {
807 exe_ctx.SetThreadSP(thread_sp);
808 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
809 if (exe_ctx.GetFramePtr() == nullptr)
810 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
811 }
812 }
813 }
814 return exe_ctx;
815}
816
817void Debugger::DispatchInputInterrupt() {
818 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
819 IOHandlerSP reader_sp(m_input_reader_stack.Top());
820 if (reader_sp)
821 reader_sp->Interrupt();
822}
823
824void Debugger::DispatchInputEndOfFile() {
825 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
826 IOHandlerSP reader_sp(m_input_reader_stack.Top());
827 if (reader_sp)
828 reader_sp->GotEOF();
829}
830
831void Debugger::ClearIOHandlers() {
832 // The bottom input reader should be the main debugger input reader. We do
833 // not want to close that one here.
834 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
835 while (m_input_reader_stack.GetSize() > 1) {
836 IOHandlerSP reader_sp(m_input_reader_stack.Top());
837 if (reader_sp)
838 PopIOHandler(reader_sp);
839 }
840}
841
842void Debugger::ExecuteIOHandlers() {
843 while (true) {
844 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000847
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 // Remove all input readers that are done from the top of the stack
851 while (true) {
852 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
853 if (top_reader_sp && top_reader_sp->GetIsDone())
854 PopIOHandler(top_reader_sp);
855 else
856 break;
857 }
858 }
859 ClearIOHandlers();
860}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
863 return m_input_reader_stack.IsTop(reader_sp);
864}
Greg Clayton44d93782014-01-27 23:43:24 +0000865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
867 IOHandler::Type second_top_type) {
868 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
869}
870
871void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
872 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
873 m_input_reader_stack.PrintAsync(stream.get(), s, len);
874}
875
876ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
877 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
878}
879
880const char *Debugger::GetIOHandlerCommandPrefix() {
881 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
882}
883
884const char *Debugger::GetIOHandlerHelpPrologue() {
885 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
886}
887
888void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
889 PushIOHandler(reader_sp);
890
891 IOHandlerSP top_reader_sp = reader_sp;
892 while (top_reader_sp) {
893 top_reader_sp->Run();
894
895 if (top_reader_sp.get() == reader_sp.get()) {
896 if (PopIOHandler(reader_sp))
897 break;
898 }
899
900 while (true) {
901 top_reader_sp = m_input_reader_stack.Top();
902 if (top_reader_sp && top_reader_sp->GetIsDone())
903 PopIOHandler(top_reader_sp);
904 else
905 break;
906 }
907 }
908}
909
910void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
911 StreamFileSP &out,
912 StreamFileSP &err) {
913 // Before an IOHandler runs, it must have in/out/err streams.
914 // This function is called when one ore more of the streams
915 // are nullptr. We use the top input reader's in/out/err streams,
916 // or fall back to the debugger file handles, or we fall back
917 // onto stdin/stdout/stderr as a last resort.
918
919 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
920 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
921 // If no STDIN has been set, then set it appropriately
922 if (!in) {
923 if (top_reader_sp)
924 in = top_reader_sp->GetInputStreamFile();
925 else
926 in = GetInputFile();
927
928 // If there is nothing, use stdin
929 if (!in)
930 in = StreamFileSP(new StreamFile(stdin, false));
931 }
932 // If no STDOUT has been set, then set it appropriately
933 if (!out) {
934 if (top_reader_sp)
935 out = top_reader_sp->GetOutputStreamFile();
936 else
937 out = GetOutputFile();
938
939 // If there is nothing, use stdout
940 if (!out)
941 out = StreamFileSP(new StreamFile(stdout, false));
942 }
943 // If no STDERR has been set, then set it appropriately
944 if (!err) {
945 if (top_reader_sp)
946 err = top_reader_sp->GetErrorStreamFile();
947 else
948 err = GetErrorFile();
949
950 // If there is nothing, use stderr
951 if (!err)
952 err = StreamFileSP(new StreamFile(stdout, false));
953 }
954}
955
956void Debugger::PushIOHandler(const IOHandlerSP &reader_sp) {
957 if (!reader_sp)
958 return;
959
960 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
961
962 // Get the current top input reader...
963 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
964
965 // Don't push the same IO handler twice...
966 if (reader_sp == top_reader_sp)
967 return;
968
969 // Push our new input reader
970 m_input_reader_stack.Push(reader_sp);
971 reader_sp->Activate();
972
973 // Interrupt the top input reader to it will exit its Run() function
974 // and let this new input reader take over
975 if (top_reader_sp) {
976 top_reader_sp->Deactivate();
977 top_reader_sp->Cancel();
978 }
979}
980
981bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
982 if (!pop_reader_sp)
983 return false;
984
985 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
986
987 // The reader on the stop of the stack is done, so let the next
988 // read on the stack refresh its prompt and if there is one...
989 if (m_input_reader_stack.IsEmpty())
990 return false;
991
992 IOHandlerSP reader_sp(m_input_reader_stack.Top());
993
994 if (pop_reader_sp != reader_sp)
995 return false;
996
997 reader_sp->Deactivate();
998 reader_sp->Cancel();
999 m_input_reader_stack.Pop();
1000
1001 reader_sp = m_input_reader_stack.Top();
1002 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001003 reader_sp->Activate();
1004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 return true;
1006}
1007
1008StreamSP Debugger::GetAsyncOutputStream() {
1009 return StreamSP(new StreamAsynchronousIO(*this, true));
1010}
1011
1012StreamSP Debugger::GetAsyncErrorStream() {
1013 return StreamSP(new StreamAsynchronousIO(*this, false));
1014}
1015
1016size_t Debugger::GetNumDebuggers() {
1017 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1018 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1019 return g_debugger_list_ptr->size();
1020 }
1021 return 0;
1022}
1023
1024lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1025 DebuggerSP debugger_sp;
1026
1027 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1028 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1029 if (index < g_debugger_list_ptr->size())
1030 debugger_sp = g_debugger_list_ptr->at(index);
1031 }
1032
1033 return debugger_sp;
1034}
1035
1036DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1037 DebuggerSP debugger_sp;
1038
1039 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1040 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1041 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1042 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1043 if ((*pos)->GetID() == id) {
1044 debugger_sp = *pos;
1045 break;
1046 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001047 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048 }
1049 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001050}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001051
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001052#if 0
Greg Clayton1b654882010-09-19 02:33:57 +00001053static void
Jason Molendab57e4a12013-11-04 09:33:30 +00001054TestPromptFormats (StackFrame *frame)
Greg Clayton1b654882010-09-19 02:33:57 +00001055{
Eugene Zelenkodf370552016-03-02 02:18:18 +00001056 if (frame == nullptr)
Greg Clayton1b654882010-09-19 02:33:57 +00001057 return;
1058
1059 StreamString s;
1060 const char *prompt_format =
1061 "{addr = '${addr}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001062 "{addr-file-or-load = '${addr-file-or-load}'\n}"
1063 "{current-pc-arrow = '${current-pc-arrow}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001064 "{process.id = '${process.id}'\n}"
1065 "{process.name = '${process.name}'\n}"
1066 "{process.file.basename = '${process.file.basename}'\n}"
1067 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1068 "{thread.id = '${thread.id}'\n}"
1069 "{thread.index = '${thread.index}'\n}"
1070 "{thread.name = '${thread.name}'\n}"
1071 "{thread.queue = '${thread.queue}'\n}"
1072 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1073 "{target.arch = '${target.arch}'\n}"
1074 "{module.file.basename = '${module.file.basename}'\n}"
1075 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1076 "{file.basename = '${file.basename}'\n}"
1077 "{file.fullpath = '${file.fullpath}'\n}"
1078 "{frame.index = '${frame.index}'\n}"
1079 "{frame.pc = '${frame.pc}'\n}"
1080 "{frame.sp = '${frame.sp}'\n}"
1081 "{frame.fp = '${frame.fp}'\n}"
1082 "{frame.flags = '${frame.flags}'\n}"
1083 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1084 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1085 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1086 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1087 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1088 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1089 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1090 "{function.id = '${function.id}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001091 "{function.changed = '${function.changed}'\n}"
1092 "{function.initial-function = '${function.initial-function}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001093 "{function.name = '${function.name}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001094 "{function.name-without-args = '${function.name-without-args}'\n}"
Greg Claytonccbc08e2012-01-14 17:04:19 +00001095 "{function.name-with-args = '${function.name-with-args}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001096 "{function.addr-offset = '${function.addr-offset}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001097 "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001098 "{function.line-offset = '${function.line-offset}'\n}"
1099 "{function.pc-offset = '${function.pc-offset}'\n}"
1100 "{line.file.basename = '${line.file.basename}'\n}"
1101 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1102 "{line.number = '${line.number}'\n}"
1103 "{line.start-addr = '${line.start-addr}'\n}"
1104 "{line.end-addr = '${line.end-addr}'\n}"
1105;
1106
1107 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1108 ExecutionContext exe_ctx;
Greg Clayton0603aa92010-10-04 01:05:56 +00001109 frame->CalculateExecutionContext(exe_ctx);
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001110 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
Greg Clayton1b654882010-09-19 02:33:57 +00001111 {
1112 printf("%s\n", s.GetData());
1113 }
1114 else
1115 {
Greg Clayton1b654882010-09-19 02:33:57 +00001116 printf ("what we got: %s\n", s.GetData());
1117 }
1118}
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001119#endif
Greg Clayton1b654882010-09-19 02:33:57 +00001120
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1122 const SymbolContext *sc,
1123 const SymbolContext *prev_sc,
1124 const ExecutionContext *exe_ctx,
1125 const Address *addr, Stream &s) {
1126 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001127
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 if (format == nullptr) {
1129 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1130 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1131 if (format == nullptr) {
1132 FormatEntity::Parse("${addr}: ", format_entry);
1133 format = &format_entry;
1134 }
1135 }
1136 bool function_changed = false;
1137 bool initial_function = false;
1138 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1139 if (sc && (sc->function || sc->symbol)) {
1140 if (prev_sc->symbol && sc->symbol) {
1141 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1142 prev_sc->symbol->GetType())) {
1143 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001144 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 } else if (prev_sc->function && sc->function) {
1146 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1147 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001148 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 }
1152 // The first context on a list of instructions will have a prev_sc that
1153 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1154 // would return false. But we do get a prev_sc pointer.
1155 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1156 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1157 initial_function = true;
1158 }
1159 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1160 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001161}
1162
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1164 void *baton) {
1165 // For simplicity's sake, I am not going to deal with how to close down any
1166 // open logging streams, I just redirect everything from here on out to the
1167 // callback.
1168 m_log_callback_stream_sp.reset(new StreamCallback(log_callback, baton));
Jim Ingham228063c2012-02-21 02:23:08 +00001169}
1170
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171bool Debugger::EnableLog(const char *channel, const char **categories,
1172 const char *log_file, uint32_t log_options,
1173 Stream &error_stream) {
1174 StreamSP log_stream_sp;
1175 if (m_log_callback_stream_sp) {
1176 log_stream_sp = m_log_callback_stream_sp;
1177 // For now when using the callback mode you always get thread & timestamp.
1178 log_options |=
1179 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1180 } else if (log_file == nullptr || *log_file == '\0') {
1181 log_stream_sp = GetOutputFile();
1182 } else {
1183 LogStreamMap::iterator pos = m_log_streams.find(log_file);
1184 if (pos != m_log_streams.end())
1185 log_stream_sp = pos->second.lock();
1186 if (!log_stream_sp) {
1187 uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate |
1188 File::eOpenOptionCloseOnExec | File::eOpenOptionAppend;
1189 if (!(log_options & LLDB_LOG_OPTION_APPEND))
1190 options |= File::eOpenOptionTruncate;
Pavel Labath8ac06992015-03-20 09:43:20 +00001191
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 log_stream_sp.reset(new StreamFile(log_file, options));
1193 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001194 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 }
1196 assert(log_stream_sp);
1197
1198 if (log_options == 0)
1199 log_options =
1200 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1201
1202 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1203 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001204}
1205
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206SourceManager &Debugger::GetSourceManager() {
1207 if (!m_source_manager_ap)
1208 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
1209 return *m_source_manager_ap;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001210}
1211
Greg Clayton44d93782014-01-27 23:43:24 +00001212// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1214 using namespace lldb;
1215 const uint32_t event_type =
1216 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1217 event_sp);
1218
1219 // if (event_type & eBreakpointEventTypeAdded
1220 // || event_type & eBreakpointEventTypeRemoved
1221 // || event_type & eBreakpointEventTypeEnabled
1222 // || event_type & eBreakpointEventTypeDisabled
1223 // || event_type & eBreakpointEventTypeCommandChanged
1224 // || event_type & eBreakpointEventTypeConditionChanged
1225 // || event_type & eBreakpointEventTypeIgnoreChanged
1226 // || event_type & eBreakpointEventTypeLocationsResolved)
1227 // {
1228 // // Don't do anything about these events, since the breakpoint
1229 // commands already echo these actions.
1230 // }
1231 //
1232 if (event_type & eBreakpointEventTypeLocationsAdded) {
1233 uint32_t num_new_locations =
1234 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1235 event_sp);
1236 if (num_new_locations > 0) {
1237 BreakpointSP breakpoint =
1238 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1239 StreamSP output_sp(GetAsyncOutputStream());
1240 if (output_sp) {
1241 output_sp->Printf("%d location%s added to breakpoint %d\n",
1242 num_new_locations, num_new_locations == 1 ? "" : "s",
1243 breakpoint->GetID());
1244 output_sp->Flush();
1245 }
Greg Clayton44d93782014-01-27 23:43:24 +00001246 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 }
1248 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1249 // {
1250 // // These locations just get disabled, not sure it is worth spamming
1251 // folks about this on the command line.
1252 // }
1253 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1254 // {
1255 // // This might be an interesting thing to note, but I'm going to
1256 // leave it quiet for now, it just looked noisy.
1257 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001258}
1259
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1261 size_t total_bytes = 0;
1262 if (stream == nullptr)
1263 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001264
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 if (stream) {
1266 // The process has stuff waiting for stdout; get it and write it out to the
1267 // appropriate place.
1268 if (process == nullptr) {
1269 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1270 if (target_sp)
1271 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001272 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 if (process) {
1274 Error error;
1275 size_t len;
1276 char stdio_buffer[1024];
1277 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1278 error)) > 0) {
1279 stream->Write(stdio_buffer, len);
1280 total_bytes += len;
1281 }
1282 }
1283 stream->Flush();
1284 }
1285 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001286}
1287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1289 size_t total_bytes = 0;
1290 if (stream == nullptr)
1291 stream = GetOutputFile().get();
1292
1293 if (stream) {
1294 // The process has stuff waiting for stderr; get it and write it out to the
1295 // appropriate place.
1296 if (process == nullptr) {
1297 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1298 if (target_sp)
1299 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001300 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 if (process) {
1302 Error error;
1303 size_t len;
1304 char stdio_buffer[1024];
1305 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1306 error)) > 0) {
1307 stream->Write(stdio_buffer, len);
1308 total_bytes += len;
1309 }
1310 }
1311 stream->Flush();
1312 }
1313 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001314}
1315
1316// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1318 using namespace lldb;
1319 const uint32_t event_type = event_sp->GetType();
1320 ProcessSP process_sp =
1321 (event_type == Process::eBroadcastBitStructuredData)
1322 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1323 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001324
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325 StreamSP output_stream_sp = GetAsyncOutputStream();
1326 StreamSP error_stream_sp = GetAsyncErrorStream();
1327 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001328
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329 if (!gui_enabled) {
1330 bool pop_process_io_handler = false;
1331 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001332
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 bool state_is_stopped = false;
1334 const bool got_state_changed =
1335 (event_type & Process::eBroadcastBitStateChanged) != 0;
1336 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1337 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1338 const bool got_structured_data =
1339 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001340
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341 if (got_state_changed) {
1342 StateType event_state =
1343 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1344 state_is_stopped = StateIsStoppedState(event_state, false);
1345 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001346
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 // Display running state changes first before any STDIO
1348 if (got_state_changed && !state_is_stopped) {
1349 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1350 pop_process_io_handler);
1351 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001352
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 // Now display and STDOUT
1354 if (got_stdout || got_state_changed) {
1355 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1356 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001357
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 // Now display and STDERR
1359 if (got_stderr || got_state_changed) {
1360 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1361 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001362
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 // Give structured data events an opportunity to display.
1364 if (got_structured_data) {
1365 StructuredDataPluginSP plugin_sp =
1366 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1367 if (plugin_sp) {
1368 auto structured_data_sp =
1369 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1370 if (output_stream_sp) {
1371 StreamString content_stream;
1372 Error error =
1373 plugin_sp->GetDescription(structured_data_sp, content_stream);
1374 if (error.Success()) {
1375 if (!content_stream.GetString().empty()) {
1376 // Add newline.
1377 content_stream.PutChar('\n');
1378 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001379
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 // Print it.
1381 output_stream_sp->PutCString(content_stream.GetString().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00001382 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001383 } else {
1384 error_stream_sp->Printf("Failed to print structured "
1385 "data with plugin %s: %s",
1386 plugin_sp->GetPluginName().AsCString(),
1387 error.AsCString());
1388 }
Todd Fiala75930012016-08-19 04:21:48 +00001389 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001391 }
Greg Clayton44d93782014-01-27 23:43:24 +00001392
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 // Now display any stopped state changes after any STDIO
1394 if (got_state_changed && state_is_stopped) {
1395 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1396 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001397 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398
1399 output_stream_sp->Flush();
1400 error_stream_sp->Flush();
1401
1402 if (pop_process_io_handler)
1403 process_sp->PopProcessIOHandler();
1404 }
Greg Clayton44d93782014-01-27 23:43:24 +00001405}
1406
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1408 // At present the only thread event we handle is the Frame Changed event,
1409 // and all we do for that is just reprint the thread status for that thread.
1410 using namespace lldb;
1411 const uint32_t event_type = event_sp->GetType();
1412 if (event_type == Thread::eBroadcastBitStackChanged ||
1413 event_type == Thread::eBroadcastBitThreadSelected) {
1414 ThreadSP thread_sp(
1415 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1416 if (thread_sp) {
1417 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1);
1418 }
1419 }
Greg Clayton44d93782014-01-27 23:43:24 +00001420}
1421
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1423
1424void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1425 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001426}
1427
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1429 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001430}
1431
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432void Debugger::DefaultEventHandler() {
1433 ListenerSP listener_sp(GetListener());
1434 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1435 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1436 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1437 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1438 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001439
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 BroadcastEventSpec process_event_spec(
1441 broadcaster_class_process,
1442 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1443 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001444
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1446 Thread::eBroadcastBitStackChanged |
1447 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1450 target_event_spec);
1451 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1452 process_event_spec);
1453 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1454 thread_event_spec);
1455 listener_sp->StartListeningForEvents(
1456 m_command_interpreter_ap.get(),
1457 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1458 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1459 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001460
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 // Let the thread that spawned us know that we have started up and
1462 // that we are now listening to all required events so no events get missed
1463 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001464
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 bool done = false;
1466 while (!done) {
1467 EventSP event_sp;
1468 if (listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp)) {
1469 if (event_sp) {
1470 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1471 if (broadcaster) {
1472 uint32_t event_type = event_sp->GetType();
1473 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1474 if (broadcaster_class == broadcaster_class_process) {
1475 HandleProcessEvent(event_sp);
1476 } else if (broadcaster_class == broadcaster_class_target) {
1477 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1478 event_sp.get())) {
1479 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001480 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 } else if (broadcaster_class == broadcaster_class_thread) {
1482 HandleThreadEvent(event_sp);
1483 } else if (broadcaster == m_command_interpreter_ap.get()) {
1484 if (event_type &
1485 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1486 done = true;
1487 } else if (event_type &
1488 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1489 const char *data = reinterpret_cast<const char *>(
1490 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1491 if (data && data[0]) {
1492 StreamSP error_sp(GetAsyncErrorStream());
1493 if (error_sp) {
1494 error_sp->PutCString(data);
1495 error_sp->Flush();
1496 }
1497 }
1498 } else if (event_type & CommandInterpreter::
1499 eBroadcastBitAsynchronousOutputData) {
1500 const char *data = reinterpret_cast<const char *>(
1501 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1502 if (data && data[0]) {
1503 StreamSP output_sp(GetAsyncOutputStream());
1504 if (output_sp) {
1505 output_sp->PutCString(data);
1506 output_sp->Flush();
1507 }
1508 }
1509 }
1510 }
Greg Clayton44d93782014-01-27 23:43:24 +00001511 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512
1513 if (m_forward_listener_sp)
1514 m_forward_listener_sp->AddEvent(event_sp);
1515 }
Greg Clayton44d93782014-01-27 23:43:24 +00001516 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517 }
Greg Clayton44d93782014-01-27 23:43:24 +00001518}
1519
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1521 ((Debugger *)arg)->DefaultEventHandler();
1522 return NULL;
Greg Clayton44d93782014-01-27 23:43:24 +00001523}
1524
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525bool Debugger::StartEventHandlerThread() {
1526 if (!m_event_handler_thread.IsJoinable()) {
1527 // We must synchronize with the DefaultEventHandler() thread to ensure
1528 // it is up and running and listening to events before we return from
1529 // this function. We do this by listening to events for the
1530 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1531 ListenerSP listener_sp(
1532 Listener::MakeListener("lldb.debugger.event-handler"));
1533 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1534 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001535
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 // Use larger 8MB stack for this thread
1537 m_event_handler_thread = ThreadLauncher::LaunchThread(
1538 "lldb.debugger.event-handler", EventHandlerThread, this, nullptr,
1539 g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001540
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 // Make sure DefaultEventHandler() is running and listening to events before
1542 // we return
1543 // from this function. We are only listening for events of type
1544 // eBroadcastBitEventThreadIsListening so we don't need to check the event,
1545 // we just need
1546 // to wait an infinite amount of time for it (nullptr timeout as the first
1547 // parameter)
1548 lldb::EventSP event_sp;
1549 listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp);
1550 }
1551 return m_event_handler_thread.IsJoinable();
1552}
1553
1554void Debugger::StopEventHandlerThread() {
1555 if (m_event_handler_thread.IsJoinable()) {
1556 GetCommandInterpreter().BroadcastEvent(
1557 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1558 m_event_handler_thread.Join(nullptr);
1559 }
1560}
1561
1562lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1563 Debugger *debugger = (Debugger *)arg;
1564 debugger->ExecuteIOHandlers();
1565 debugger->StopEventHandlerThread();
1566 return NULL;
1567}
1568
1569bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1570
1571bool Debugger::StartIOHandlerThread() {
1572 if (!m_io_handler_thread.IsJoinable())
1573 m_io_handler_thread = ThreadLauncher::LaunchThread(
1574 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1575 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1576 return m_io_handler_thread.IsJoinable();
1577}
1578
1579void Debugger::StopIOHandlerThread() {
1580 if (m_io_handler_thread.IsJoinable()) {
1581 if (m_input_file_sp)
1582 m_input_file_sp->GetFile().Close();
1583 m_io_handler_thread.Join(nullptr);
1584 }
1585}
1586
1587void Debugger::JoinIOHandlerThread() {
1588 if (HasIOHandlerThread()) {
1589 thread_result_t result;
1590 m_io_handler_thread.Join(&result);
1591 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1592 }
1593}
1594
1595Target *Debugger::GetDummyTarget() {
1596 return m_target_list.GetDummyTarget(*this).get();
1597}
1598
1599Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1600 Target *target = nullptr;
1601 if (!prefer_dummy) {
1602 target = m_target_list.GetSelectedTarget().get();
1603 if (target)
1604 return target;
1605 }
1606
1607 return GetDummyTarget();
1608}
1609
1610Error Debugger::RunREPL(LanguageType language, const char *repl_options) {
1611 Error err;
1612 FileSpec repl_executable;
1613
1614 if (language == eLanguageTypeUnknown) {
1615 std::set<LanguageType> repl_languages;
1616
1617 Language::GetLanguagesSupportingREPLs(repl_languages);
1618
1619 if (repl_languages.size() == 1) {
1620 language = *repl_languages.begin();
1621 } else if (repl_languages.empty()) {
1622 err.SetErrorStringWithFormat(
1623 "LLDB isn't configured with REPL support for any languages.");
1624 return err;
1625 } else {
1626 err.SetErrorStringWithFormat(
1627 "Multiple possible REPL languages. Please specify a language.");
1628 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001629 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 }
Greg Clayton44d93782014-01-27 23:43:24 +00001631
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632 Target *const target =
1633 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001634
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001636
Kate Stoneb9c1b512016-09-06 20:57:50 +00001637 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001638 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 }
1640
1641 if (!repl_sp) {
1642 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1643 Language::GetNameForLanguageType(language));
1644 return err;
1645 }
1646
1647 repl_sp->SetCompilerOptions(repl_options);
1648 repl_sp->RunLoop();
1649
1650 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001651}