blob: d42e4df56d8bc152d04fd9b7a0698df8d494c6c5 [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
Zachary Turner2f3df612017-04-06 21:28:29 +000012#include "lldb/Breakpoint/Breakpoint.h" // for Breakpoint, Brea...
13#include "lldb/Core/Event.h" // for Event, EventData...
Greg Clayton554f68d2015-02-04 22:00:53 +000014#include "lldb/Core/FormatEntity.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000015#include "lldb/Core/Listener.h" // for Listener
16#include "lldb/Core/Mangled.h" // for Mangled
Greg Claytone8cd0c92012-10-19 18:02:49 +000017#include "lldb/Core/PluginManager.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/State.h"
Jim Ingham5b52f0c2011-06-02 23:58:26 +000019#include "lldb/Core/StreamAsynchronousIO.h"
Greg Clayton44d93782014-01-27 23:43:24 +000020#include "lldb/Core/StreamFile.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000021#include "lldb/DataFormatters/DataVisualization.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000022#include "lldb/Expression/REPL.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000023#include "lldb/Host/File.h" // for File, File::kInv...
Zachary Turner42ff0ad2014-08-21 17:29:12 +000024#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000025#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000026#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000028#include "lldb/Interpreter/OptionValue.h" // for OptionValue, Opt...
Zachary Turner633a29c2015-03-04 01:58:01 +000029#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000030#include "lldb/Interpreter/OptionValueSInt64.h"
31#include "lldb/Interpreter/OptionValueString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000032#include "lldb/Interpreter/Property.h" // for PropertyDefinition
33#include "lldb/Interpreter/ScriptInterpreter.h" // for ScriptInterpreter
Greg Clayton1f746072012-08-29 21:13:06 +000034#include "lldb/Symbol/Function.h"
35#include "lldb/Symbol/Symbol.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000036#include "lldb/Symbol/SymbolContext.h" // for SymbolContext
Sean Callanan3e7e9152015-10-20 00:23:46 +000037#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Target/Process.h"
Todd Fiala75930012016-08-19 04:21:48 +000039#include "lldb/Target/StructuredDataPlugin.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000040#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#include "lldb/Target/TargetList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Target/Thread.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000043#include "lldb/Target/ThreadList.h" // for ThreadList
Greg Clayton5a314712011-10-14 07:41:33 +000044#include "lldb/Utility/AnsiTerminal.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000045#include "lldb/Utility/Log.h" // for LLDB_LOG_OPTION_...
46#include "lldb/Utility/Stream.h" // for Stream
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000047#include "lldb/Utility/StreamCallback.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000048#include "lldb/Utility/StreamString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000049
50#if defined(LLVM_ON_WIN32)
51#include "lldb/Host/windows/PosixApi.h" // for PATH_MAX
52#endif
53
54#include "llvm/ADT/None.h" // for None
55#include "llvm/ADT/STLExtras.h" // for make_unique
56#include "llvm/ADT/StringRef.h"
57#include "llvm/ADT/iterator.h" // for iterator_facade_...
58#include "llvm/Support/DynamicLibrary.h"
59#include "llvm/Support/FileSystem.h"
60#include "llvm/Support/Threading.h"
61#include "llvm/Support/raw_ostream.h" // for raw_fd_ostream
62
63#include <list> // for list
64#include <memory> // for make_shared
65#include <mutex>
66#include <set> // for set
67#include <stdio.h> // for size_t, NULL
68#include <stdlib.h> // for getenv
69#include <string.h> // for strcmp
70#include <string> // for string
71#include <system_error> // for error_code
72
73namespace lldb_private {
74class Address;
75}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000076
77using namespace lldb;
78using namespace lldb_private;
79
Caroline Ticeebc1bb22010-06-30 16:22:25 +000080static lldb::user_id_t g_unique_id = 1;
Zachary Turner7c2896a2014-10-24 22:06:29 +000081static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000082
Greg Clayton1b654882010-09-19 02:33:57 +000083#pragma mark Static Functions
84
Greg Clayton1b654882010-09-19 02:33:57 +000085typedef std::vector<DebuggerSP> DebuggerList;
Kate Stoneb9c1b512016-09-06 20:57:50 +000086static std::recursive_mutex *g_debugger_list_mutex_ptr =
87 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
88static DebuggerList *g_debugger_list_ptr =
89 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
Greg Claytone372b982011-11-21 21:44:34 +000090
Kate Stoneb9c1b512016-09-06 20:57:50 +000091OptionEnumValueElement g_show_disassembly_enum_values[] = {
92 {Debugger::eStopDisassemblyTypeNever, "never",
93 "Never show disassembly when displaying a stop context."},
94 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
95 "Show disassembly when there is no debug information."},
96 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
97 "Show disassembly when there is no source information, or the source file "
98 "is missing when displaying a stop context."},
99 {Debugger::eStopDisassemblyTypeAlways, "always",
100 "Always show disassembly when displaying a stop context."},
101 {0, nullptr, nullptr}};
Greg Claytone372b982011-11-21 21:44:34 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103OptionEnumValueElement g_language_enumerators[] = {
104 {eScriptLanguageNone, "none", "Disable scripting languages."},
105 {eScriptLanguagePython, "python",
106 "Select python as the default scripting language."},
107 {eScriptLanguageDefault, "default",
108 "Select the lldb default as the default scripting language."},
109 {0, nullptr, nullptr}};
Greg Claytone372b982011-11-21 21:44:34 +0000110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111#define MODULE_WITH_FUNC \
112 "{ " \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000113 "${module.file.basename}{`${function.name-with-args}" \
114 "{${frame.no-debug}${function.pc-offset}}}}"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000115
116#define MODULE_WITH_FUNC_NO_ARGS \
117 "{ " \
118 "${module.file.basename}{`${function.name-without-args}" \
119 "{${frame.no-debug}${function.pc-offset}}}}"
120
Greg Clayton67cc0632012-08-22 17:17:09 +0000121#define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
Jason Molenda6ab659a2015-07-29 00:42:47 +0000122#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000123
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124#define DEFAULT_THREAD_FORMAT \
125 "thread #${thread.index}: tid = ${thread.id%tid}" \
126 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
127 "{, name = '${thread.name}'}" \
128 "{, queue = '${thread.queue}'}" \
129 "{, activity = '${thread.info.activity.name}'}" \
130 "{, ${thread.info.trace_messages} messages}" \
131 "{, stop reason = ${thread.stop-reason}}" \
132 "{\\nReturn value: ${thread.return-value}}" \
133 "{\\nCompleted expression: ${thread.completed-expression}}" \
134 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000135
Jim Ingham6a9767c2016-11-08 20:36:40 +0000136#define DEFAULT_THREAD_STOP_FORMAT \
137 "thread #${thread.index}{, name = '${thread.name}'}" \
138 "{, queue = '${thread.queue}'}" \
139 "{, activity = '${thread.info.activity.name}'}" \
140 "{, ${thread.info.trace_messages} messages}" \
141 "{, stop reason = ${thread.stop-reason}}" \
142 "{\\nReturn value: ${thread.return-value}}" \
143 "{\\nCompleted expression: ${thread.completed-expression}}" \
144 "\\n"
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146#define DEFAULT_FRAME_FORMAT \
Jason Molenda270e8222017-01-28 02:54:10 +0000147 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 IS_OPTIMIZED "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000149
Pavel Labath7f1c1212017-06-12 16:25:24 +0000150#define DEFAULT_FRAME_FORMAT_NO_ARGS \
151 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \
152 IS_OPTIMIZED "\\n"
153
Jason Molendac980fa92015-02-13 23:24:21 +0000154// Three parts to this disassembly format specification:
155// 1. If this is a new function/symbol (no previous symbol/function), print
156// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157// 2. If this is a symbol context change (different from previous
158// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000159// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160// 3. print
161// address <+offset>:
162#define DEFAULT_DISASSEMBLY_FORMAT \
163 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
164 "without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${" \
165 "function.name-without-args}}:\n}{${current-pc-arrow} " \
166 "}${addr-file-or-load}{ " \
167 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000168
169// gdb's disassembly format can be emulated with
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170// ${current-pc-arrow}${addr-file-or-load}{
171// <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000172
173// lldb's original format for disassembly would look like this format string -
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174// {${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}
175// }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000176
Todd Fiala9666ba72016-09-21 20:13:14 +0000177#define DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX "${ansi.underline}"
178#define DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX "${ansi.normal}"
179
180static OptionEnumValueElement s_stop_show_column_values[] = {
181 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
182 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
183 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
184 "\"caret-only\" mode was selected."},
185 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
186 "terminal codes when running LLDB with "
187 "color/ANSI enabled."},
188 {eStopShowColumnCaret, "caret",
189 "Highlight the stop column with a caret character (^) underneath the stop "
190 "column. This method introduces a new line in source listings that "
191 "display thread stop locations."},
192 {eStopShowColumnNone, "none", "Do not highlight the stop column."},
193 {0, nullptr, nullptr}};
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195static PropertyDefinition g_properties[] = {
196 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
197 "If true all confirmation prompts will receive their default reply."},
198 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000199 DEFAULT_DISASSEMBLY_FORMAT, nullptr,
200 "The default disassembly format "
201 "string to use when disassembling "
202 "instruction sequences."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 {"frame-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000204 DEFAULT_FRAME_FORMAT, nullptr,
205 "The default frame format string to use "
206 "when displaying stack frame information "
207 "for threads."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
209 "Notify the user explicitly if an expression returns void (default: "
210 "false)."},
211 {"prompt", OptionValue::eTypeString, true,
212 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ",
213 nullptr, "The debugger command line prompt displayed for the user."},
214 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
215 nullptr, g_language_enumerators,
216 "The script language to be used for evaluating user-written scripts."},
217 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000218 nullptr,
219 "The number of disassembly lines to show when displaying a "
220 "stopped context."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
222 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
223 g_show_disassembly_enum_values,
224 "Control when to display disassembly when displaying a stopped context."},
225 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000226 nullptr,
227 "The number of sources lines to display that come after the "
228 "current source line when displaying a stopped context."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000230 nullptr,
231 "The number of sources lines to display that come before the "
232 "current source line when displaying a stopped context."},
Todd Fiala9666ba72016-09-21 20:13:14 +0000233 {"stop-show-column", OptionValue::eTypeEnum, false,
234 eStopShowColumnAnsiOrCaret, nullptr, s_stop_show_column_values,
235 "If true, LLDB will use the column information from the debug info to "
236 "mark the current position when displaying a stopped context."},
237 {"stop-show-column-ansi-prefix", OptionValue::eTypeFormatEntity, true, 0,
238 DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX, nullptr,
239 "When displaying the column marker in a color-enabled (i.e. ANSI) "
240 "terminal, use the ANSI terminal code specified in this format at the "
241 "immediately before the column to be marked."},
242 {"stop-show-column-ansi-suffix", OptionValue::eTypeFormatEntity, true, 0,
243 DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX, nullptr,
244 "When displaying the column marker in a color-enabled (i.e. ANSI) "
245 "terminal, use the ANSI terminal code specified in this format "
246 "immediately after the column to be marked."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, nullptr,
248 "The maximum number of columns to use for displaying text."},
249 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000250 DEFAULT_THREAD_FORMAT, nullptr,
251 "The default thread format string to use "
252 "when displaying thread information."},
Jim Ingham6a9767c2016-11-08 20:36:40 +0000253 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000254 DEFAULT_THREAD_STOP_FORMAT, nullptr,
255 "The default thread format "
256 "string to use when displaying thread "
257 "information as part of the stop display."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr,
259 nullptr, "Whether to use an external editor or not."},
260 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
261 "Whether to use Ansi color codes or not."},
262 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000263 nullptr,
264 "If true, LLDB will automatically display small structs in "
265 "one-liner format (default: true)."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
267 "If true, LLDB will auto indent/outdent code. Currently only supported in "
268 "the REPL (default: true)."},
269 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
270 "If true, LLDB will print the values of variables declared in an "
271 "expression. Currently only supported in the REPL (default: true)."},
272 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, nullptr,
273 "The tab size to use when indenting code in multi-line input mode "
274 "(default: 4)."},
275 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000276 nullptr,
277 "If true, LLDB will automatically escape non-printable and "
278 "escape characters when formatting strings."},
279 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0,
280 DEFAULT_FRAME_FORMAT_NO_ARGS, nullptr,
281 "The default frame format string to use when displaying stack frame"
282 "information for threads from thread backtrace unique."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285enum {
286 ePropertyAutoConfirm = 0,
287 ePropertyDisassemblyFormat,
288 ePropertyFrameFormat,
289 ePropertyNotiftVoid,
290 ePropertyPrompt,
291 ePropertyScriptLanguage,
292 ePropertyStopDisassemblyCount,
293 ePropertyStopDisassemblyDisplay,
294 ePropertyStopLineCountAfter,
295 ePropertyStopLineCountBefore,
Todd Fiala9666ba72016-09-21 20:13:14 +0000296 ePropertyStopShowColumn,
297 ePropertyStopShowColumnAnsiPrefix,
298 ePropertyStopShowColumnAnsiSuffix,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 ePropertyTerminalWidth,
300 ePropertyThreadFormat,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000301 ePropertyThreadStopFormat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 ePropertyUseExternalEditor,
303 ePropertyUseColor,
304 ePropertyAutoOneLineSummaries,
305 ePropertyAutoIndent,
306 ePropertyPrintDecls,
307 ePropertyTabSize,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000308 ePropertyEscapeNonPrintables,
309 ePropertyFrameFormatUnique,
Greg Clayton67cc0632012-08-22 17:17:09 +0000310};
311
Eugene Zelenkodf370552016-03-02 02:18:18 +0000312LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000313
Zachary Turner97206d52017-05-12 04:51:55 +0000314Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
315 VarSetOperationType op,
316 llvm::StringRef property_path,
317 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000318 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
319 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 TargetSP target_sp;
321 LoadScriptFromSymFile load_script_old_value;
322 if (is_load_script && exe_ctx->GetTargetSP()) {
323 target_sp = exe_ctx->GetTargetSP();
324 load_script_old_value =
325 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
326 }
Zachary Turner97206d52017-05-12 04:51:55 +0000327 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (error.Success()) {
329 // FIXME it would be nice to have "on-change" callbacks for properties
Zachary Turner31d97a52016-11-17 18:08:12 +0000330 if (property_path == g_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000331 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
333 new_prompt, GetUseColor());
334 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000335 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000337 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
338 auto prompt_change_event_sp = std::make_shared<Event>(
339 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Zachary Turner31d97a52016-11-17 18:08:12 +0000341 } else if (property_path == g_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 // use-color changed. Ping the prompt so it can reset the ansi terminal
343 // codes.
344 SetPrompt(GetPrompt());
345 } else if (is_load_script && target_sp &&
346 load_script_old_value == eLoadScriptFromSymFileWarn) {
347 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
348 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000349 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 StreamString feedback_stream;
351 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
352 StreamFileSP stream_sp(GetErrorFile());
353 if (stream_sp) {
354 for (auto error : errors) {
355 stream_sp->Printf("%s\n", error.AsCString());
356 }
357 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000358 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 }
360 }
361 }
362 } else if (is_escape_non_printables) {
363 DataVisualization::ForceUpdate();
364 }
365 }
366 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369bool Debugger::GetAutoConfirm() const {
370 const uint32_t idx = ePropertyAutoConfirm;
371 return m_collection_sp->GetPropertyAtIndexAsBoolean(
372 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000373}
374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
376 const uint32_t idx = ePropertyDisassemblyFormat;
377 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000378}
379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380const FormatEntity::Entry *Debugger::GetFrameFormat() const {
381 const uint32_t idx = ePropertyFrameFormat;
382 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000383}
384
Pavel Labath7f1c1212017-06-12 16:25:24 +0000385const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
386 const uint32_t idx = ePropertyFrameFormatUnique;
387 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
388}
389
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390bool Debugger::GetNotifyVoid() const {
391 const uint32_t idx = ePropertyNotiftVoid;
392 return m_collection_sp->GetPropertyAtIndexAsBoolean(
393 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000394}
395
Zachary Turner514d8cd2016-09-23 18:06:53 +0000396llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 const uint32_t idx = ePropertyPrompt;
398 return m_collection_sp->GetPropertyAtIndexAsString(
399 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000400}
401
Zachary Turner514d8cd2016-09-23 18:06:53 +0000402void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 const uint32_t idx = ePropertyPrompt;
404 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000405 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 std::string str =
407 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
408 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000409 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000411}
412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413const FormatEntity::Entry *Debugger::GetThreadFormat() const {
414 const uint32_t idx = ePropertyThreadFormat;
415 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000416}
417
Jim Ingham6a9767c2016-11-08 20:36:40 +0000418const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
419 const uint32_t idx = ePropertyThreadStopFormat;
420 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
421}
422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
424 const uint32_t idx = ePropertyScriptLanguage;
425 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
426 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000427}
428
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
430 const uint32_t idx = ePropertyScriptLanguage;
431 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
432 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000433}
434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435uint32_t Debugger::GetTerminalWidth() const {
436 const uint32_t idx = ePropertyTerminalWidth;
437 return m_collection_sp->GetPropertyAtIndexAsSInt64(
438 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000439}
440
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441bool Debugger::SetTerminalWidth(uint32_t term_width) {
442 const uint32_t idx = ePropertyTerminalWidth;
443 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000444}
445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446bool Debugger::GetUseExternalEditor() const {
447 const uint32_t idx = ePropertyUseExternalEditor;
448 return m_collection_sp->GetPropertyAtIndexAsBoolean(
449 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000450}
Greg Claytone372b982011-11-21 21:44:34 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452bool Debugger::SetUseExternalEditor(bool b) {
453 const uint32_t idx = ePropertyUseExternalEditor;
454 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000455}
Enrico Granata553fad52013-10-25 23:09:40 +0000456
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457bool Debugger::GetUseColor() const {
458 const uint32_t idx = ePropertyUseColor;
459 return m_collection_sp->GetPropertyAtIndexAsBoolean(
460 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000461}
462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463bool Debugger::SetUseColor(bool b) {
464 const uint32_t idx = ePropertyUseColor;
465 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
466 SetPrompt(GetPrompt());
467 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000468}
469
Todd Fiala9666ba72016-09-21 20:13:14 +0000470StopShowColumn Debugger::GetStopShowColumn() const {
471 const uint32_t idx = ePropertyStopShowColumn;
472 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
473 nullptr, idx, g_properties[idx].default_uint_value);
474}
475
476const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiPrefix() const {
477 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
478 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
479}
480
481const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiSuffix() const {
482 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
483 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
484}
485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486uint32_t Debugger::GetStopSourceLineCount(bool before) const {
487 const uint32_t idx =
488 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
489 return m_collection_sp->GetPropertyAtIndexAsSInt64(
490 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000491}
492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
494 const uint32_t idx = ePropertyStopDisassemblyDisplay;
495 return (Debugger::StopDisassemblyType)
496 m_collection_sp->GetPropertyAtIndexAsEnumeration(
497 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000498}
499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500uint32_t Debugger::GetDisassemblyLineCount() const {
501 const uint32_t idx = ePropertyStopDisassemblyCount;
502 return m_collection_sp->GetPropertyAtIndexAsSInt64(
503 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000504}
505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506bool Debugger::GetAutoOneLineSummaries() const {
507 const uint32_t idx = ePropertyAutoOneLineSummaries;
508 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000509}
510
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511bool Debugger::GetEscapeNonPrintables() const {
512 const uint32_t idx = ePropertyEscapeNonPrintables;
513 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
514}
515
516bool Debugger::GetAutoIndent() const {
517 const uint32_t idx = ePropertyAutoIndent;
518 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
519}
520
521bool Debugger::SetAutoIndent(bool b) {
522 const uint32_t idx = ePropertyAutoIndent;
523 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
524}
525
526bool Debugger::GetPrintDecls() const {
527 const uint32_t idx = ePropertyPrintDecls;
528 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
529}
530
531bool Debugger::SetPrintDecls(bool b) {
532 const uint32_t idx = ePropertyPrintDecls;
533 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
534}
535
536uint32_t Debugger::GetTabSize() const {
537 const uint32_t idx = ePropertyTabSize;
538 return m_collection_sp->GetPropertyAtIndexAsUInt64(
539 nullptr, idx, g_properties[idx].default_uint_value);
540}
541
542bool Debugger::SetTabSize(uint32_t tab_size) {
543 const uint32_t idx = ePropertyTabSize;
544 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000545}
546
Greg Clayton1b654882010-09-19 02:33:57 +0000547#pragma mark Debugger
548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549// const DebuggerPropertiesSP &
550// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000551//{
552// return m_properties_sp;
553//}
554//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
557 assert(g_debugger_list_ptr == nullptr &&
558 "Debugger::Initialize called more than once!");
559 g_debugger_list_mutex_ptr = new std::recursive_mutex();
560 g_debugger_list_ptr = new DebuggerList();
561 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562}
563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564void Debugger::Terminate() {
565 assert(g_debugger_list_ptr &&
566 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
569 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000570 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
572 for (const auto &debugger : *g_debugger_list_ptr)
573 debugger->Clear();
574 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000575 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000577}
578
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000580
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000582
Zachary Turner97206d52017-05-12 04:51:55 +0000583bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 if (g_load_plugin_callback) {
585 llvm::sys::DynamicLibrary dynlib =
586 g_load_plugin_callback(shared_from_this(), spec, error);
587 if (dynlib.isValid()) {
588 m_loaded_plugins.push_back(dynlib);
589 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000590 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 } else {
592 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
593 // and if the public API layer isn't available (code is linking against
594 // all of the internal LLDB static libraries), then we can't load plugins
595 error.SetErrorString("Public API layer is not available");
596 }
597 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000598}
599
600static FileSpec::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000601LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 const FileSpec &file_spec) {
Zachary Turner97206d52017-05-12 04:51:55 +0000603 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 static ConstString g_dylibext("dylib");
606 static ConstString g_solibext("so");
607
608 if (!baton)
609 return FileSpec::eEnumerateDirectoryResultQuit;
610
611 Debugger *debugger = (Debugger *)baton;
612
Zachary Turner7d86ee52017-03-08 17:56:08 +0000613 namespace fs = llvm::sys::fs;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 // If we have a regular file, a symbolic link or unknown file type, try
615 // and process the file. We must handle unknown as sometimes the directory
616 // enumeration might be enumerating a file system that doesn't have correct
617 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000618 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
619 ft == fs::file_type::type_unknown) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 FileSpec plugin_file_spec(file_spec);
621 plugin_file_spec.ResolvePath();
622
623 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
624 plugin_file_spec.GetFileNameExtension() != g_solibext) {
625 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000626 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627
Zachary Turner97206d52017-05-12 04:51:55 +0000628 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
630
Enrico Granata21dfcd92012-09-28 23:57:51 +0000631 return FileSpec::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000632 } else if (ft == fs::file_type::directory_file ||
633 ft == fs::file_type::symlink_file ||
634 ft == fs::file_type::type_unknown) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 // Try and recurse into anything that a directory or symbolic link.
636 // We must also do this for unknown as sometimes the directory enumeration
637 // might be enumerating a file system that doesn't have correct file type
638 // information.
639 return FileSpec::eEnumerateDirectoryResultEnter;
640 }
641
642 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000643}
644
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645void Debugger::InstanceInitialize() {
646 FileSpec dir_spec;
647 const bool find_directories = true;
648 const bool find_files = true;
649 const bool find_other = true;
650 char dir_path[PATH_MAX];
651 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec)) {
652 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
653 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
654 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000655 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec)) {
659 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
660 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
661 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 }
664
665 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000666}
667
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
669 void *baton) {
670 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
671 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
672 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
673 g_debugger_list_ptr->push_back(debugger_sp);
674 }
675 debugger_sp->InstanceInitialize();
676 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000677}
678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679void Debugger::Destroy(DebuggerSP &debugger_sp) {
680 if (!debugger_sp)
681 return;
682
683 debugger_sp->Clear();
684
685 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
686 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
687 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
688 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
689 if ((*pos).get() == debugger_sp.get()) {
690 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000691 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000693 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000695}
696
Greg Clayton4d122c42011-09-17 08:33:22 +0000697DebuggerSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
699 DebuggerSP debugger_sp;
700 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
701 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
702 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
703 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
704 if ((*pos)->m_instance_name == instance_name) {
705 debugger_sp = *pos;
706 break;
707 }
Greg Clayton6920b522012-08-22 18:39:03 +0000708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 }
710 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000711}
Greg Clayton66111032010-06-23 01:19:29 +0000712
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
714 TargetSP target_sp;
715 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
716 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
717 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
718 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
719 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
720 if (target_sp)
721 break;
Greg Clayton66111032010-06-23 01:19:29 +0000722 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 }
724 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000725}
726
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727TargetSP Debugger::FindTargetWithProcess(Process *process) {
728 TargetSP target_sp;
729 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
730 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
731 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
732 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
733 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
734 if (target_sp)
735 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000736 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 }
738 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000739}
740
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
742 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000743 Properties(std::make_shared<OptionValueProperties>()),
744 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
745 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
746 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
748 m_terminal_state(), m_target_list(*this), m_platform_list(),
749 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
750 m_source_manager_ap(), m_source_file_cache(),
Zachary Turner2f3df612017-04-06 21:28:29 +0000751 m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>(
752 *this, eScriptLanguageDefault, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
754 m_event_handler_thread(), m_io_handler_thread(),
755 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
756 m_forward_listener_sp(), m_clear_once() {
757 char instance_cstr[256];
758 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
759 m_instance_name.SetCString(instance_cstr);
760 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000761 m_log_callback_stream_sp =
762 std::make_shared<StreamCallback>(log_callback, baton);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 m_command_interpreter_ap->Initialize();
764 // Always add our default platform to the platform list
765 PlatformSP default_platform_sp(Platform::GetHostPlatform());
766 assert(default_platform_sp);
767 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000768
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 m_collection_sp->Initialize(g_properties);
770 m_collection_sp->AppendProperty(
771 ConstString("target"),
772 ConstString("Settings specify to debugging targets."), true,
773 Target::GetGlobalProperties()->GetValueProperties());
774 m_collection_sp->AppendProperty(
775 ConstString("platform"), ConstString("Platform settings."), true,
776 Platform::GetGlobalPlatformProperties()->GetValueProperties());
777 if (m_command_interpreter_ap) {
778 m_collection_sp->AppendProperty(
779 ConstString("interpreter"),
780 ConstString("Settings specify to the debugger's command interpreter."),
781 true, m_command_interpreter_ap->GetValueProperties());
782 }
783 OptionValueSInt64 *term_width =
784 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
785 nullptr, ePropertyTerminalWidth);
786 term_width->SetMinimumValue(10);
787 term_width->SetMaximumValue(1024);
788
789 // Turn off use-color if this is a dumb terminal.
790 const char *term = getenv("TERM");
791 if (term && !strcmp(term, "dumb"))
792 SetUseColor(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793}
794
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797void Debugger::Clear() {
798 //----------------------------------------------------------------------
799 // Make sure we call this function only once. With the C++ global
800 // destructor chain having a list of debuggers and with code that can be
801 // running on other threads, we need to ensure this doesn't happen
802 // multiple times.
803 //
804 // The following functions call Debugger::Clear():
805 // Debugger::~Debugger();
806 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
807 // static void Debugger::Terminate();
808 //----------------------------------------------------------------------
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000809 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000810 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 StopIOHandlerThread();
812 StopEventHandlerThread();
813 m_listener_sp->Clear();
814 int num_targets = m_target_list.GetNumTargets();
815 for (int i = 0; i < num_targets; i++) {
816 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
817 if (target_sp) {
818 ProcessSP process_sp(target_sp->GetProcessSP());
819 if (process_sp)
820 process_sp->Finalize();
821 target_sp->Destroy();
822 }
Greg Clayton577508d2014-06-20 00:23:57 +0000823 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 m_broadcaster_manager_sp->Clear();
825
826 // Close the input file _before_ we close the input read communications
827 // class
828 // as it does NOT own the input file, our m_input_file does.
829 m_terminal_state.Clear();
830 if (m_input_file_sp)
831 m_input_file_sp->GetFile().Close();
832
833 m_command_interpreter_ap->Clear();
834 });
Greg Clayton44d93782014-01-27 23:43:24 +0000835}
836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837bool Debugger::GetCloseInputOnEOF() const {
838 // return m_input_comm.GetCloseOnEOF();
839 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000840}
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842void Debugger::SetCloseInputOnEOF(bool b) {
843 // m_input_comm.SetCloseOnEOF(b);
844}
845
846bool Debugger::GetAsyncExecution() {
847 return !m_command_interpreter_ap->GetSynchronous();
848}
849
850void Debugger::SetAsyncExecution(bool async_execution) {
851 m_command_interpreter_ap->SetSynchronous(!async_execution);
852}
853
854void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
855 if (m_input_file_sp)
856 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
857 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000858 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859
860 File &in_file = m_input_file_sp->GetFile();
861 if (!in_file.IsValid())
862 in_file.SetStream(stdin, true);
863
864 // Save away the terminal state if that is relevant, so that we can restore it
865 // in RestoreInputState.
866 SaveInputTerminalState();
867}
868
869void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
870 if (m_output_file_sp)
871 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
872 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000873 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874
875 File &out_file = m_output_file_sp->GetFile();
876 if (!out_file.IsValid())
877 out_file.SetStream(stdout, false);
878
879 // do not create the ScriptInterpreter just for setting the output file handle
880 // as the constructor will know how to do the right thing on its own
881 const bool can_create = false;
882 ScriptInterpreter *script_interpreter =
883 GetCommandInterpreter().GetScriptInterpreter(can_create);
884 if (script_interpreter)
885 script_interpreter->ResetOutputFileHandle(fh);
886}
887
888void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
889 if (m_error_file_sp)
890 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
891 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000892 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893
894 File &err_file = m_error_file_sp->GetFile();
895 if (!err_file.IsValid())
896 err_file.SetStream(stderr, false);
897}
898
899void Debugger::SaveInputTerminalState() {
900 if (m_input_file_sp) {
901 File &in_file = m_input_file_sp->GetFile();
902 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
903 m_terminal_state.Save(in_file.GetDescriptor(), true);
904 }
905}
906
907void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
908
909ExecutionContext Debugger::GetSelectedExecutionContext() {
910 ExecutionContext exe_ctx;
911 TargetSP target_sp(GetSelectedTarget());
912 exe_ctx.SetTargetSP(target_sp);
913
914 if (target_sp) {
915 ProcessSP process_sp(target_sp->GetProcessSP());
916 exe_ctx.SetProcessSP(process_sp);
917 if (process_sp && !process_sp->IsRunning()) {
918 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
919 if (thread_sp) {
920 exe_ctx.SetThreadSP(thread_sp);
921 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
922 if (exe_ctx.GetFramePtr() == nullptr)
923 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
924 }
925 }
926 }
927 return exe_ctx;
928}
929
930void Debugger::DispatchInputInterrupt() {
931 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
932 IOHandlerSP reader_sp(m_input_reader_stack.Top());
933 if (reader_sp)
934 reader_sp->Interrupt();
935}
936
937void Debugger::DispatchInputEndOfFile() {
938 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
939 IOHandlerSP reader_sp(m_input_reader_stack.Top());
940 if (reader_sp)
941 reader_sp->GotEOF();
942}
943
944void Debugger::ClearIOHandlers() {
945 // The bottom input reader should be the main debugger input reader. We do
946 // not want to close that one here.
947 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
948 while (m_input_reader_stack.GetSize() > 1) {
949 IOHandlerSP reader_sp(m_input_reader_stack.Top());
950 if (reader_sp)
951 PopIOHandler(reader_sp);
952 }
953}
954
955void Debugger::ExecuteIOHandlers() {
956 while (true) {
957 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000960
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 // Remove all input readers that are done from the top of the stack
964 while (true) {
965 IOHandlerSP 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 ClearIOHandlers();
973}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000974
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
976 return m_input_reader_stack.IsTop(reader_sp);
977}
Greg Clayton44d93782014-01-27 23:43:24 +0000978
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
980 IOHandler::Type second_top_type) {
981 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
982}
983
984void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
985 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
986 m_input_reader_stack.PrintAsync(stream.get(), s, len);
987}
988
989ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
990 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
991}
992
993const char *Debugger::GetIOHandlerCommandPrefix() {
994 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
995}
996
997const char *Debugger::GetIOHandlerHelpPrologue() {
998 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
999}
1000
1001void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1002 PushIOHandler(reader_sp);
1003
1004 IOHandlerSP top_reader_sp = reader_sp;
1005 while (top_reader_sp) {
1006 top_reader_sp->Run();
1007
1008 if (top_reader_sp.get() == reader_sp.get()) {
1009 if (PopIOHandler(reader_sp))
1010 break;
1011 }
1012
1013 while (true) {
1014 top_reader_sp = m_input_reader_stack.Top();
1015 if (top_reader_sp && top_reader_sp->GetIsDone())
1016 PopIOHandler(top_reader_sp);
1017 else
1018 break;
1019 }
1020 }
1021}
1022
1023void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1024 StreamFileSP &out,
1025 StreamFileSP &err) {
1026 // Before an IOHandler runs, it must have in/out/err streams.
1027 // This function is called when one ore more of the streams
1028 // are nullptr. We use the top input reader's in/out/err streams,
1029 // or fall back to the debugger file handles, or we fall back
1030 // onto stdin/stdout/stderr as a last resort.
1031
1032 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1033 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1034 // If no STDIN has been set, then set it appropriately
1035 if (!in) {
1036 if (top_reader_sp)
1037 in = top_reader_sp->GetInputStreamFile();
1038 else
1039 in = GetInputFile();
1040
1041 // If there is nothing, use stdin
1042 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001043 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 }
1045 // If no STDOUT has been set, then set it appropriately
1046 if (!out) {
1047 if (top_reader_sp)
1048 out = top_reader_sp->GetOutputStreamFile();
1049 else
1050 out = GetOutputFile();
1051
1052 // If there is nothing, use stdout
1053 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001054 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 }
1056 // If no STDERR has been set, then set it appropriately
1057 if (!err) {
1058 if (top_reader_sp)
1059 err = top_reader_sp->GetErrorStreamFile();
1060 else
1061 err = GetErrorFile();
1062
1063 // If there is nothing, use stderr
1064 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001065 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 }
1067}
1068
1069void Debugger::PushIOHandler(const IOHandlerSP &reader_sp) {
1070 if (!reader_sp)
1071 return;
1072
1073 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1074
1075 // Get the current top input reader...
1076 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1077
1078 // Don't push the same IO handler twice...
1079 if (reader_sp == top_reader_sp)
1080 return;
1081
1082 // Push our new input reader
1083 m_input_reader_stack.Push(reader_sp);
1084 reader_sp->Activate();
1085
1086 // Interrupt the top input reader to it will exit its Run() function
1087 // and let this new input reader take over
1088 if (top_reader_sp) {
1089 top_reader_sp->Deactivate();
1090 top_reader_sp->Cancel();
1091 }
1092}
1093
1094bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1095 if (!pop_reader_sp)
1096 return false;
1097
1098 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1099
1100 // The reader on the stop of the stack is done, so let the next
1101 // read on the stack refresh its prompt and if there is one...
1102 if (m_input_reader_stack.IsEmpty())
1103 return false;
1104
1105 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1106
1107 if (pop_reader_sp != reader_sp)
1108 return false;
1109
1110 reader_sp->Deactivate();
1111 reader_sp->Cancel();
1112 m_input_reader_stack.Pop();
1113
1114 reader_sp = m_input_reader_stack.Top();
1115 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001116 reader_sp->Activate();
1117
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 return true;
1119}
1120
1121StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001122 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123}
1124
1125StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001126 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127}
1128
1129size_t Debugger::GetNumDebuggers() {
1130 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1131 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1132 return g_debugger_list_ptr->size();
1133 }
1134 return 0;
1135}
1136
1137lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1138 DebuggerSP debugger_sp;
1139
1140 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1141 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1142 if (index < g_debugger_list_ptr->size())
1143 debugger_sp = g_debugger_list_ptr->at(index);
1144 }
1145
1146 return debugger_sp;
1147}
1148
1149DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1150 DebuggerSP debugger_sp;
1151
1152 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1153 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1154 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1155 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1156 if ((*pos)->GetID() == id) {
1157 debugger_sp = *pos;
1158 break;
1159 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001160 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 }
1162 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001163}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001164
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001165#if 0
Greg Clayton1b654882010-09-19 02:33:57 +00001166static void
Jason Molendab57e4a12013-11-04 09:33:30 +00001167TestPromptFormats (StackFrame *frame)
Greg Clayton1b654882010-09-19 02:33:57 +00001168{
Eugene Zelenkodf370552016-03-02 02:18:18 +00001169 if (frame == nullptr)
Greg Clayton1b654882010-09-19 02:33:57 +00001170 return;
1171
1172 StreamString s;
1173 const char *prompt_format =
1174 "{addr = '${addr}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001175 "{addr-file-or-load = '${addr-file-or-load}'\n}"
1176 "{current-pc-arrow = '${current-pc-arrow}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001177 "{process.id = '${process.id}'\n}"
1178 "{process.name = '${process.name}'\n}"
1179 "{process.file.basename = '${process.file.basename}'\n}"
1180 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1181 "{thread.id = '${thread.id}'\n}"
1182 "{thread.index = '${thread.index}'\n}"
1183 "{thread.name = '${thread.name}'\n}"
1184 "{thread.queue = '${thread.queue}'\n}"
1185 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1186 "{target.arch = '${target.arch}'\n}"
1187 "{module.file.basename = '${module.file.basename}'\n}"
1188 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1189 "{file.basename = '${file.basename}'\n}"
1190 "{file.fullpath = '${file.fullpath}'\n}"
1191 "{frame.index = '${frame.index}'\n}"
1192 "{frame.pc = '${frame.pc}'\n}"
1193 "{frame.sp = '${frame.sp}'\n}"
1194 "{frame.fp = '${frame.fp}'\n}"
1195 "{frame.flags = '${frame.flags}'\n}"
1196 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1197 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1198 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1199 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1200 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1201 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1202 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1203 "{function.id = '${function.id}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001204 "{function.changed = '${function.changed}'\n}"
1205 "{function.initial-function = '${function.initial-function}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001206 "{function.name = '${function.name}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001207 "{function.name-without-args = '${function.name-without-args}'\n}"
Greg Claytonccbc08e2012-01-14 17:04:19 +00001208 "{function.name-with-args = '${function.name-with-args}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001209 "{function.addr-offset = '${function.addr-offset}'\n}"
Jason Molendaaff1b352014-10-10 23:07:36 +00001210 "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001211 "{function.line-offset = '${function.line-offset}'\n}"
1212 "{function.pc-offset = '${function.pc-offset}'\n}"
1213 "{line.file.basename = '${line.file.basename}'\n}"
1214 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1215 "{line.number = '${line.number}'\n}"
1216 "{line.start-addr = '${line.start-addr}'\n}"
1217 "{line.end-addr = '${line.end-addr}'\n}"
1218;
1219
1220 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1221 ExecutionContext exe_ctx;
Greg Clayton0603aa92010-10-04 01:05:56 +00001222 frame->CalculateExecutionContext(exe_ctx);
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001223 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
Greg Clayton1b654882010-09-19 02:33:57 +00001224 {
1225 printf("%s\n", s.GetData());
1226 }
1227 else
1228 {
Greg Clayton1b654882010-09-19 02:33:57 +00001229 printf ("what we got: %s\n", s.GetData());
1230 }
1231}
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001232#endif
Greg Clayton1b654882010-09-19 02:33:57 +00001233
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1235 const SymbolContext *sc,
1236 const SymbolContext *prev_sc,
1237 const ExecutionContext *exe_ctx,
1238 const Address *addr, Stream &s) {
1239 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001240
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 if (format == nullptr) {
1242 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1243 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1244 if (format == nullptr) {
1245 FormatEntity::Parse("${addr}: ", format_entry);
1246 format = &format_entry;
1247 }
1248 }
1249 bool function_changed = false;
1250 bool initial_function = false;
1251 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1252 if (sc && (sc->function || sc->symbol)) {
1253 if (prev_sc->symbol && sc->symbol) {
1254 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1255 prev_sc->symbol->GetType())) {
1256 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 } else if (prev_sc->function && sc->function) {
1259 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1260 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001261 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001263 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 }
1265 // The first context on a list of instructions will have a prev_sc that
1266 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1267 // would return false. But we do get a prev_sc pointer.
1268 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1269 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1270 initial_function = true;
1271 }
1272 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1273 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001274}
1275
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1277 void *baton) {
1278 // For simplicity's sake, I am not going to deal with how to close down any
1279 // open logging streams, I just redirect everything from here on out to the
1280 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001281 m_log_callback_stream_sp =
1282 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001283}
1284
Pavel Labath5e336902017-03-01 10:08:40 +00001285bool Debugger::EnableLog(llvm::StringRef channel,
1286 llvm::ArrayRef<const char *> categories,
1287 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001288 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001289 const bool should_close = true;
1290 const bool unbuffered = true;
1291
1292 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 if (m_log_callback_stream_sp) {
1294 log_stream_sp = m_log_callback_stream_sp;
1295 // For now when using the callback mode you always get thread & timestamp.
1296 log_options |=
1297 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001298 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001299 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1300 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001302 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 if (pos != m_log_streams.end())
1304 log_stream_sp = pos->second.lock();
1305 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001306 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1307 if (log_options & LLDB_LOG_OPTION_APPEND)
1308 flags |= llvm::sys::fs::F_Append;
1309 int FD;
1310 if (std::error_code ec =
1311 llvm::sys::fs::openFileForWrite(log_file, FD, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001312 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001313 return false;
1314 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001315 log_stream_sp =
1316 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001318 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319 }
1320 assert(log_stream_sp);
1321
1322 if (log_options == 0)
1323 log_options =
1324 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1325
1326 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1327 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001328}
1329
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330SourceManager &Debugger::GetSourceManager() {
1331 if (!m_source_manager_ap)
Zachary Turner2f3df612017-04-06 21:28:29 +00001332 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 return *m_source_manager_ap;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001334}
1335
Greg Clayton44d93782014-01-27 23:43:24 +00001336// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1338 using namespace lldb;
1339 const uint32_t event_type =
1340 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1341 event_sp);
1342
1343 // if (event_type & eBreakpointEventTypeAdded
1344 // || event_type & eBreakpointEventTypeRemoved
1345 // || event_type & eBreakpointEventTypeEnabled
1346 // || event_type & eBreakpointEventTypeDisabled
1347 // || event_type & eBreakpointEventTypeCommandChanged
1348 // || event_type & eBreakpointEventTypeConditionChanged
1349 // || event_type & eBreakpointEventTypeIgnoreChanged
1350 // || event_type & eBreakpointEventTypeLocationsResolved)
1351 // {
1352 // // Don't do anything about these events, since the breakpoint
1353 // commands already echo these actions.
1354 // }
1355 //
1356 if (event_type & eBreakpointEventTypeLocationsAdded) {
1357 uint32_t num_new_locations =
1358 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1359 event_sp);
1360 if (num_new_locations > 0) {
1361 BreakpointSP breakpoint =
1362 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1363 StreamSP output_sp(GetAsyncOutputStream());
1364 if (output_sp) {
1365 output_sp->Printf("%d location%s added to breakpoint %d\n",
1366 num_new_locations, num_new_locations == 1 ? "" : "s",
1367 breakpoint->GetID());
1368 output_sp->Flush();
1369 }
Greg Clayton44d93782014-01-27 23:43:24 +00001370 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 }
1372 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1373 // {
1374 // // These locations just get disabled, not sure it is worth spamming
1375 // folks about this on the command line.
1376 // }
1377 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1378 // {
1379 // // This might be an interesting thing to note, but I'm going to
1380 // leave it quiet for now, it just looked noisy.
1381 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001382}
1383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1385 size_t total_bytes = 0;
1386 if (stream == nullptr)
1387 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001388
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389 if (stream) {
1390 // The process has stuff waiting for stdout; get it and write it out to the
1391 // appropriate place.
1392 if (process == nullptr) {
1393 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1394 if (target_sp)
1395 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001396 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001398 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 size_t len;
1400 char stdio_buffer[1024];
1401 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1402 error)) > 0) {
1403 stream->Write(stdio_buffer, len);
1404 total_bytes += len;
1405 }
1406 }
1407 stream->Flush();
1408 }
1409 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001410}
1411
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1413 size_t total_bytes = 0;
1414 if (stream == nullptr)
1415 stream = GetOutputFile().get();
1416
1417 if (stream) {
1418 // The process has stuff waiting for stderr; get it and write it out to the
1419 // appropriate place.
1420 if (process == nullptr) {
1421 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1422 if (target_sp)
1423 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001424 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001426 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 size_t len;
1428 char stdio_buffer[1024];
1429 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1430 error)) > 0) {
1431 stream->Write(stdio_buffer, len);
1432 total_bytes += len;
1433 }
1434 }
1435 stream->Flush();
1436 }
1437 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001438}
1439
1440// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1442 using namespace lldb;
1443 const uint32_t event_type = event_sp->GetType();
1444 ProcessSP process_sp =
1445 (event_type == Process::eBroadcastBitStructuredData)
1446 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1447 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 StreamSP output_stream_sp = GetAsyncOutputStream();
1450 StreamSP error_stream_sp = GetAsyncErrorStream();
1451 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001452
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 if (!gui_enabled) {
1454 bool pop_process_io_handler = false;
1455 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001456
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 bool state_is_stopped = false;
1458 const bool got_state_changed =
1459 (event_type & Process::eBroadcastBitStateChanged) != 0;
1460 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1461 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1462 const bool got_structured_data =
1463 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001464
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 if (got_state_changed) {
1466 StateType event_state =
1467 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1468 state_is_stopped = StateIsStoppedState(event_state, false);
1469 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001470
Kate Stoneb9c1b512016-09-06 20:57:50 +00001471 // Display running state changes first before any STDIO
1472 if (got_state_changed && !state_is_stopped) {
1473 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1474 pop_process_io_handler);
1475 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001476
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 // Now display and STDOUT
1478 if (got_stdout || got_state_changed) {
1479 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1480 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001481
Kate Stoneb9c1b512016-09-06 20:57:50 +00001482 // Now display and STDERR
1483 if (got_stderr || got_state_changed) {
1484 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1485 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001486
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 // Give structured data events an opportunity to display.
1488 if (got_structured_data) {
1489 StructuredDataPluginSP plugin_sp =
1490 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1491 if (plugin_sp) {
1492 auto structured_data_sp =
1493 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1494 if (output_stream_sp) {
1495 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001496 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497 plugin_sp->GetDescription(structured_data_sp, content_stream);
1498 if (error.Success()) {
1499 if (!content_stream.GetString().empty()) {
1500 // Add newline.
1501 content_stream.PutChar('\n');
1502 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001503
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001505 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001506 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001507 } else {
1508 error_stream_sp->Printf("Failed to print structured "
1509 "data with plugin %s: %s",
1510 plugin_sp->GetPluginName().AsCString(),
1511 error.AsCString());
1512 }
Todd Fiala75930012016-08-19 04:21:48 +00001513 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001514 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001515 }
Greg Clayton44d93782014-01-27 23:43:24 +00001516
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517 // Now display any stopped state changes after any STDIO
1518 if (got_state_changed && state_is_stopped) {
1519 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1520 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001521 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001522
1523 output_stream_sp->Flush();
1524 error_stream_sp->Flush();
1525
1526 if (pop_process_io_handler)
1527 process_sp->PopProcessIOHandler();
1528 }
Greg Clayton44d93782014-01-27 23:43:24 +00001529}
1530
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1532 // At present the only thread event we handle is the Frame Changed event,
1533 // and all we do for that is just reprint the thread status for that thread.
1534 using namespace lldb;
1535 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001536 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537 if (event_type == Thread::eBroadcastBitStackChanged ||
1538 event_type == Thread::eBroadcastBitThreadSelected) {
1539 ThreadSP thread_sp(
1540 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1541 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001542 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543 }
1544 }
Greg Clayton44d93782014-01-27 23:43:24 +00001545}
1546
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1548
1549void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1550 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001551}
1552
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1554 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001555}
1556
Kate Stoneb9c1b512016-09-06 20:57:50 +00001557void Debugger::DefaultEventHandler() {
1558 ListenerSP listener_sp(GetListener());
1559 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1560 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1561 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1562 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1563 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001564
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565 BroadcastEventSpec process_event_spec(
1566 broadcaster_class_process,
1567 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1568 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001569
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1571 Thread::eBroadcastBitStackChanged |
1572 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001573
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1575 target_event_spec);
1576 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1577 process_event_spec);
1578 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1579 thread_event_spec);
1580 listener_sp->StartListeningForEvents(
1581 m_command_interpreter_ap.get(),
1582 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1583 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1584 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001585
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586 // Let the thread that spawned us know that we have started up and
1587 // that we are now listening to all required events so no events get missed
1588 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001589
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 bool done = false;
1591 while (!done) {
1592 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001593 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001594 if (event_sp) {
1595 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1596 if (broadcaster) {
1597 uint32_t event_type = event_sp->GetType();
1598 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1599 if (broadcaster_class == broadcaster_class_process) {
1600 HandleProcessEvent(event_sp);
1601 } else if (broadcaster_class == broadcaster_class_target) {
1602 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1603 event_sp.get())) {
1604 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001605 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606 } else if (broadcaster_class == broadcaster_class_thread) {
1607 HandleThreadEvent(event_sp);
1608 } else if (broadcaster == m_command_interpreter_ap.get()) {
1609 if (event_type &
1610 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1611 done = true;
1612 } else if (event_type &
1613 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1614 const char *data = reinterpret_cast<const char *>(
1615 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1616 if (data && data[0]) {
1617 StreamSP error_sp(GetAsyncErrorStream());
1618 if (error_sp) {
1619 error_sp->PutCString(data);
1620 error_sp->Flush();
1621 }
1622 }
1623 } else if (event_type & CommandInterpreter::
1624 eBroadcastBitAsynchronousOutputData) {
1625 const char *data = reinterpret_cast<const char *>(
1626 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1627 if (data && data[0]) {
1628 StreamSP output_sp(GetAsyncOutputStream());
1629 if (output_sp) {
1630 output_sp->PutCString(data);
1631 output_sp->Flush();
1632 }
1633 }
1634 }
1635 }
Greg Clayton44d93782014-01-27 23:43:24 +00001636 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001637
1638 if (m_forward_listener_sp)
1639 m_forward_listener_sp->AddEvent(event_sp);
1640 }
Greg Clayton44d93782014-01-27 23:43:24 +00001641 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 }
Greg Clayton44d93782014-01-27 23:43:24 +00001643}
1644
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1646 ((Debugger *)arg)->DefaultEventHandler();
1647 return NULL;
Greg Clayton44d93782014-01-27 23:43:24 +00001648}
1649
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650bool Debugger::StartEventHandlerThread() {
1651 if (!m_event_handler_thread.IsJoinable()) {
1652 // We must synchronize with the DefaultEventHandler() thread to ensure
1653 // it is up and running and listening to events before we return from
1654 // this function. We do this by listening to events for the
1655 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1656 ListenerSP listener_sp(
1657 Listener::MakeListener("lldb.debugger.event-handler"));
1658 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1659 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661 // Use larger 8MB stack for this thread
1662 m_event_handler_thread = ThreadLauncher::LaunchThread(
1663 "lldb.debugger.event-handler", EventHandlerThread, this, nullptr,
1664 g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001665
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 // Make sure DefaultEventHandler() is running and listening to events before
1667 // we return
1668 // from this function. We are only listening for events of type
1669 // eBroadcastBitEventThreadIsListening so we don't need to check the event,
1670 // we just need
1671 // to wait an infinite amount of time for it (nullptr timeout as the first
1672 // parameter)
1673 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001674 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675 }
1676 return m_event_handler_thread.IsJoinable();
1677}
1678
1679void Debugger::StopEventHandlerThread() {
1680 if (m_event_handler_thread.IsJoinable()) {
1681 GetCommandInterpreter().BroadcastEvent(
1682 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1683 m_event_handler_thread.Join(nullptr);
1684 }
1685}
1686
1687lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1688 Debugger *debugger = (Debugger *)arg;
1689 debugger->ExecuteIOHandlers();
1690 debugger->StopEventHandlerThread();
1691 return NULL;
1692}
1693
1694bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1695
1696bool Debugger::StartIOHandlerThread() {
1697 if (!m_io_handler_thread.IsJoinable())
1698 m_io_handler_thread = ThreadLauncher::LaunchThread(
1699 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1700 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1701 return m_io_handler_thread.IsJoinable();
1702}
1703
1704void Debugger::StopIOHandlerThread() {
1705 if (m_io_handler_thread.IsJoinable()) {
1706 if (m_input_file_sp)
1707 m_input_file_sp->GetFile().Close();
1708 m_io_handler_thread.Join(nullptr);
1709 }
1710}
1711
1712void Debugger::JoinIOHandlerThread() {
1713 if (HasIOHandlerThread()) {
1714 thread_result_t result;
1715 m_io_handler_thread.Join(&result);
1716 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1717 }
1718}
1719
1720Target *Debugger::GetDummyTarget() {
1721 return m_target_list.GetDummyTarget(*this).get();
1722}
1723
1724Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1725 Target *target = nullptr;
1726 if (!prefer_dummy) {
1727 target = m_target_list.GetSelectedTarget().get();
1728 if (target)
1729 return target;
1730 }
1731
1732 return GetDummyTarget();
1733}
1734
Zachary Turner97206d52017-05-12 04:51:55 +00001735Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1736 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 FileSpec repl_executable;
1738
1739 if (language == eLanguageTypeUnknown) {
1740 std::set<LanguageType> repl_languages;
1741
1742 Language::GetLanguagesSupportingREPLs(repl_languages);
1743
1744 if (repl_languages.size() == 1) {
1745 language = *repl_languages.begin();
1746 } else if (repl_languages.empty()) {
1747 err.SetErrorStringWithFormat(
1748 "LLDB isn't configured with REPL support for any languages.");
1749 return err;
1750 } else {
1751 err.SetErrorStringWithFormat(
1752 "Multiple possible REPL languages. Please specify a language.");
1753 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001754 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 }
Greg Clayton44d93782014-01-27 23:43:24 +00001756
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757 Target *const target =
1758 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001759
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001761
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001763 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764 }
1765
1766 if (!repl_sp) {
1767 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1768 Language::GetNameForLanguageType(language));
1769 return err;
1770 }
1771
1772 repl_sp->SetCompilerOptions(repl_options);
1773 repl_sp->RunLoop();
1774
1775 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001776}