blob: 972d0bc0a6d76b821428b4930bfbfc45eef3eb58 [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
Adrian Prantl235354be2018-03-02 22:42:44 +000017#include "lldb/Core/ModuleList.h" // for Mangled
Greg Claytone8cd0c92012-10-19 18:02:49 +000018#include "lldb/Core/PluginManager.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/State.h"
Jim Ingham5b52f0c2011-06-02 23:58:26 +000020#include "lldb/Core/StreamAsynchronousIO.h"
Greg Clayton44d93782014-01-27 23:43:24 +000021#include "lldb/Core/StreamFile.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000022#include "lldb/DataFormatters/DataVisualization.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000023#include "lldb/Expression/REPL.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000024#include "lldb/Host/File.h" // for File, File::kInv...
Zachary Turner42ff0ad2014-08-21 17:29:12 +000025#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000026#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000027#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000029#include "lldb/Interpreter/OptionValue.h" // for OptionValue, Opt...
Zachary Turner633a29c2015-03-04 01:58:01 +000030#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000031#include "lldb/Interpreter/OptionValueSInt64.h"
32#include "lldb/Interpreter/OptionValueString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000033#include "lldb/Interpreter/Property.h" // for PropertyDefinition
34#include "lldb/Interpreter/ScriptInterpreter.h" // for ScriptInterpreter
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Symbol/Function.h"
36#include "lldb/Symbol/Symbol.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000037#include "lldb/Symbol/SymbolContext.h" // for SymbolContext
Sean Callanan3e7e9152015-10-20 00:23:46 +000038#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Target/Process.h"
Todd Fiala75930012016-08-19 04:21:48 +000040#include "lldb/Target/StructuredDataPlugin.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000041#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000042#include "lldb/Target/TargetList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/Thread.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000044#include "lldb/Target/ThreadList.h" // for ThreadList
Greg Clayton5a314712011-10-14 07:41:33 +000045#include "lldb/Utility/AnsiTerminal.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000046#include "lldb/Utility/Log.h" // for LLDB_LOG_OPTION_...
47#include "lldb/Utility/Stream.h" // for Stream
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000048#include "lldb/Utility/StreamCallback.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000049#include "lldb/Utility/StreamString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000050
Nico Weberb1cb0b792018-04-10 13:33:45 +000051#if defined(_WIN32)
Zachary Turner2f3df612017-04-06 21:28:29 +000052#include "lldb/Host/windows/PosixApi.h" // for PATH_MAX
53#endif
54
55#include "llvm/ADT/None.h" // for None
56#include "llvm/ADT/STLExtras.h" // for make_unique
57#include "llvm/ADT/StringRef.h"
58#include "llvm/ADT/iterator.h" // for iterator_facade_...
59#include "llvm/Support/DynamicLibrary.h"
60#include "llvm/Support/FileSystem.h"
61#include "llvm/Support/Threading.h"
62#include "llvm/Support/raw_ostream.h" // for raw_fd_ostream
63
64#include <list> // for list
65#include <memory> // for make_shared
66#include <mutex>
67#include <set> // for set
68#include <stdio.h> // for size_t, NULL
69#include <stdlib.h> // for getenv
70#include <string.h> // for strcmp
71#include <string> // for string
72#include <system_error> // for error_code
73
74namespace lldb_private {
75class Address;
76}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000077
78using namespace lldb;
79using namespace lldb_private;
80
Caroline Ticeebc1bb22010-06-30 16:22:25 +000081static lldb::user_id_t g_unique_id = 1;
Zachary Turner7c2896a2014-10-24 22:06:29 +000082static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000083
Greg Clayton1b654882010-09-19 02:33:57 +000084#pragma mark Static Functions
85
Greg Clayton1b654882010-09-19 02:33:57 +000086typedef std::vector<DebuggerSP> DebuggerList;
Kate Stoneb9c1b512016-09-06 20:57:50 +000087static std::recursive_mutex *g_debugger_list_mutex_ptr =
88 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
89static DebuggerList *g_debugger_list_ptr =
90 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
Greg Claytone372b982011-11-21 21:44:34 +000091
Kate Stoneb9c1b512016-09-06 20:57:50 +000092OptionEnumValueElement g_show_disassembly_enum_values[] = {
93 {Debugger::eStopDisassemblyTypeNever, "never",
94 "Never show disassembly when displaying a stop context."},
95 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
96 "Show disassembly when there is no debug information."},
97 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
98 "Show disassembly when there is no source information, or the source file "
99 "is missing when displaying a stop context."},
100 {Debugger::eStopDisassemblyTypeAlways, "always",
101 "Always show disassembly when displaying a stop context."},
102 {0, nullptr, nullptr}};
Greg Claytone372b982011-11-21 21:44:34 +0000103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104OptionEnumValueElement g_language_enumerators[] = {
105 {eScriptLanguageNone, "none", "Disable scripting languages."},
106 {eScriptLanguagePython, "python",
107 "Select python as the default scripting language."},
108 {eScriptLanguageDefault, "default",
109 "Select the lldb default as the default scripting language."},
110 {0, nullptr, nullptr}};
Greg Claytone372b982011-11-21 21:44:34 +0000111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112#define MODULE_WITH_FUNC \
113 "{ " \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000114 "${module.file.basename}{`${function.name-with-args}" \
115 "{${frame.no-debug}${function.pc-offset}}}}"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000116
117#define MODULE_WITH_FUNC_NO_ARGS \
118 "{ " \
119 "${module.file.basename}{`${function.name-without-args}" \
120 "{${frame.no-debug}${function.pc-offset}}}}"
121
Greg Clayton67cc0632012-08-22 17:17:09 +0000122#define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
Jason Molenda6ab659a2015-07-29 00:42:47 +0000123#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125#define DEFAULT_THREAD_FORMAT \
126 "thread #${thread.index}: tid = ${thread.id%tid}" \
127 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
128 "{, name = '${thread.name}'}" \
129 "{, queue = '${thread.queue}'}" \
130 "{, activity = '${thread.info.activity.name}'}" \
131 "{, ${thread.info.trace_messages} messages}" \
132 "{, stop reason = ${thread.stop-reason}}" \
133 "{\\nReturn value: ${thread.return-value}}" \
134 "{\\nCompleted expression: ${thread.completed-expression}}" \
135 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000136
Jim Ingham6a9767c2016-11-08 20:36:40 +0000137#define DEFAULT_THREAD_STOP_FORMAT \
138 "thread #${thread.index}{, name = '${thread.name}'}" \
139 "{, queue = '${thread.queue}'}" \
140 "{, activity = '${thread.info.activity.name}'}" \
141 "{, ${thread.info.trace_messages} messages}" \
142 "{, stop reason = ${thread.stop-reason}}" \
143 "{\\nReturn value: ${thread.return-value}}" \
144 "{\\nCompleted expression: ${thread.completed-expression}}" \
145 "\\n"
146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147#define DEFAULT_FRAME_FORMAT \
Jason Molenda270e8222017-01-28 02:54:10 +0000148 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 IS_OPTIMIZED "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000150
Pavel Labath7f1c1212017-06-12 16:25:24 +0000151#define DEFAULT_FRAME_FORMAT_NO_ARGS \
152 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \
153 IS_OPTIMIZED "\\n"
154
Jason Molendac980fa92015-02-13 23:24:21 +0000155// Three parts to this disassembly format specification:
156// 1. If this is a new function/symbol (no previous symbol/function), print
157// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158// 2. If this is a symbol context change (different from previous
159// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000160// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161// 3. print
162// address <+offset>:
163#define DEFAULT_DISASSEMBLY_FORMAT \
164 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
165 "without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${" \
166 "function.name-without-args}}:\n}{${current-pc-arrow} " \
167 "}${addr-file-or-load}{ " \
168 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000169
Adrian Prantl05097242018-04-30 16:49:04 +0000170// gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
171// file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
172// offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000173
174// lldb's original format for disassembly would look like this format string -
Adrian Prantl05097242018-04-30 16:49:04 +0000175// {${function.initial-function}{${module.file.basename}`}{${function.name-
176// without-
177// args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
178// without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000179
Todd Fiala9666ba72016-09-21 20:13:14 +0000180#define DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX "${ansi.underline}"
181#define DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX "${ansi.normal}"
182
183static OptionEnumValueElement s_stop_show_column_values[] = {
184 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
185 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
186 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
187 "\"caret-only\" mode was selected."},
188 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
189 "terminal codes when running LLDB with "
190 "color/ANSI enabled."},
191 {eStopShowColumnCaret, "caret",
192 "Highlight the stop column with a caret character (^) underneath the stop "
193 "column. This method introduces a new line in source listings that "
194 "display thread stop locations."},
195 {eStopShowColumnNone, "none", "Do not highlight the stop column."},
196 {0, nullptr, nullptr}};
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198static PropertyDefinition g_properties[] = {
199 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
200 "If true all confirmation prompts will receive their default reply."},
201 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000202 DEFAULT_DISASSEMBLY_FORMAT, nullptr,
203 "The default disassembly format "
204 "string to use when disassembling "
205 "instruction sequences."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 {"frame-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000207 DEFAULT_FRAME_FORMAT, nullptr,
208 "The default frame format string to use "
209 "when displaying stack frame information "
210 "for threads."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, nullptr,
212 "Notify the user explicitly if an expression returns void (default: "
213 "false)."},
214 {"prompt", OptionValue::eTypeString, true,
215 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ",
216 nullptr, "The debugger command line prompt displayed for the user."},
217 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
218 nullptr, g_language_enumerators,
219 "The script language to be used for evaluating user-written scripts."},
220 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000221 nullptr,
222 "The number of disassembly lines to show when displaying a "
223 "stopped context."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
225 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
226 g_show_disassembly_enum_values,
227 "Control when to display disassembly when displaying a stopped context."},
228 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000229 nullptr,
230 "The number of sources lines to display that come after the "
231 "current source line when displaying a stopped context."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000233 nullptr,
234 "The number of sources lines to display that come before the "
235 "current source line when displaying a stopped context."},
Todd Fiala9666ba72016-09-21 20:13:14 +0000236 {"stop-show-column", OptionValue::eTypeEnum, false,
237 eStopShowColumnAnsiOrCaret, nullptr, s_stop_show_column_values,
238 "If true, LLDB will use the column information from the debug info to "
239 "mark the current position when displaying a stopped context."},
240 {"stop-show-column-ansi-prefix", OptionValue::eTypeFormatEntity, true, 0,
241 DEFAULT_STOP_SHOW_COLUMN_ANSI_PREFIX, nullptr,
242 "When displaying the column marker in a color-enabled (i.e. ANSI) "
243 "terminal, use the ANSI terminal code specified in this format at the "
244 "immediately before the column to be marked."},
245 {"stop-show-column-ansi-suffix", OptionValue::eTypeFormatEntity, true, 0,
246 DEFAULT_STOP_SHOW_COLUMN_ANSI_SUFFIX, nullptr,
247 "When displaying the column marker in a color-enabled (i.e. ANSI) "
248 "terminal, use the ANSI terminal code specified in this format "
249 "immediately after the column to be marked."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, nullptr,
251 "The maximum number of columns to use for displaying text."},
252 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000253 DEFAULT_THREAD_FORMAT, nullptr,
254 "The default thread format string to use "
255 "when displaying thread information."},
Jim Ingham6a9767c2016-11-08 20:36:40 +0000256 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000257 DEFAULT_THREAD_STOP_FORMAT, nullptr,
258 "The default thread format "
259 "string to use when displaying thread "
260 "information as part of the stop display."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr,
262 nullptr, "Whether to use an external editor or not."},
263 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
264 "Whether to use Ansi color codes or not."},
265 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000266 nullptr,
267 "If true, LLDB will automatically display small structs in "
268 "one-liner format (default: true)."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
270 "If true, LLDB will auto indent/outdent code. Currently only supported in "
271 "the REPL (default: true)."},
272 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
273 "If true, LLDB will print the values of variables declared in an "
274 "expression. Currently only supported in the REPL (default: true)."},
275 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, nullptr,
276 "The tab size to use when indenting code in multi-line input mode "
277 "(default: 4)."},
278 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000279 nullptr,
280 "If true, LLDB will automatically escape non-printable and "
281 "escape characters when formatting strings."},
282 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0,
283 DEFAULT_FRAME_FORMAT_NO_ARGS, nullptr,
284 "The default frame format string to use when displaying stack frame"
285 "information for threads from thread backtrace unique."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000287
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288enum {
289 ePropertyAutoConfirm = 0,
290 ePropertyDisassemblyFormat,
291 ePropertyFrameFormat,
292 ePropertyNotiftVoid,
293 ePropertyPrompt,
294 ePropertyScriptLanguage,
295 ePropertyStopDisassemblyCount,
296 ePropertyStopDisassemblyDisplay,
297 ePropertyStopLineCountAfter,
298 ePropertyStopLineCountBefore,
Todd Fiala9666ba72016-09-21 20:13:14 +0000299 ePropertyStopShowColumn,
300 ePropertyStopShowColumnAnsiPrefix,
301 ePropertyStopShowColumnAnsiSuffix,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 ePropertyTerminalWidth,
303 ePropertyThreadFormat,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000304 ePropertyThreadStopFormat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 ePropertyUseExternalEditor,
306 ePropertyUseColor,
307 ePropertyAutoOneLineSummaries,
308 ePropertyAutoIndent,
309 ePropertyPrintDecls,
310 ePropertyTabSize,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000311 ePropertyEscapeNonPrintables,
312 ePropertyFrameFormatUnique,
Greg Clayton67cc0632012-08-22 17:17:09 +0000313};
314
Eugene Zelenkodf370552016-03-02 02:18:18 +0000315LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000316
Zachary Turner97206d52017-05-12 04:51:55 +0000317Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
318 VarSetOperationType op,
319 llvm::StringRef property_path,
320 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000321 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
322 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 TargetSP target_sp;
324 LoadScriptFromSymFile load_script_old_value;
325 if (is_load_script && exe_ctx->GetTargetSP()) {
326 target_sp = exe_ctx->GetTargetSP();
327 load_script_old_value =
328 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
329 }
Zachary Turner97206d52017-05-12 04:51:55 +0000330 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 if (error.Success()) {
332 // FIXME it would be nice to have "on-change" callbacks for properties
Zachary Turner31d97a52016-11-17 18:08:12 +0000333 if (property_path == g_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000334 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
336 new_prompt, GetUseColor());
337 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000338 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000340 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
341 auto prompt_change_event_sp = std::make_shared<Event>(
342 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Zachary Turner31d97a52016-11-17 18:08:12 +0000344 } else if (property_path == g_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 // use-color changed. Ping the prompt so it can reset the ansi terminal
346 // codes.
347 SetPrompt(GetPrompt());
348 } else if (is_load_script && target_sp &&
349 load_script_old_value == eLoadScriptFromSymFileWarn) {
350 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
351 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000352 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 StreamString feedback_stream;
354 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
355 StreamFileSP stream_sp(GetErrorFile());
356 if (stream_sp) {
357 for (auto error : errors) {
358 stream_sp->Printf("%s\n", error.AsCString());
359 }
360 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000361 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 }
363 }
364 }
365 } else if (is_escape_non_printables) {
366 DataVisualization::ForceUpdate();
367 }
368 }
369 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000370}
371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372bool Debugger::GetAutoConfirm() const {
373 const uint32_t idx = ePropertyAutoConfirm;
374 return m_collection_sp->GetPropertyAtIndexAsBoolean(
375 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000376}
377
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
379 const uint32_t idx = ePropertyDisassemblyFormat;
380 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000381}
382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383const FormatEntity::Entry *Debugger::GetFrameFormat() const {
384 const uint32_t idx = ePropertyFrameFormat;
385 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000386}
387
Pavel Labath7f1c1212017-06-12 16:25:24 +0000388const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
389 const uint32_t idx = ePropertyFrameFormatUnique;
390 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
391}
392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393bool Debugger::GetNotifyVoid() const {
394 const uint32_t idx = ePropertyNotiftVoid;
395 return m_collection_sp->GetPropertyAtIndexAsBoolean(
396 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000397}
398
Zachary Turner514d8cd2016-09-23 18:06:53 +0000399llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 const uint32_t idx = ePropertyPrompt;
401 return m_collection_sp->GetPropertyAtIndexAsString(
402 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000403}
404
Zachary Turner514d8cd2016-09-23 18:06:53 +0000405void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 const uint32_t idx = ePropertyPrompt;
407 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000408 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 std::string str =
410 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
411 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000412 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000414}
415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416const FormatEntity::Entry *Debugger::GetThreadFormat() const {
417 const uint32_t idx = ePropertyThreadFormat;
418 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000419}
420
Jim Ingham6a9767c2016-11-08 20:36:40 +0000421const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
422 const uint32_t idx = ePropertyThreadStopFormat;
423 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
424}
425
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
427 const uint32_t idx = ePropertyScriptLanguage;
428 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
429 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000430}
431
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
433 const uint32_t idx = ePropertyScriptLanguage;
434 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
435 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000436}
437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438uint32_t Debugger::GetTerminalWidth() const {
439 const uint32_t idx = ePropertyTerminalWidth;
440 return m_collection_sp->GetPropertyAtIndexAsSInt64(
441 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000442}
443
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444bool Debugger::SetTerminalWidth(uint32_t term_width) {
445 const uint32_t idx = ePropertyTerminalWidth;
446 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000447}
448
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449bool Debugger::GetUseExternalEditor() const {
450 const uint32_t idx = ePropertyUseExternalEditor;
451 return m_collection_sp->GetPropertyAtIndexAsBoolean(
452 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000453}
Greg Claytone372b982011-11-21 21:44:34 +0000454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455bool Debugger::SetUseExternalEditor(bool b) {
456 const uint32_t idx = ePropertyUseExternalEditor;
457 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000458}
Enrico Granata553fad52013-10-25 23:09:40 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460bool Debugger::GetUseColor() const {
461 const uint32_t idx = ePropertyUseColor;
462 return m_collection_sp->GetPropertyAtIndexAsBoolean(
463 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000464}
465
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466bool Debugger::SetUseColor(bool b) {
467 const uint32_t idx = ePropertyUseColor;
468 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
469 SetPrompt(GetPrompt());
470 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000471}
472
Todd Fiala9666ba72016-09-21 20:13:14 +0000473StopShowColumn Debugger::GetStopShowColumn() const {
474 const uint32_t idx = ePropertyStopShowColumn;
475 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
476 nullptr, idx, g_properties[idx].default_uint_value);
477}
478
479const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiPrefix() const {
480 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
481 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
482}
483
484const FormatEntity::Entry *Debugger::GetStopShowColumnAnsiSuffix() const {
485 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
486 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
487}
488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489uint32_t Debugger::GetStopSourceLineCount(bool before) const {
490 const uint32_t idx =
491 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
492 return m_collection_sp->GetPropertyAtIndexAsSInt64(
493 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000494}
495
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
497 const uint32_t idx = ePropertyStopDisassemblyDisplay;
498 return (Debugger::StopDisassemblyType)
499 m_collection_sp->GetPropertyAtIndexAsEnumeration(
500 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000501}
502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503uint32_t Debugger::GetDisassemblyLineCount() const {
504 const uint32_t idx = ePropertyStopDisassemblyCount;
505 return m_collection_sp->GetPropertyAtIndexAsSInt64(
506 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000507}
508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509bool Debugger::GetAutoOneLineSummaries() const {
510 const uint32_t idx = ePropertyAutoOneLineSummaries;
511 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000512}
513
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514bool Debugger::GetEscapeNonPrintables() const {
515 const uint32_t idx = ePropertyEscapeNonPrintables;
516 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
517}
518
519bool Debugger::GetAutoIndent() const {
520 const uint32_t idx = ePropertyAutoIndent;
521 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
522}
523
524bool Debugger::SetAutoIndent(bool b) {
525 const uint32_t idx = ePropertyAutoIndent;
526 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
527}
528
529bool Debugger::GetPrintDecls() const {
530 const uint32_t idx = ePropertyPrintDecls;
531 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
532}
533
534bool Debugger::SetPrintDecls(bool b) {
535 const uint32_t idx = ePropertyPrintDecls;
536 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
537}
538
539uint32_t Debugger::GetTabSize() const {
540 const uint32_t idx = ePropertyTabSize;
541 return m_collection_sp->GetPropertyAtIndexAsUInt64(
542 nullptr, idx, g_properties[idx].default_uint_value);
543}
544
545bool Debugger::SetTabSize(uint32_t tab_size) {
546 const uint32_t idx = ePropertyTabSize;
547 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000548}
549
Greg Clayton1b654882010-09-19 02:33:57 +0000550#pragma mark Debugger
551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552// const DebuggerPropertiesSP &
553// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000554//{
555// return m_properties_sp;
556//}
557//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
560 assert(g_debugger_list_ptr == nullptr &&
561 "Debugger::Initialize called more than once!");
562 g_debugger_list_mutex_ptr = new std::recursive_mutex();
563 g_debugger_list_ptr = new DebuggerList();
564 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000565}
566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567void Debugger::Terminate() {
568 assert(g_debugger_list_ptr &&
569 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
572 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000573 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
575 for (const auto &debugger : *g_debugger_list_ptr)
576 debugger->Clear();
577 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000580}
581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000585
Zachary Turner97206d52017-05-12 04:51:55 +0000586bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587 if (g_load_plugin_callback) {
588 llvm::sys::DynamicLibrary dynlib =
589 g_load_plugin_callback(shared_from_this(), spec, error);
590 if (dynlib.isValid()) {
591 m_loaded_plugins.push_back(dynlib);
592 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000593 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000595 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
596 // if the public API layer isn't available (code is linking against all of
597 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 error.SetErrorString("Public API layer is not available");
599 }
600 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000601}
602
603static FileSpec::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000604LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 const FileSpec &file_spec) {
Zachary Turner97206d52017-05-12 04:51:55 +0000606 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000607
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000608 static ConstString g_dylibext(".dylib");
609 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610
611 if (!baton)
612 return FileSpec::eEnumerateDirectoryResultQuit;
613
614 Debugger *debugger = (Debugger *)baton;
615
Zachary Turner7d86ee52017-03-08 17:56:08 +0000616 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000617 // If we have a regular file, a symbolic link or unknown file type, try and
618 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 // enumeration might be enumerating a file system that doesn't have correct
620 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000621 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
622 ft == fs::file_type::type_unknown) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 FileSpec plugin_file_spec(file_spec);
624 plugin_file_spec.ResolvePath();
625
626 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
627 plugin_file_spec.GetFileNameExtension() != g_solibext) {
628 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000629 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630
Zachary Turner97206d52017-05-12 04:51:55 +0000631 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
633
Enrico Granata21dfcd92012-09-28 23:57:51 +0000634 return FileSpec::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000635 } else if (ft == fs::file_type::directory_file ||
636 ft == fs::file_type::symlink_file ||
637 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000638 // Try and recurse into anything that a directory or symbolic link. We must
639 // also do this for unknown as sometimes the directory enumeration might be
640 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 // information.
642 return FileSpec::eEnumerateDirectoryResultEnter;
643 }
644
645 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000646}
647
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 const bool find_directories = true;
650 const bool find_files = true;
651 const bool find_other = true;
652 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000653 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
655 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
656 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000657 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000659
Pavel Labath60f028f2018-06-19 15:09:07 +0000660 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
662 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
663 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000664 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 }
666
667 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000668}
669
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
671 void *baton) {
672 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
673 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
674 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
675 g_debugger_list_ptr->push_back(debugger_sp);
676 }
677 debugger_sp->InstanceInitialize();
678 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000679}
680
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681void Debugger::Destroy(DebuggerSP &debugger_sp) {
682 if (!debugger_sp)
683 return;
684
685 debugger_sp->Clear();
686
687 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
688 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
689 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
690 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
691 if ((*pos).get() == debugger_sp.get()) {
692 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000693 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000697}
698
Greg Clayton4d122c42011-09-17 08:33:22 +0000699DebuggerSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
701 DebuggerSP debugger_sp;
702 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
703 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
704 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
705 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
706 if ((*pos)->m_instance_name == instance_name) {
707 debugger_sp = *pos;
708 break;
709 }
Greg Clayton6920b522012-08-22 18:39:03 +0000710 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 }
712 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000713}
Greg Clayton66111032010-06-23 01:19:29 +0000714
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
716 TargetSP target_sp;
717 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
718 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
719 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
720 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
721 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
722 if (target_sp)
723 break;
Greg Clayton66111032010-06-23 01:19:29 +0000724 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 }
726 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000727}
728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729TargetSP Debugger::FindTargetWithProcess(Process *process) {
730 TargetSP target_sp;
731 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
732 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
733 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
734 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
735 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
736 if (target_sp)
737 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000738 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 }
740 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000741}
742
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
744 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000745 Properties(std::make_shared<OptionValueProperties>()),
746 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
747 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
748 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
750 m_terminal_state(), m_target_list(*this), m_platform_list(),
751 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
752 m_source_manager_ap(), m_source_file_cache(),
Zachary Turner2f3df612017-04-06 21:28:29 +0000753 m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>(
754 *this, eScriptLanguageDefault, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
756 m_event_handler_thread(), m_io_handler_thread(),
757 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
758 m_forward_listener_sp(), m_clear_once() {
759 char instance_cstr[256];
760 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
761 m_instance_name.SetCString(instance_cstr);
762 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000763 m_log_callback_stream_sp =
764 std::make_shared<StreamCallback>(log_callback, baton);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 m_command_interpreter_ap->Initialize();
766 // Always add our default platform to the platform list
767 PlatformSP default_platform_sp(Platform::GetHostPlatform());
768 assert(default_platform_sp);
769 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 m_collection_sp->Initialize(g_properties);
772 m_collection_sp->AppendProperty(
773 ConstString("target"),
774 ConstString("Settings specify to debugging targets."), true,
775 Target::GetGlobalProperties()->GetValueProperties());
776 m_collection_sp->AppendProperty(
777 ConstString("platform"), ConstString("Platform settings."), true,
778 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000779 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000780 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
781 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782 if (m_command_interpreter_ap) {
783 m_collection_sp->AppendProperty(
784 ConstString("interpreter"),
785 ConstString("Settings specify to the debugger's command interpreter."),
786 true, m_command_interpreter_ap->GetValueProperties());
787 }
788 OptionValueSInt64 *term_width =
789 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
790 nullptr, ePropertyTerminalWidth);
791 term_width->SetMinimumValue(10);
792 term_width->SetMaximumValue(1024);
793
794 // Turn off use-color if this is a dumb terminal.
795 const char *term = getenv("TERM");
796 if (term && !strcmp(term, "dumb"))
797 SetUseColor(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798}
799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802void Debugger::Clear() {
803 //----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000804 // Make sure we call this function only once. With the C++ global destructor
805 // chain having a list of debuggers and with code that can be running on
806 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 //
808 // The following functions call Debugger::Clear():
809 // Debugger::~Debugger();
810 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
811 // static void Debugger::Terminate();
812 //----------------------------------------------------------------------
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000813 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000814 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 StopIOHandlerThread();
816 StopEventHandlerThread();
817 m_listener_sp->Clear();
818 int num_targets = m_target_list.GetNumTargets();
819 for (int i = 0; i < num_targets; i++) {
820 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
821 if (target_sp) {
822 ProcessSP process_sp(target_sp->GetProcessSP());
823 if (process_sp)
824 process_sp->Finalize();
825 target_sp->Destroy();
826 }
Greg Clayton577508d2014-06-20 00:23:57 +0000827 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 m_broadcaster_manager_sp->Clear();
829
830 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000831 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 m_terminal_state.Clear();
833 if (m_input_file_sp)
834 m_input_file_sp->GetFile().Close();
835
836 m_command_interpreter_ap->Clear();
837 });
Greg Clayton44d93782014-01-27 23:43:24 +0000838}
839
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840bool Debugger::GetCloseInputOnEOF() const {
841 // return m_input_comm.GetCloseOnEOF();
842 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000843}
844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845void Debugger::SetCloseInputOnEOF(bool b) {
846 // m_input_comm.SetCloseOnEOF(b);
847}
848
849bool Debugger::GetAsyncExecution() {
850 return !m_command_interpreter_ap->GetSynchronous();
851}
852
853void Debugger::SetAsyncExecution(bool async_execution) {
854 m_command_interpreter_ap->SetSynchronous(!async_execution);
855}
856
857void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
858 if (m_input_file_sp)
859 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
860 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000861 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862
863 File &in_file = m_input_file_sp->GetFile();
864 if (!in_file.IsValid())
865 in_file.SetStream(stdin, true);
866
Adrian Prantl05097242018-04-30 16:49:04 +0000867 // Save away the terminal state if that is relevant, so that we can restore
868 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 SaveInputTerminalState();
870}
871
872void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
873 if (m_output_file_sp)
874 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
875 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000876 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877
878 File &out_file = m_output_file_sp->GetFile();
879 if (!out_file.IsValid())
880 out_file.SetStream(stdout, false);
881
Adrian Prantl05097242018-04-30 16:49:04 +0000882 // do not create the ScriptInterpreter just for setting the output file
883 // handle as the constructor will know how to do the right thing on its own
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 const bool can_create = false;
885 ScriptInterpreter *script_interpreter =
886 GetCommandInterpreter().GetScriptInterpreter(can_create);
887 if (script_interpreter)
888 script_interpreter->ResetOutputFileHandle(fh);
889}
890
891void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
892 if (m_error_file_sp)
893 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
894 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000895 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896
897 File &err_file = m_error_file_sp->GetFile();
898 if (!err_file.IsValid())
899 err_file.SetStream(stderr, false);
900}
901
902void Debugger::SaveInputTerminalState() {
903 if (m_input_file_sp) {
904 File &in_file = m_input_file_sp->GetFile();
905 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
906 m_terminal_state.Save(in_file.GetDescriptor(), true);
907 }
908}
909
910void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
911
912ExecutionContext Debugger::GetSelectedExecutionContext() {
913 ExecutionContext exe_ctx;
914 TargetSP target_sp(GetSelectedTarget());
915 exe_ctx.SetTargetSP(target_sp);
916
917 if (target_sp) {
918 ProcessSP process_sp(target_sp->GetProcessSP());
919 exe_ctx.SetProcessSP(process_sp);
920 if (process_sp && !process_sp->IsRunning()) {
921 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
922 if (thread_sp) {
923 exe_ctx.SetThreadSP(thread_sp);
924 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
925 if (exe_ctx.GetFramePtr() == nullptr)
926 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
927 }
928 }
929 }
930 return exe_ctx;
931}
932
933void Debugger::DispatchInputInterrupt() {
934 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
935 IOHandlerSP reader_sp(m_input_reader_stack.Top());
936 if (reader_sp)
937 reader_sp->Interrupt();
938}
939
940void Debugger::DispatchInputEndOfFile() {
941 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
942 IOHandlerSP reader_sp(m_input_reader_stack.Top());
943 if (reader_sp)
944 reader_sp->GotEOF();
945}
946
947void Debugger::ClearIOHandlers() {
948 // The bottom input reader should be the main debugger input reader. We do
949 // not want to close that one here.
950 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
951 while (m_input_reader_stack.GetSize() > 1) {
952 IOHandlerSP reader_sp(m_input_reader_stack.Top());
953 if (reader_sp)
954 PopIOHandler(reader_sp);
955 }
956}
957
958void Debugger::ExecuteIOHandlers() {
959 while (true) {
960 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000963
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000965
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 // Remove all input readers that are done from the top of the stack
967 while (true) {
968 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
969 if (top_reader_sp && top_reader_sp->GetIsDone())
970 PopIOHandler(top_reader_sp);
971 else
972 break;
973 }
974 }
975 ClearIOHandlers();
976}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000977
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
979 return m_input_reader_stack.IsTop(reader_sp);
980}
Greg Clayton44d93782014-01-27 23:43:24 +0000981
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
983 IOHandler::Type second_top_type) {
984 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
985}
986
987void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
988 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
989 m_input_reader_stack.PrintAsync(stream.get(), s, len);
990}
991
992ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
993 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
994}
995
996const char *Debugger::GetIOHandlerCommandPrefix() {
997 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
998}
999
1000const char *Debugger::GetIOHandlerHelpPrologue() {
1001 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1002}
1003
1004void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1005 PushIOHandler(reader_sp);
1006
1007 IOHandlerSP top_reader_sp = reader_sp;
1008 while (top_reader_sp) {
1009 top_reader_sp->Run();
1010
1011 if (top_reader_sp.get() == reader_sp.get()) {
1012 if (PopIOHandler(reader_sp))
1013 break;
1014 }
1015
1016 while (true) {
1017 top_reader_sp = m_input_reader_stack.Top();
1018 if (top_reader_sp && top_reader_sp->GetIsDone())
1019 PopIOHandler(top_reader_sp);
1020 else
1021 break;
1022 }
1023 }
1024}
1025
1026void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1027 StreamFileSP &out,
1028 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +00001029 // Before an IOHandler runs, it must have in/out/err streams. This function
1030 // is called when one ore more of the streams are nullptr. We use the top
1031 // input reader's in/out/err streams, or fall back to the debugger file
1032 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033
1034 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1035 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1036 // If no STDIN has been set, then set it appropriately
1037 if (!in) {
1038 if (top_reader_sp)
1039 in = top_reader_sp->GetInputStreamFile();
1040 else
1041 in = GetInputFile();
1042
1043 // If there is nothing, use stdin
1044 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001045 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 }
1047 // If no STDOUT has been set, then set it appropriately
1048 if (!out) {
1049 if (top_reader_sp)
1050 out = top_reader_sp->GetOutputStreamFile();
1051 else
1052 out = GetOutputFile();
1053
1054 // If there is nothing, use stdout
1055 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001056 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 }
1058 // If no STDERR has been set, then set it appropriately
1059 if (!err) {
1060 if (top_reader_sp)
1061 err = top_reader_sp->GetErrorStreamFile();
1062 else
1063 err = GetErrorFile();
1064
1065 // If there is nothing, use stderr
1066 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001067 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 }
1069}
1070
1071void Debugger::PushIOHandler(const IOHandlerSP &reader_sp) {
1072 if (!reader_sp)
1073 return;
1074
1075 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1076
1077 // Get the current top input reader...
1078 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1079
1080 // Don't push the same IO handler twice...
1081 if (reader_sp == top_reader_sp)
1082 return;
1083
1084 // Push our new input reader
1085 m_input_reader_stack.Push(reader_sp);
1086 reader_sp->Activate();
1087
Adrian Prantl05097242018-04-30 16:49:04 +00001088 // Interrupt the top input reader to it will exit its Run() function and let
1089 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 if (top_reader_sp) {
1091 top_reader_sp->Deactivate();
1092 top_reader_sp->Cancel();
1093 }
1094}
1095
1096bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1097 if (!pop_reader_sp)
1098 return false;
1099
1100 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1101
Adrian Prantl05097242018-04-30 16:49:04 +00001102 // The reader on the stop of the stack is done, so let the next read on the
1103 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 if (m_input_reader_stack.IsEmpty())
1105 return false;
1106
1107 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1108
1109 if (pop_reader_sp != reader_sp)
1110 return false;
1111
1112 reader_sp->Deactivate();
1113 reader_sp->Cancel();
1114 m_input_reader_stack.Pop();
1115
1116 reader_sp = m_input_reader_stack.Top();
1117 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001118 reader_sp->Activate();
1119
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 return true;
1121}
1122
1123StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001124 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125}
1126
1127StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001128 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001129}
1130
1131size_t Debugger::GetNumDebuggers() {
1132 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1133 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1134 return g_debugger_list_ptr->size();
1135 }
1136 return 0;
1137}
1138
1139lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1140 DebuggerSP debugger_sp;
1141
1142 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1143 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1144 if (index < g_debugger_list_ptr->size())
1145 debugger_sp = g_debugger_list_ptr->at(index);
1146 }
1147
1148 return debugger_sp;
1149}
1150
1151DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1152 DebuggerSP debugger_sp;
1153
1154 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1155 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1156 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1157 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1158 if ((*pos)->GetID() == id) {
1159 debugger_sp = *pos;
1160 break;
1161 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001162 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 }
1164 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001165}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001166
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1168 const SymbolContext *sc,
1169 const SymbolContext *prev_sc,
1170 const ExecutionContext *exe_ctx,
1171 const Address *addr, Stream &s) {
1172 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001173
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 if (format == nullptr) {
1175 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1176 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1177 if (format == nullptr) {
1178 FormatEntity::Parse("${addr}: ", format_entry);
1179 format = &format_entry;
1180 }
1181 }
1182 bool function_changed = false;
1183 bool initial_function = false;
1184 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1185 if (sc && (sc->function || sc->symbol)) {
1186 if (prev_sc->symbol && sc->symbol) {
1187 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1188 prev_sc->symbol->GetType())) {
1189 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001190 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 } else if (prev_sc->function && sc->function) {
1192 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1193 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001194 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001196 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 }
Adrian Prantl05097242018-04-30 16:49:04 +00001198 // The first context on a list of instructions will have a prev_sc that has
1199 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 // would return false. But we do get a prev_sc pointer.
1201 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1202 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1203 initial_function = true;
1204 }
1205 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1206 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001207}
1208
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1210 void *baton) {
1211 // For simplicity's sake, I am not going to deal with how to close down any
1212 // open logging streams, I just redirect everything from here on out to the
1213 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001214 m_log_callback_stream_sp =
1215 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001216}
1217
Pavel Labath5e336902017-03-01 10:08:40 +00001218bool Debugger::EnableLog(llvm::StringRef channel,
1219 llvm::ArrayRef<const char *> categories,
1220 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001221 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001222 const bool should_close = true;
1223 const bool unbuffered = true;
1224
1225 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 if (m_log_callback_stream_sp) {
1227 log_stream_sp = m_log_callback_stream_sp;
1228 // For now when using the callback mode you always get thread & timestamp.
1229 log_options |=
1230 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001231 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001232 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1233 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001235 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 if (pos != m_log_streams.end())
1237 log_stream_sp = pos->second.lock();
1238 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001239 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1240 if (log_options & LLDB_LOG_OPTION_APPEND)
1241 flags |= llvm::sys::fs::F_Append;
1242 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001243 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1244 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001245 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001246 return false;
1247 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001248 log_stream_sp =
1249 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 }
1253 assert(log_stream_sp);
1254
1255 if (log_options == 0)
1256 log_options =
1257 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1258
1259 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1260 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001261}
1262
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263SourceManager &Debugger::GetSourceManager() {
1264 if (!m_source_manager_ap)
Zachary Turner2f3df612017-04-06 21:28:29 +00001265 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 return *m_source_manager_ap;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001267}
1268
Greg Clayton44d93782014-01-27 23:43:24 +00001269// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1271 using namespace lldb;
1272 const uint32_t event_type =
1273 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1274 event_sp);
1275
1276 // if (event_type & eBreakpointEventTypeAdded
1277 // || event_type & eBreakpointEventTypeRemoved
1278 // || event_type & eBreakpointEventTypeEnabled
1279 // || event_type & eBreakpointEventTypeDisabled
1280 // || event_type & eBreakpointEventTypeCommandChanged
1281 // || event_type & eBreakpointEventTypeConditionChanged
1282 // || event_type & eBreakpointEventTypeIgnoreChanged
1283 // || event_type & eBreakpointEventTypeLocationsResolved)
1284 // {
1285 // // Don't do anything about these events, since the breakpoint
1286 // commands already echo these actions.
1287 // }
1288 //
1289 if (event_type & eBreakpointEventTypeLocationsAdded) {
1290 uint32_t num_new_locations =
1291 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1292 event_sp);
1293 if (num_new_locations > 0) {
1294 BreakpointSP breakpoint =
1295 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1296 StreamSP output_sp(GetAsyncOutputStream());
1297 if (output_sp) {
1298 output_sp->Printf("%d location%s added to breakpoint %d\n",
1299 num_new_locations, num_new_locations == 1 ? "" : "s",
1300 breakpoint->GetID());
1301 output_sp->Flush();
1302 }
Greg Clayton44d93782014-01-27 23:43:24 +00001303 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 }
1305 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1306 // {
1307 // // These locations just get disabled, not sure it is worth spamming
1308 // folks about this on the command line.
1309 // }
1310 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1311 // {
1312 // // This might be an interesting thing to note, but I'm going to
1313 // leave it quiet for now, it just looked noisy.
1314 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001315}
1316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1318 size_t total_bytes = 0;
1319 if (stream == nullptr)
1320 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001321
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 if (stream) {
1323 // The process has stuff waiting for stdout; get it and write it out to the
1324 // appropriate place.
1325 if (process == nullptr) {
1326 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1327 if (target_sp)
1328 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001329 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001331 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 size_t len;
1333 char stdio_buffer[1024];
1334 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1335 error)) > 0) {
1336 stream->Write(stdio_buffer, len);
1337 total_bytes += len;
1338 }
1339 }
1340 stream->Flush();
1341 }
1342 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001343}
1344
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1346 size_t total_bytes = 0;
1347 if (stream == nullptr)
1348 stream = GetOutputFile().get();
1349
1350 if (stream) {
1351 // The process has stuff waiting for stderr; get it and write it out to the
1352 // appropriate place.
1353 if (process == nullptr) {
1354 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1355 if (target_sp)
1356 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001357 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001359 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001360 size_t len;
1361 char stdio_buffer[1024];
1362 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1363 error)) > 0) {
1364 stream->Write(stdio_buffer, len);
1365 total_bytes += len;
1366 }
1367 }
1368 stream->Flush();
1369 }
1370 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001371}
1372
1373// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1375 using namespace lldb;
1376 const uint32_t event_type = event_sp->GetType();
1377 ProcessSP process_sp =
1378 (event_type == Process::eBroadcastBitStructuredData)
1379 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1380 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001381
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 StreamSP output_stream_sp = GetAsyncOutputStream();
1383 StreamSP error_stream_sp = GetAsyncErrorStream();
1384 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001385
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386 if (!gui_enabled) {
1387 bool pop_process_io_handler = false;
1388 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001389
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 bool state_is_stopped = false;
1391 const bool got_state_changed =
1392 (event_type & Process::eBroadcastBitStateChanged) != 0;
1393 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1394 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1395 const bool got_structured_data =
1396 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001397
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398 if (got_state_changed) {
1399 StateType event_state =
1400 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1401 state_is_stopped = StateIsStoppedState(event_state, false);
1402 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001403
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404 // Display running state changes first before any STDIO
1405 if (got_state_changed && !state_is_stopped) {
1406 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1407 pop_process_io_handler);
1408 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 // Now display and STDOUT
1411 if (got_stdout || got_state_changed) {
1412 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1413 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001414
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415 // Now display and STDERR
1416 if (got_stderr || got_state_changed) {
1417 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1418 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001419
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420 // Give structured data events an opportunity to display.
1421 if (got_structured_data) {
1422 StructuredDataPluginSP plugin_sp =
1423 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1424 if (plugin_sp) {
1425 auto structured_data_sp =
1426 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1427 if (output_stream_sp) {
1428 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001429 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 plugin_sp->GetDescription(structured_data_sp, content_stream);
1431 if (error.Success()) {
1432 if (!content_stream.GetString().empty()) {
1433 // Add newline.
1434 content_stream.PutChar('\n');
1435 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001436
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001438 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001439 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 } else {
1441 error_stream_sp->Printf("Failed to print structured "
1442 "data with plugin %s: %s",
1443 plugin_sp->GetPluginName().AsCString(),
1444 error.AsCString());
1445 }
Todd Fiala75930012016-08-19 04:21:48 +00001446 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001448 }
Greg Clayton44d93782014-01-27 23:43:24 +00001449
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 // Now display any stopped state changes after any STDIO
1451 if (got_state_changed && state_is_stopped) {
1452 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1453 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001454 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455
1456 output_stream_sp->Flush();
1457 error_stream_sp->Flush();
1458
1459 if (pop_process_io_handler)
1460 process_sp->PopProcessIOHandler();
1461 }
Greg Clayton44d93782014-01-27 23:43:24 +00001462}
1463
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001465 // At present the only thread event we handle is the Frame Changed event, and
1466 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 using namespace lldb;
1468 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001469 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 if (event_type == Thread::eBroadcastBitStackChanged ||
1471 event_type == Thread::eBroadcastBitThreadSelected) {
1472 ThreadSP thread_sp(
1473 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1474 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001475 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 }
1477 }
Greg Clayton44d93782014-01-27 23:43:24 +00001478}
1479
Kate Stoneb9c1b512016-09-06 20:57:50 +00001480bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1481
1482void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1483 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001484}
1485
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1487 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001488}
1489
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490void Debugger::DefaultEventHandler() {
1491 ListenerSP listener_sp(GetListener());
1492 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1493 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1494 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1495 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1496 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001497
Kate Stoneb9c1b512016-09-06 20:57:50 +00001498 BroadcastEventSpec process_event_spec(
1499 broadcaster_class_process,
1500 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1501 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001502
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1504 Thread::eBroadcastBitStackChanged |
1505 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001506
Kate Stoneb9c1b512016-09-06 20:57:50 +00001507 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1508 target_event_spec);
1509 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1510 process_event_spec);
1511 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1512 thread_event_spec);
1513 listener_sp->StartListeningForEvents(
1514 m_command_interpreter_ap.get(),
1515 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1516 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1517 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001518
Adrian Prantl05097242018-04-30 16:49:04 +00001519 // Let the thread that spawned us know that we have started up and that we
1520 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001522
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 bool done = false;
1524 while (!done) {
1525 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001526 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527 if (event_sp) {
1528 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1529 if (broadcaster) {
1530 uint32_t event_type = event_sp->GetType();
1531 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1532 if (broadcaster_class == broadcaster_class_process) {
1533 HandleProcessEvent(event_sp);
1534 } else if (broadcaster_class == broadcaster_class_target) {
1535 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1536 event_sp.get())) {
1537 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001538 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001539 } else if (broadcaster_class == broadcaster_class_thread) {
1540 HandleThreadEvent(event_sp);
1541 } else if (broadcaster == m_command_interpreter_ap.get()) {
1542 if (event_type &
1543 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1544 done = true;
1545 } else if (event_type &
1546 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1547 const char *data = reinterpret_cast<const char *>(
1548 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1549 if (data && data[0]) {
1550 StreamSP error_sp(GetAsyncErrorStream());
1551 if (error_sp) {
1552 error_sp->PutCString(data);
1553 error_sp->Flush();
1554 }
1555 }
1556 } else if (event_type & CommandInterpreter::
1557 eBroadcastBitAsynchronousOutputData) {
1558 const char *data = reinterpret_cast<const char *>(
1559 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1560 if (data && data[0]) {
1561 StreamSP output_sp(GetAsyncOutputStream());
1562 if (output_sp) {
1563 output_sp->PutCString(data);
1564 output_sp->Flush();
1565 }
1566 }
1567 }
1568 }
Greg Clayton44d93782014-01-27 23:43:24 +00001569 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570
1571 if (m_forward_listener_sp)
1572 m_forward_listener_sp->AddEvent(event_sp);
1573 }
Greg Clayton44d93782014-01-27 23:43:24 +00001574 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001575 }
Greg Clayton44d93782014-01-27 23:43:24 +00001576}
1577
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1579 ((Debugger *)arg)->DefaultEventHandler();
1580 return NULL;
Greg Clayton44d93782014-01-27 23:43:24 +00001581}
1582
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583bool Debugger::StartEventHandlerThread() {
1584 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001585 // We must synchronize with the DefaultEventHandler() thread to ensure it
1586 // is up and running and listening to events before we return from this
1587 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001589 ConstString full_name("lldb.debugger.event-handler");
1590 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001591 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1592 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001593
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001594 auto thread_name =
1595 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1596 full_name.AsCString() : "dbg.evt-handler";
1597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 // Use larger 8MB stack for this thread
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001599 m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name,
1600 EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001601
Adrian Prantl05097242018-04-30 16:49:04 +00001602 // Make sure DefaultEventHandler() is running and listening to events
1603 // before we return from this function. We are only listening for events of
1604 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1605 // event, we just need to wait an infinite amount of time for it (nullptr
1606 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001608 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609 }
1610 return m_event_handler_thread.IsJoinable();
1611}
1612
1613void Debugger::StopEventHandlerThread() {
1614 if (m_event_handler_thread.IsJoinable()) {
1615 GetCommandInterpreter().BroadcastEvent(
1616 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1617 m_event_handler_thread.Join(nullptr);
1618 }
1619}
1620
1621lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1622 Debugger *debugger = (Debugger *)arg;
1623 debugger->ExecuteIOHandlers();
1624 debugger->StopEventHandlerThread();
1625 return NULL;
1626}
1627
1628bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1629
1630bool Debugger::StartIOHandlerThread() {
1631 if (!m_io_handler_thread.IsJoinable())
1632 m_io_handler_thread = ThreadLauncher::LaunchThread(
1633 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1634 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1635 return m_io_handler_thread.IsJoinable();
1636}
1637
1638void Debugger::StopIOHandlerThread() {
1639 if (m_io_handler_thread.IsJoinable()) {
1640 if (m_input_file_sp)
1641 m_input_file_sp->GetFile().Close();
1642 m_io_handler_thread.Join(nullptr);
1643 }
1644}
1645
1646void Debugger::JoinIOHandlerThread() {
1647 if (HasIOHandlerThread()) {
1648 thread_result_t result;
1649 m_io_handler_thread.Join(&result);
1650 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1651 }
1652}
1653
1654Target *Debugger::GetDummyTarget() {
1655 return m_target_list.GetDummyTarget(*this).get();
1656}
1657
1658Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1659 Target *target = nullptr;
1660 if (!prefer_dummy) {
1661 target = m_target_list.GetSelectedTarget().get();
1662 if (target)
1663 return target;
1664 }
1665
1666 return GetDummyTarget();
1667}
1668
Zachary Turner97206d52017-05-12 04:51:55 +00001669Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1670 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671 FileSpec repl_executable;
1672
1673 if (language == eLanguageTypeUnknown) {
1674 std::set<LanguageType> repl_languages;
1675
1676 Language::GetLanguagesSupportingREPLs(repl_languages);
1677
1678 if (repl_languages.size() == 1) {
1679 language = *repl_languages.begin();
1680 } else if (repl_languages.empty()) {
1681 err.SetErrorStringWithFormat(
1682 "LLDB isn't configured with REPL support for any languages.");
1683 return err;
1684 } else {
1685 err.SetErrorStringWithFormat(
1686 "Multiple possible REPL languages. Please specify a language.");
1687 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 }
Greg Clayton44d93782014-01-27 23:43:24 +00001690
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 Target *const target =
1692 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001693
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001695
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001697 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001698 }
1699
1700 if (!repl_sp) {
1701 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1702 Language::GetNameForLanguageType(language));
1703 return err;
1704 }
1705
1706 repl_sp->SetCompilerOptions(repl_options);
1707 repl_sp->RunLoop();
1708
1709 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001710}