blob: b7bf76be4ffc4ca7dcf45e774ec3f1b7c482074f [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"
Pavel Labathd821c992018-08-07 11:07:21 +000015#include "lldb/Core/Listener.h" // for Listener
16#include "lldb/Core/Mangled.h" // for Mangled
17#include "lldb/Core/ModuleList.h" // for Mangled
Greg Claytone8cd0c92012-10-19 18:02:49 +000018#include "lldb/Core/PluginManager.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"
Pavel Labathd821c992018-08-07 11:07:21 +000045#include "lldb/Utility/Log.h" // for LLDB_LOG_OPTION_...
46#include "lldb/Utility/State.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000047#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
David Bolvansky8aa23612018-09-05 22:06:58 +000053#include "lldb/Host/windows/windows.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000054#endif
55
56#include "llvm/ADT/None.h" // for None
57#include "llvm/ADT/STLExtras.h" // for make_unique
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/iterator.h" // for iterator_facade_...
60#include "llvm/Support/DynamicLibrary.h"
61#include "llvm/Support/FileSystem.h"
David Bolvansky8aa23612018-09-05 22:06:58 +000062#include "llvm/Support/Process.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000063#include "llvm/Support/Threading.h"
64#include "llvm/Support/raw_ostream.h" // for raw_fd_ostream
65
66#include <list> // for list
67#include <memory> // for make_shared
68#include <mutex>
69#include <set> // for set
70#include <stdio.h> // for size_t, NULL
71#include <stdlib.h> // for getenv
72#include <string.h> // for strcmp
73#include <string> // for string
74#include <system_error> // for error_code
75
76namespace lldb_private {
77class Address;
78}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000079
80using namespace lldb;
81using namespace lldb_private;
82
Caroline Ticeebc1bb22010-06-30 16:22:25 +000083static lldb::user_id_t g_unique_id = 1;
Zachary Turner7c2896a2014-10-24 22:06:29 +000084static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000085
Greg Clayton1b654882010-09-19 02:33:57 +000086#pragma mark Static Functions
87
Greg Clayton1b654882010-09-19 02:33:57 +000088typedef std::vector<DebuggerSP> DebuggerList;
Kate Stoneb9c1b512016-09-06 20:57:50 +000089static std::recursive_mutex *g_debugger_list_mutex_ptr =
90 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
91static DebuggerList *g_debugger_list_ptr =
92 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
Greg Claytone372b982011-11-21 21:44:34 +000093
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000094static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000095 {Debugger::eStopDisassemblyTypeNever, "never",
96 "Never show disassembly when displaying a stop context."},
97 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
98 "Show disassembly when there is no debug information."},
99 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
100 "Show disassembly when there is no source information, or the source file "
101 "is missing when displaying a stop context."},
102 {Debugger::eStopDisassemblyTypeAlways, "always",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000103 "Always show disassembly when displaying a stop context."} };
Greg Claytone372b982011-11-21 21:44:34 +0000104
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000105static constexpr OptionEnumValueElement g_language_enumerators[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 {eScriptLanguageNone, "none", "Disable scripting languages."},
107 {eScriptLanguagePython, "python",
108 "Select python as the default scripting language."},
109 {eScriptLanguageDefault, "default",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000110 "Select the lldb default as the default scripting language."} };
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
Adrian Prantl4954f6a2018-09-05 23:52:08 +0000122#define FILE_AND_LINE \
123 "{ at ${line.file.basename}:${line.number}{:${line.column}}}"
Jason Molenda6ab659a2015-07-29 00:42:47 +0000124#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126#define DEFAULT_THREAD_FORMAT \
127 "thread #${thread.index}: tid = ${thread.id%tid}" \
128 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
129 "{, name = '${thread.name}'}" \
130 "{, queue = '${thread.queue}'}" \
131 "{, activity = '${thread.info.activity.name}'}" \
132 "{, ${thread.info.trace_messages} messages}" \
133 "{, stop reason = ${thread.stop-reason}}" \
134 "{\\nReturn value: ${thread.return-value}}" \
135 "{\\nCompleted expression: ${thread.completed-expression}}" \
136 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000137
Jim Ingham6a9767c2016-11-08 20:36:40 +0000138#define DEFAULT_THREAD_STOP_FORMAT \
139 "thread #${thread.index}{, name = '${thread.name}'}" \
140 "{, queue = '${thread.queue}'}" \
141 "{, activity = '${thread.info.activity.name}'}" \
142 "{, ${thread.info.trace_messages} messages}" \
143 "{, stop reason = ${thread.stop-reason}}" \
144 "{\\nReturn value: ${thread.return-value}}" \
145 "{\\nCompleted expression: ${thread.completed-expression}}" \
146 "\\n"
147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148#define DEFAULT_FRAME_FORMAT \
Jason Molenda270e8222017-01-28 02:54:10 +0000149 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 IS_OPTIMIZED "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000151
Pavel Labath7f1c1212017-06-12 16:25:24 +0000152#define DEFAULT_FRAME_FORMAT_NO_ARGS \
153 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \
154 IS_OPTIMIZED "\\n"
155
Jason Molendac980fa92015-02-13 23:24:21 +0000156// Three parts to this disassembly format specification:
157// 1. If this is a new function/symbol (no previous symbol/function), print
158// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159// 2. If this is a symbol context change (different from previous
160// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000161// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162// 3. print
163// address <+offset>:
164#define DEFAULT_DISASSEMBLY_FORMAT \
165 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
166 "without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${" \
167 "function.name-without-args}}:\n}{${current-pc-arrow} " \
168 "}${addr-file-or-load}{ " \
169 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000170
Adrian Prantl05097242018-04-30 16:49:04 +0000171// gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
172// file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
173// offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000174
175// lldb's original format for disassembly would look like this format string -
Adrian Prantl05097242018-04-30 16:49:04 +0000176// {${function.initial-function}{${module.file.basename}`}{${function.name-
177// without-
178// args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
179// without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000180
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000181static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
Todd Fiala9666ba72016-09-21 20:13:14 +0000182 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
183 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
184 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
185 "\"caret-only\" mode was selected."},
186 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
187 "terminal codes when running LLDB with "
188 "color/ANSI enabled."},
189 {eStopShowColumnCaret, "caret",
190 "Highlight the stop column with a caret character (^) underneath the stop "
191 "column. This method introduces a new line in source listings that "
192 "display thread stop locations."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000193 {eStopShowColumnNone, "none", "Do not highlight the stop column."}};
Todd Fiala9666ba72016-09-21 20:13:14 +0000194
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000195static constexpr PropertyDefinition g_properties[] = {
196 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 "If true all confirmation prompts will receive their default reply."},
198 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000199 DEFAULT_DISASSEMBLY_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000200 "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,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000204 DEFAULT_FRAME_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000205 "The default frame format string to use "
206 "when displaying stack frame information "
207 "for threads."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000208 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 "Notify the user explicitly if an expression returns void (default: "
210 "false)."},
211 {"prompt", OptionValue::eTypeString, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000212 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", {},
213 "The debugger command line prompt displayed for the user."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000215 nullptr, OptionEnumValues(g_language_enumerators),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 "The script language to be used for evaluating user-written scripts."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000217 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000218 "The number of disassembly lines to show when displaying a "
219 "stopped context."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
221 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000222 OptionEnumValues(g_show_disassembly_enum_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 "Control when to display disassembly when displaying a stopped context."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000224 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000225 "The number of sources lines to display that come after the "
226 "current source line when displaying a stopped context."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000227 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000228 "The number of sources lines to display that come before the "
229 "current source line when displaying a stopped context."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000230 {"highlight-source", OptionValue::eTypeBoolean, true, true, nullptr, {},
231 "If true, LLDB will highlight the displayed source code."},
Todd Fiala9666ba72016-09-21 20:13:14 +0000232 {"stop-show-column", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000233 eStopShowColumnAnsiOrCaret, nullptr, OptionEnumValues(s_stop_show_column_values),
Todd Fiala9666ba72016-09-21 20:13:14 +0000234 "If true, LLDB will use the column information from the debug info to "
235 "mark the current position when displaying a stopped context."},
Raphael Isemann20786322018-08-30 00:09:21 +0000236 {"stop-show-column-ansi-prefix", OptionValue::eTypeString, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000237 "${ansi.underline}", {},
Todd Fiala9666ba72016-09-21 20:13:14 +0000238 "When displaying the column marker in a color-enabled (i.e. ANSI) "
239 "terminal, use the ANSI terminal code specified in this format at the "
240 "immediately before the column to be marked."},
Raphael Isemann20786322018-08-30 00:09:21 +0000241 {"stop-show-column-ansi-suffix", OptionValue::eTypeString, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000242 "${ansi.normal}", {},
Todd Fiala9666ba72016-09-21 20:13:14 +0000243 "When displaying the column marker in a color-enabled (i.e. ANSI) "
244 "terminal, use the ANSI terminal code specified in this format "
245 "immediately after the column to be marked."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000246 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 "The maximum number of columns to use for displaying text."},
248 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000249 DEFAULT_THREAD_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000250 "The default thread format string to use "
251 "when displaying thread information."},
Jim Ingham6a9767c2016-11-08 20:36:40 +0000252 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000253 DEFAULT_THREAD_STOP_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000254 "The default thread format "
255 "string to use when displaying thread "
256 "information as part of the stop display."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000257 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr, {},
258 "Whether to use an external editor or not."},
259 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 "Whether to use Ansi color codes or not."},
261 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000262 {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000263 "If true, LLDB will automatically display small structs in "
264 "one-liner format (default: true)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000265 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 "If true, LLDB will auto indent/outdent code. Currently only supported in "
267 "the REPL (default: true)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000268 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 "If true, LLDB will print the values of variables declared in an "
270 "expression. Currently only supported in the REPL (default: true)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000271 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 "The tab size to use when indenting code in multi-line input mode "
273 "(default: 4)."},
274 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000275 {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000276 "If true, LLDB will automatically escape non-printable and "
277 "escape characters when formatting strings."},
278 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000279 DEFAULT_FRAME_FORMAT_NO_ARGS, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000280 "The default frame format string to use when displaying stack frame"
Tatyana Krasnukhae40db052018-09-27 07:11:58 +0000281 "information for threads from thread backtrace unique."}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000282
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283enum {
284 ePropertyAutoConfirm = 0,
285 ePropertyDisassemblyFormat,
286 ePropertyFrameFormat,
287 ePropertyNotiftVoid,
288 ePropertyPrompt,
289 ePropertyScriptLanguage,
290 ePropertyStopDisassemblyCount,
291 ePropertyStopDisassemblyDisplay,
292 ePropertyStopLineCountAfter,
293 ePropertyStopLineCountBefore,
Raphael Isemann566afa02018-08-02 00:30:15 +0000294 ePropertyHighlightSource,
Todd Fiala9666ba72016-09-21 20:13:14 +0000295 ePropertyStopShowColumn,
296 ePropertyStopShowColumnAnsiPrefix,
297 ePropertyStopShowColumnAnsiSuffix,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 ePropertyTerminalWidth,
299 ePropertyThreadFormat,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000300 ePropertyThreadStopFormat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 ePropertyUseExternalEditor,
302 ePropertyUseColor,
303 ePropertyAutoOneLineSummaries,
304 ePropertyAutoIndent,
305 ePropertyPrintDecls,
306 ePropertyTabSize,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000307 ePropertyEscapeNonPrintables,
308 ePropertyFrameFormatUnique,
Greg Clayton67cc0632012-08-22 17:17:09 +0000309};
310
Eugene Zelenkodf370552016-03-02 02:18:18 +0000311LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000312
Zachary Turner97206d52017-05-12 04:51:55 +0000313Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
314 VarSetOperationType op,
315 llvm::StringRef property_path,
316 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000317 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
318 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 TargetSP target_sp;
320 LoadScriptFromSymFile load_script_old_value;
321 if (is_load_script && exe_ctx->GetTargetSP()) {
322 target_sp = exe_ctx->GetTargetSP();
323 load_script_old_value =
324 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
325 }
Zachary Turner97206d52017-05-12 04:51:55 +0000326 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 if (error.Success()) {
328 // FIXME it would be nice to have "on-change" callbacks for properties
Zachary Turner31d97a52016-11-17 18:08:12 +0000329 if (property_path == g_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000330 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
332 new_prompt, GetUseColor());
333 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000334 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000336 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
337 auto prompt_change_event_sp = std::make_shared<Event>(
338 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Zachary Turner31d97a52016-11-17 18:08:12 +0000340 } else if (property_path == g_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 // use-color changed. Ping the prompt so it can reset the ansi terminal
342 // codes.
343 SetPrompt(GetPrompt());
344 } else if (is_load_script && target_sp &&
345 load_script_old_value == eLoadScriptFromSymFileWarn) {
346 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
347 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000348 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 StreamString feedback_stream;
350 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
351 StreamFileSP stream_sp(GetErrorFile());
352 if (stream_sp) {
353 for (auto error : errors) {
354 stream_sp->Printf("%s\n", error.AsCString());
355 }
356 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000357 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 }
359 }
360 }
361 } else if (is_escape_non_printables) {
362 DataVisualization::ForceUpdate();
363 }
364 }
365 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000366}
367
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368bool Debugger::GetAutoConfirm() const {
369 const uint32_t idx = ePropertyAutoConfirm;
370 return m_collection_sp->GetPropertyAtIndexAsBoolean(
371 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000372}
373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
375 const uint32_t idx = ePropertyDisassemblyFormat;
376 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000377}
378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379const FormatEntity::Entry *Debugger::GetFrameFormat() const {
380 const uint32_t idx = ePropertyFrameFormat;
381 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000382}
383
Pavel Labath7f1c1212017-06-12 16:25:24 +0000384const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
385 const uint32_t idx = ePropertyFrameFormatUnique;
386 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
387}
388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389bool Debugger::GetNotifyVoid() const {
390 const uint32_t idx = ePropertyNotiftVoid;
391 return m_collection_sp->GetPropertyAtIndexAsBoolean(
392 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000393}
394
Zachary Turner514d8cd2016-09-23 18:06:53 +0000395llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 const uint32_t idx = ePropertyPrompt;
397 return m_collection_sp->GetPropertyAtIndexAsString(
398 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000399}
400
Zachary Turner514d8cd2016-09-23 18:06:53 +0000401void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 const uint32_t idx = ePropertyPrompt;
403 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000404 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 std::string str =
406 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
407 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000408 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000410}
411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412const FormatEntity::Entry *Debugger::GetThreadFormat() const {
413 const uint32_t idx = ePropertyThreadFormat;
414 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000415}
416
Jim Ingham6a9767c2016-11-08 20:36:40 +0000417const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
418 const uint32_t idx = ePropertyThreadStopFormat;
419 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
420}
421
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
423 const uint32_t idx = ePropertyScriptLanguage;
424 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
425 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000426}
427
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
429 const uint32_t idx = ePropertyScriptLanguage;
430 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
431 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000432}
433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434uint32_t Debugger::GetTerminalWidth() const {
435 const uint32_t idx = ePropertyTerminalWidth;
436 return m_collection_sp->GetPropertyAtIndexAsSInt64(
437 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000438}
439
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440bool Debugger::SetTerminalWidth(uint32_t term_width) {
441 const uint32_t idx = ePropertyTerminalWidth;
442 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000443}
444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445bool Debugger::GetUseExternalEditor() const {
446 const uint32_t idx = ePropertyUseExternalEditor;
447 return m_collection_sp->GetPropertyAtIndexAsBoolean(
448 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000449}
Greg Claytone372b982011-11-21 21:44:34 +0000450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451bool Debugger::SetUseExternalEditor(bool b) {
452 const uint32_t idx = ePropertyUseExternalEditor;
453 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000454}
Enrico Granata553fad52013-10-25 23:09:40 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456bool Debugger::GetUseColor() const {
457 const uint32_t idx = ePropertyUseColor;
458 return m_collection_sp->GetPropertyAtIndexAsBoolean(
459 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000460}
461
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462bool Debugger::SetUseColor(bool b) {
463 const uint32_t idx = ePropertyUseColor;
464 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
465 SetPrompt(GetPrompt());
466 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000467}
468
Raphael Isemann566afa02018-08-02 00:30:15 +0000469bool Debugger::GetHighlightSource() const {
470 const uint32_t idx = ePropertyHighlightSource;
471 return m_collection_sp->GetPropertyAtIndexAsBoolean(
472 nullptr, idx, g_properties[idx].default_uint_value);
473}
474
Todd Fiala9666ba72016-09-21 20:13:14 +0000475StopShowColumn Debugger::GetStopShowColumn() const {
476 const uint32_t idx = ePropertyStopShowColumn;
477 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
478 nullptr, idx, g_properties[idx].default_uint_value);
479}
480
Raphael Isemann20786322018-08-30 00:09:21 +0000481llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000482 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000483 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000484}
485
Raphael Isemann20786322018-08-30 00:09:21 +0000486llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000487 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000488 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000489}
490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491uint32_t Debugger::GetStopSourceLineCount(bool before) const {
492 const uint32_t idx =
493 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
494 return m_collection_sp->GetPropertyAtIndexAsSInt64(
495 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000496}
497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
499 const uint32_t idx = ePropertyStopDisassemblyDisplay;
500 return (Debugger::StopDisassemblyType)
501 m_collection_sp->GetPropertyAtIndexAsEnumeration(
502 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000503}
504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505uint32_t Debugger::GetDisassemblyLineCount() const {
506 const uint32_t idx = ePropertyStopDisassemblyCount;
507 return m_collection_sp->GetPropertyAtIndexAsSInt64(
508 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000509}
510
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511bool Debugger::GetAutoOneLineSummaries() const {
512 const uint32_t idx = ePropertyAutoOneLineSummaries;
513 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000514}
515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516bool Debugger::GetEscapeNonPrintables() const {
517 const uint32_t idx = ePropertyEscapeNonPrintables;
518 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
519}
520
521bool Debugger::GetAutoIndent() const {
522 const uint32_t idx = ePropertyAutoIndent;
523 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
524}
525
526bool Debugger::SetAutoIndent(bool b) {
527 const uint32_t idx = ePropertyAutoIndent;
528 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
529}
530
531bool Debugger::GetPrintDecls() const {
532 const uint32_t idx = ePropertyPrintDecls;
533 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
534}
535
536bool Debugger::SetPrintDecls(bool b) {
537 const uint32_t idx = ePropertyPrintDecls;
538 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
539}
540
541uint32_t Debugger::GetTabSize() const {
542 const uint32_t idx = ePropertyTabSize;
543 return m_collection_sp->GetPropertyAtIndexAsUInt64(
544 nullptr, idx, g_properties[idx].default_uint_value);
545}
546
547bool Debugger::SetTabSize(uint32_t tab_size) {
548 const uint32_t idx = ePropertyTabSize;
549 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000550}
551
Greg Clayton1b654882010-09-19 02:33:57 +0000552#pragma mark Debugger
553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554// const DebuggerPropertiesSP &
555// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000556//{
557// return m_properties_sp;
558//}
559//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
562 assert(g_debugger_list_ptr == nullptr &&
563 "Debugger::Initialize called more than once!");
564 g_debugger_list_mutex_ptr = new std::recursive_mutex();
565 g_debugger_list_ptr = new DebuggerList();
566 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000567}
568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569void Debugger::Terminate() {
570 assert(g_debugger_list_ptr &&
571 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
574 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000575 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
577 for (const auto &debugger : *g_debugger_list_ptr)
578 debugger->Clear();
579 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582}
583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000587
Zachary Turner97206d52017-05-12 04:51:55 +0000588bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 if (g_load_plugin_callback) {
590 llvm::sys::DynamicLibrary dynlib =
591 g_load_plugin_callback(shared_from_this(), spec, error);
592 if (dynlib.isValid()) {
593 m_loaded_plugins.push_back(dynlib);
594 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000595 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000597 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
598 // if the public API layer isn't available (code is linking against all of
599 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 error.SetErrorString("Public API layer is not available");
601 }
602 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000603}
604
605static FileSpec::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000606LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 const FileSpec &file_spec) {
Zachary Turner97206d52017-05-12 04:51:55 +0000608 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000609
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000610 static ConstString g_dylibext(".dylib");
611 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612
613 if (!baton)
614 return FileSpec::eEnumerateDirectoryResultQuit;
615
616 Debugger *debugger = (Debugger *)baton;
617
Zachary Turner7d86ee52017-03-08 17:56:08 +0000618 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000619 // If we have a regular file, a symbolic link or unknown file type, try and
620 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 // enumeration might be enumerating a file system that doesn't have correct
622 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000623 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
624 ft == fs::file_type::type_unknown) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 FileSpec plugin_file_spec(file_spec);
626 plugin_file_spec.ResolvePath();
627
628 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
629 plugin_file_spec.GetFileNameExtension() != g_solibext) {
630 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000631 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632
Zachary Turner97206d52017-05-12 04:51:55 +0000633 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
635
Enrico Granata21dfcd92012-09-28 23:57:51 +0000636 return FileSpec::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000637 } else if (ft == fs::file_type::directory_file ||
638 ft == fs::file_type::symlink_file ||
639 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000640 // Try and recurse into anything that a directory or symbolic link. We must
641 // also do this for unknown as sometimes the directory enumeration might be
642 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643 // information.
644 return FileSpec::eEnumerateDirectoryResultEnter;
645 }
646
647 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000648}
649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 const bool find_directories = true;
652 const bool find_files = true;
653 const bool find_other = true;
654 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000655 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
657 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
658 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000659 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000661
Pavel Labath60f028f2018-06-19 15:09:07 +0000662 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
664 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
665 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000666 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 }
668
669 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000670}
671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
673 void *baton) {
674 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
675 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
676 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
677 g_debugger_list_ptr->push_back(debugger_sp);
678 }
679 debugger_sp->InstanceInitialize();
680 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000681}
682
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683void Debugger::Destroy(DebuggerSP &debugger_sp) {
684 if (!debugger_sp)
685 return;
686
687 debugger_sp->Clear();
688
689 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
690 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
691 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
692 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
693 if ((*pos).get() == debugger_sp.get()) {
694 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000695 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000697 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000699}
700
Greg Clayton4d122c42011-09-17 08:33:22 +0000701DebuggerSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
703 DebuggerSP debugger_sp;
704 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
705 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
706 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
707 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
708 if ((*pos)->m_instance_name == instance_name) {
709 debugger_sp = *pos;
710 break;
711 }
Greg Clayton6920b522012-08-22 18:39:03 +0000712 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 }
714 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000715}
Greg Clayton66111032010-06-23 01:19:29 +0000716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
718 TargetSP target_sp;
719 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
720 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
721 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
722 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
723 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
724 if (target_sp)
725 break;
Greg Clayton66111032010-06-23 01:19:29 +0000726 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 }
728 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000729}
730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731TargetSP Debugger::FindTargetWithProcess(Process *process) {
732 TargetSP target_sp;
733 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
734 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
735 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
736 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
737 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
738 if (target_sp)
739 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000740 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 }
742 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000743}
744
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
746 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000747 Properties(std::make_shared<OptionValueProperties>()),
748 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
749 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
750 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
752 m_terminal_state(), m_target_list(*this), m_platform_list(),
753 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
754 m_source_manager_ap(), m_source_file_cache(),
Zachary Turner2f3df612017-04-06 21:28:29 +0000755 m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>(
756 *this, eScriptLanguageDefault, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
758 m_event_handler_thread(), m_io_handler_thread(),
759 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
760 m_forward_listener_sp(), m_clear_once() {
761 char instance_cstr[256];
762 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
763 m_instance_name.SetCString(instance_cstr);
764 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000765 m_log_callback_stream_sp =
766 std::make_shared<StreamCallback>(log_callback, baton);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 m_command_interpreter_ap->Initialize();
768 // Always add our default platform to the platform list
769 PlatformSP default_platform_sp(Platform::GetHostPlatform());
770 assert(default_platform_sp);
771 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000772
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 m_collection_sp->Initialize(g_properties);
774 m_collection_sp->AppendProperty(
775 ConstString("target"),
776 ConstString("Settings specify to debugging targets."), true,
777 Target::GetGlobalProperties()->GetValueProperties());
778 m_collection_sp->AppendProperty(
779 ConstString("platform"), ConstString("Platform settings."), true,
780 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000781 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000782 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
783 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 if (m_command_interpreter_ap) {
785 m_collection_sp->AppendProperty(
786 ConstString("interpreter"),
787 ConstString("Settings specify to the debugger's command interpreter."),
788 true, m_command_interpreter_ap->GetValueProperties());
789 }
790 OptionValueSInt64 *term_width =
791 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
792 nullptr, ePropertyTerminalWidth);
793 term_width->SetMinimumValue(10);
794 term_width->SetMaximumValue(1024);
795
796 // Turn off use-color if this is a dumb terminal.
797 const char *term = getenv("TERM");
798 if (term && !strcmp(term, "dumb"))
799 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000800 // Turn off use-color if we don't write to a terminal with color support.
801 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
802 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000803
804#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
805 // Enabling use of ANSI color codes because LLDB is using them to highlight
806 // text.
807 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000808#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809}
810
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000812
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813void Debugger::Clear() {
814 //----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000815 // Make sure we call this function only once. With the C++ global destructor
816 // chain having a list of debuggers and with code that can be running on
817 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 //
819 // The following functions call Debugger::Clear():
820 // Debugger::~Debugger();
821 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
822 // static void Debugger::Terminate();
823 //----------------------------------------------------------------------
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000824 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000825 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 StopIOHandlerThread();
827 StopEventHandlerThread();
828 m_listener_sp->Clear();
829 int num_targets = m_target_list.GetNumTargets();
830 for (int i = 0; i < num_targets; i++) {
831 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
832 if (target_sp) {
833 ProcessSP process_sp(target_sp->GetProcessSP());
834 if (process_sp)
835 process_sp->Finalize();
836 target_sp->Destroy();
837 }
Greg Clayton577508d2014-06-20 00:23:57 +0000838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 m_broadcaster_manager_sp->Clear();
840
841 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000842 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 m_terminal_state.Clear();
844 if (m_input_file_sp)
845 m_input_file_sp->GetFile().Close();
846
847 m_command_interpreter_ap->Clear();
848 });
Greg Clayton44d93782014-01-27 23:43:24 +0000849}
850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851bool Debugger::GetCloseInputOnEOF() const {
852 // return m_input_comm.GetCloseOnEOF();
853 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000854}
855
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856void Debugger::SetCloseInputOnEOF(bool b) {
857 // m_input_comm.SetCloseOnEOF(b);
858}
859
860bool Debugger::GetAsyncExecution() {
861 return !m_command_interpreter_ap->GetSynchronous();
862}
863
864void Debugger::SetAsyncExecution(bool async_execution) {
865 m_command_interpreter_ap->SetSynchronous(!async_execution);
866}
867
868void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
869 if (m_input_file_sp)
870 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
871 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000872 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873
874 File &in_file = m_input_file_sp->GetFile();
875 if (!in_file.IsValid())
876 in_file.SetStream(stdin, true);
877
Adrian Prantl05097242018-04-30 16:49:04 +0000878 // Save away the terminal state if that is relevant, so that we can restore
879 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 SaveInputTerminalState();
881}
882
883void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
884 if (m_output_file_sp)
885 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
886 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000887 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888
889 File &out_file = m_output_file_sp->GetFile();
890 if (!out_file.IsValid())
891 out_file.SetStream(stdout, false);
892
Adrian Prantl05097242018-04-30 16:49:04 +0000893 // do not create the ScriptInterpreter just for setting the output file
894 // handle as the constructor will know how to do the right thing on its own
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 const bool can_create = false;
896 ScriptInterpreter *script_interpreter =
897 GetCommandInterpreter().GetScriptInterpreter(can_create);
898 if (script_interpreter)
899 script_interpreter->ResetOutputFileHandle(fh);
900}
901
902void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
903 if (m_error_file_sp)
904 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
905 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000906 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907
908 File &err_file = m_error_file_sp->GetFile();
909 if (!err_file.IsValid())
910 err_file.SetStream(stderr, false);
911}
912
913void Debugger::SaveInputTerminalState() {
914 if (m_input_file_sp) {
915 File &in_file = m_input_file_sp->GetFile();
916 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
917 m_terminal_state.Save(in_file.GetDescriptor(), true);
918 }
919}
920
921void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
922
923ExecutionContext Debugger::GetSelectedExecutionContext() {
924 ExecutionContext exe_ctx;
925 TargetSP target_sp(GetSelectedTarget());
926 exe_ctx.SetTargetSP(target_sp);
927
928 if (target_sp) {
929 ProcessSP process_sp(target_sp->GetProcessSP());
930 exe_ctx.SetProcessSP(process_sp);
931 if (process_sp && !process_sp->IsRunning()) {
932 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
933 if (thread_sp) {
934 exe_ctx.SetThreadSP(thread_sp);
935 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
936 if (exe_ctx.GetFramePtr() == nullptr)
937 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
938 }
939 }
940 }
941 return exe_ctx;
942}
943
944void Debugger::DispatchInputInterrupt() {
945 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
946 IOHandlerSP reader_sp(m_input_reader_stack.Top());
947 if (reader_sp)
948 reader_sp->Interrupt();
949}
950
951void Debugger::DispatchInputEndOfFile() {
952 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
953 IOHandlerSP reader_sp(m_input_reader_stack.Top());
954 if (reader_sp)
955 reader_sp->GotEOF();
956}
957
958void Debugger::ClearIOHandlers() {
959 // The bottom input reader should be the main debugger input reader. We do
960 // not want to close that one here.
961 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
962 while (m_input_reader_stack.GetSize() > 1) {
963 IOHandlerSP reader_sp(m_input_reader_stack.Top());
964 if (reader_sp)
965 PopIOHandler(reader_sp);
966 }
967}
968
969void Debugger::ExecuteIOHandlers() {
970 while (true) {
971 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000972 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000974
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000976
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 // Remove all input readers that are done from the top of the stack
978 while (true) {
979 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
980 if (top_reader_sp && top_reader_sp->GetIsDone())
981 PopIOHandler(top_reader_sp);
982 else
983 break;
984 }
985 }
986 ClearIOHandlers();
987}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000988
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
990 return m_input_reader_stack.IsTop(reader_sp);
991}
Greg Clayton44d93782014-01-27 23:43:24 +0000992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
994 IOHandler::Type second_top_type) {
995 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
996}
997
998void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
999 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
1000 m_input_reader_stack.PrintAsync(stream.get(), s, len);
1001}
1002
1003ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1004 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
1005}
1006
1007const char *Debugger::GetIOHandlerCommandPrefix() {
1008 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
1009}
1010
1011const char *Debugger::GetIOHandlerHelpPrologue() {
1012 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1013}
1014
1015void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1016 PushIOHandler(reader_sp);
1017
1018 IOHandlerSP top_reader_sp = reader_sp;
1019 while (top_reader_sp) {
1020 top_reader_sp->Run();
1021
1022 if (top_reader_sp.get() == reader_sp.get()) {
1023 if (PopIOHandler(reader_sp))
1024 break;
1025 }
1026
1027 while (true) {
1028 top_reader_sp = m_input_reader_stack.Top();
1029 if (top_reader_sp && top_reader_sp->GetIsDone())
1030 PopIOHandler(top_reader_sp);
1031 else
1032 break;
1033 }
1034 }
1035}
1036
1037void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1038 StreamFileSP &out,
1039 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +00001040 // Before an IOHandler runs, it must have in/out/err streams. This function
1041 // is called when one ore more of the streams are nullptr. We use the top
1042 // input reader's in/out/err streams, or fall back to the debugger file
1043 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044
1045 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1046 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1047 // If no STDIN has been set, then set it appropriately
1048 if (!in) {
1049 if (top_reader_sp)
1050 in = top_reader_sp->GetInputStreamFile();
1051 else
1052 in = GetInputFile();
1053
1054 // If there is nothing, use stdin
1055 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001056 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 }
1058 // If no STDOUT has been set, then set it appropriately
1059 if (!out) {
1060 if (top_reader_sp)
1061 out = top_reader_sp->GetOutputStreamFile();
1062 else
1063 out = GetOutputFile();
1064
1065 // If there is nothing, use stdout
1066 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001067 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 }
1069 // If no STDERR has been set, then set it appropriately
1070 if (!err) {
1071 if (top_reader_sp)
1072 err = top_reader_sp->GetErrorStreamFile();
1073 else
1074 err = GetErrorFile();
1075
1076 // If there is nothing, use stderr
1077 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001078 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 }
1080}
1081
Raphael Isemannc01783a2018-08-29 22:50:54 +00001082void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1083 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 if (!reader_sp)
1085 return;
1086
1087 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1088
1089 // Get the current top input reader...
1090 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1091
1092 // Don't push the same IO handler twice...
1093 if (reader_sp == top_reader_sp)
1094 return;
1095
1096 // Push our new input reader
1097 m_input_reader_stack.Push(reader_sp);
1098 reader_sp->Activate();
1099
Adrian Prantl05097242018-04-30 16:49:04 +00001100 // Interrupt the top input reader to it will exit its Run() function and let
1101 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 if (top_reader_sp) {
1103 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001104 if (cancel_top_handler)
1105 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 }
1107}
1108
1109bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1110 if (!pop_reader_sp)
1111 return false;
1112
1113 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1114
Adrian Prantl05097242018-04-30 16:49:04 +00001115 // The reader on the stop of the stack is done, so let the next read on the
1116 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 if (m_input_reader_stack.IsEmpty())
1118 return false;
1119
1120 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1121
1122 if (pop_reader_sp != reader_sp)
1123 return false;
1124
1125 reader_sp->Deactivate();
1126 reader_sp->Cancel();
1127 m_input_reader_stack.Pop();
1128
1129 reader_sp = m_input_reader_stack.Top();
1130 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001131 reader_sp->Activate();
1132
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 return true;
1134}
1135
1136StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001137 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138}
1139
1140StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001141 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142}
1143
1144size_t Debugger::GetNumDebuggers() {
1145 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1146 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1147 return g_debugger_list_ptr->size();
1148 }
1149 return 0;
1150}
1151
1152lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1153 DebuggerSP debugger_sp;
1154
1155 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1156 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1157 if (index < g_debugger_list_ptr->size())
1158 debugger_sp = g_debugger_list_ptr->at(index);
1159 }
1160
1161 return debugger_sp;
1162}
1163
1164DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1165 DebuggerSP debugger_sp;
1166
1167 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1168 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1169 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1170 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1171 if ((*pos)->GetID() == id) {
1172 debugger_sp = *pos;
1173 break;
1174 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001175 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176 }
1177 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001178}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001179
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1181 const SymbolContext *sc,
1182 const SymbolContext *prev_sc,
1183 const ExecutionContext *exe_ctx,
1184 const Address *addr, Stream &s) {
1185 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001186
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187 if (format == nullptr) {
1188 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1189 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1190 if (format == nullptr) {
1191 FormatEntity::Parse("${addr}: ", format_entry);
1192 format = &format_entry;
1193 }
1194 }
1195 bool function_changed = false;
1196 bool initial_function = false;
1197 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1198 if (sc && (sc->function || sc->symbol)) {
1199 if (prev_sc->symbol && sc->symbol) {
1200 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1201 prev_sc->symbol->GetType())) {
1202 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001203 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 } else if (prev_sc->function && sc->function) {
1205 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1206 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001207 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001209 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 }
Adrian Prantl05097242018-04-30 16:49:04 +00001211 // The first context on a list of instructions will have a prev_sc that has
1212 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 // would return false. But we do get a prev_sc pointer.
1214 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1215 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1216 initial_function = true;
1217 }
1218 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1219 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001220}
1221
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1223 void *baton) {
1224 // For simplicity's sake, I am not going to deal with how to close down any
1225 // open logging streams, I just redirect everything from here on out to the
1226 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001227 m_log_callback_stream_sp =
1228 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001229}
1230
Pavel Labath5e336902017-03-01 10:08:40 +00001231bool Debugger::EnableLog(llvm::StringRef channel,
1232 llvm::ArrayRef<const char *> categories,
1233 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001234 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001235 const bool should_close = true;
1236 const bool unbuffered = true;
1237
1238 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 if (m_log_callback_stream_sp) {
1240 log_stream_sp = m_log_callback_stream_sp;
1241 // For now when using the callback mode you always get thread & timestamp.
1242 log_options |=
1243 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001244 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001245 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1246 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001248 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 if (pos != m_log_streams.end())
1250 log_stream_sp = pos->second.lock();
1251 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001252 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1253 if (log_options & LLDB_LOG_OPTION_APPEND)
1254 flags |= llvm::sys::fs::F_Append;
1255 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001256 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1257 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001258 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001259 return false;
1260 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001261 log_stream_sp =
1262 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001264 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 }
1266 assert(log_stream_sp);
1267
1268 if (log_options == 0)
1269 log_options =
1270 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1271
1272 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1273 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001274}
1275
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276SourceManager &Debugger::GetSourceManager() {
1277 if (!m_source_manager_ap)
Zachary Turner2f3df612017-04-06 21:28:29 +00001278 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 return *m_source_manager_ap;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001280}
1281
Greg Clayton44d93782014-01-27 23:43:24 +00001282// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1284 using namespace lldb;
1285 const uint32_t event_type =
1286 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1287 event_sp);
1288
1289 // if (event_type & eBreakpointEventTypeAdded
1290 // || event_type & eBreakpointEventTypeRemoved
1291 // || event_type & eBreakpointEventTypeEnabled
1292 // || event_type & eBreakpointEventTypeDisabled
1293 // || event_type & eBreakpointEventTypeCommandChanged
1294 // || event_type & eBreakpointEventTypeConditionChanged
1295 // || event_type & eBreakpointEventTypeIgnoreChanged
1296 // || event_type & eBreakpointEventTypeLocationsResolved)
1297 // {
1298 // // Don't do anything about these events, since the breakpoint
1299 // commands already echo these actions.
1300 // }
1301 //
1302 if (event_type & eBreakpointEventTypeLocationsAdded) {
1303 uint32_t num_new_locations =
1304 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1305 event_sp);
1306 if (num_new_locations > 0) {
1307 BreakpointSP breakpoint =
1308 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1309 StreamSP output_sp(GetAsyncOutputStream());
1310 if (output_sp) {
1311 output_sp->Printf("%d location%s added to breakpoint %d\n",
1312 num_new_locations, num_new_locations == 1 ? "" : "s",
1313 breakpoint->GetID());
1314 output_sp->Flush();
1315 }
Greg Clayton44d93782014-01-27 23:43:24 +00001316 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 }
1318 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1319 // {
1320 // // These locations just get disabled, not sure it is worth spamming
1321 // folks about this on the command line.
1322 // }
1323 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1324 // {
1325 // // This might be an interesting thing to note, but I'm going to
1326 // leave it quiet for now, it just looked noisy.
1327 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001328}
1329
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1331 size_t total_bytes = 0;
1332 if (stream == nullptr)
1333 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001334
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335 if (stream) {
1336 // The process has stuff waiting for stdout; get it and write it out to the
1337 // appropriate place.
1338 if (process == nullptr) {
1339 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1340 if (target_sp)
1341 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001342 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001344 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345 size_t len;
1346 char stdio_buffer[1024];
1347 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1348 error)) > 0) {
1349 stream->Write(stdio_buffer, len);
1350 total_bytes += len;
1351 }
1352 }
1353 stream->Flush();
1354 }
1355 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001356}
1357
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1359 size_t total_bytes = 0;
1360 if (stream == nullptr)
1361 stream = GetOutputFile().get();
1362
1363 if (stream) {
1364 // The process has stuff waiting for stderr; get it and write it out to the
1365 // appropriate place.
1366 if (process == nullptr) {
1367 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1368 if (target_sp)
1369 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001370 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001372 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 size_t len;
1374 char stdio_buffer[1024];
1375 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1376 error)) > 0) {
1377 stream->Write(stdio_buffer, len);
1378 total_bytes += len;
1379 }
1380 }
1381 stream->Flush();
1382 }
1383 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001384}
1385
1386// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1388 using namespace lldb;
1389 const uint32_t event_type = event_sp->GetType();
1390 ProcessSP process_sp =
1391 (event_type == Process::eBroadcastBitStructuredData)
1392 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1393 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001394
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 StreamSP output_stream_sp = GetAsyncOutputStream();
1396 StreamSP error_stream_sp = GetAsyncErrorStream();
1397 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001398
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 if (!gui_enabled) {
1400 bool pop_process_io_handler = false;
1401 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001402
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403 bool state_is_stopped = false;
1404 const bool got_state_changed =
1405 (event_type & Process::eBroadcastBitStateChanged) != 0;
1406 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1407 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1408 const bool got_structured_data =
1409 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001410
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 if (got_state_changed) {
1412 StateType event_state =
1413 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1414 state_is_stopped = StateIsStoppedState(event_state, false);
1415 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001416
Kate Stoneb9c1b512016-09-06 20:57:50 +00001417 // Display running state changes first before any STDIO
1418 if (got_state_changed && !state_is_stopped) {
1419 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1420 pop_process_io_handler);
1421 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001422
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 // Now display and STDOUT
1424 if (got_stdout || got_state_changed) {
1425 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1426 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001427
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 // Now display and STDERR
1429 if (got_stderr || got_state_changed) {
1430 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1431 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001432
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 // Give structured data events an opportunity to display.
1434 if (got_structured_data) {
1435 StructuredDataPluginSP plugin_sp =
1436 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1437 if (plugin_sp) {
1438 auto structured_data_sp =
1439 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1440 if (output_stream_sp) {
1441 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001442 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 plugin_sp->GetDescription(structured_data_sp, content_stream);
1444 if (error.Success()) {
1445 if (!content_stream.GetString().empty()) {
1446 // Add newline.
1447 content_stream.PutChar('\n');
1448 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001449
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001451 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001452 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 } else {
1454 error_stream_sp->Printf("Failed to print structured "
1455 "data with plugin %s: %s",
1456 plugin_sp->GetPluginName().AsCString(),
1457 error.AsCString());
1458 }
Todd Fiala75930012016-08-19 04:21:48 +00001459 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001461 }
Greg Clayton44d93782014-01-27 23:43:24 +00001462
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 // Now display any stopped state changes after any STDIO
1464 if (got_state_changed && state_is_stopped) {
1465 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1466 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001467 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001468
1469 output_stream_sp->Flush();
1470 error_stream_sp->Flush();
1471
1472 if (pop_process_io_handler)
1473 process_sp->PopProcessIOHandler();
1474 }
Greg Clayton44d93782014-01-27 23:43:24 +00001475}
1476
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001478 // At present the only thread event we handle is the Frame Changed event, and
1479 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001480 using namespace lldb;
1481 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001482 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 if (event_type == Thread::eBroadcastBitStackChanged ||
1484 event_type == Thread::eBroadcastBitThreadSelected) {
1485 ThreadSP thread_sp(
1486 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1487 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001488 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 }
1490 }
Greg Clayton44d93782014-01-27 23:43:24 +00001491}
1492
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1494
1495void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1496 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001497}
1498
Kate Stoneb9c1b512016-09-06 20:57:50 +00001499void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1500 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001501}
1502
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503void Debugger::DefaultEventHandler() {
1504 ListenerSP listener_sp(GetListener());
1505 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1506 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1507 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1508 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1509 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001510
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 BroadcastEventSpec process_event_spec(
1512 broadcaster_class_process,
1513 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1514 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001515
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1517 Thread::eBroadcastBitStackChanged |
1518 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001519
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1521 target_event_spec);
1522 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1523 process_event_spec);
1524 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1525 thread_event_spec);
1526 listener_sp->StartListeningForEvents(
1527 m_command_interpreter_ap.get(),
1528 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1529 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1530 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001531
Adrian Prantl05097242018-04-30 16:49:04 +00001532 // Let the thread that spawned us know that we have started up and that we
1533 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001535
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 bool done = false;
1537 while (!done) {
1538 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001539 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001540 if (event_sp) {
1541 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1542 if (broadcaster) {
1543 uint32_t event_type = event_sp->GetType();
1544 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1545 if (broadcaster_class == broadcaster_class_process) {
1546 HandleProcessEvent(event_sp);
1547 } else if (broadcaster_class == broadcaster_class_target) {
1548 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1549 event_sp.get())) {
1550 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552 } else if (broadcaster_class == broadcaster_class_thread) {
1553 HandleThreadEvent(event_sp);
1554 } else if (broadcaster == m_command_interpreter_ap.get()) {
1555 if (event_type &
1556 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1557 done = true;
1558 } else if (event_type &
1559 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1560 const char *data = reinterpret_cast<const char *>(
1561 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1562 if (data && data[0]) {
1563 StreamSP error_sp(GetAsyncErrorStream());
1564 if (error_sp) {
1565 error_sp->PutCString(data);
1566 error_sp->Flush();
1567 }
1568 }
1569 } else if (event_type & CommandInterpreter::
1570 eBroadcastBitAsynchronousOutputData) {
1571 const char *data = reinterpret_cast<const char *>(
1572 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1573 if (data && data[0]) {
1574 StreamSP output_sp(GetAsyncOutputStream());
1575 if (output_sp) {
1576 output_sp->PutCString(data);
1577 output_sp->Flush();
1578 }
1579 }
1580 }
1581 }
Greg Clayton44d93782014-01-27 23:43:24 +00001582 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583
1584 if (m_forward_listener_sp)
1585 m_forward_listener_sp->AddEvent(event_sp);
1586 }
Greg Clayton44d93782014-01-27 23:43:24 +00001587 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588 }
Greg Clayton44d93782014-01-27 23:43:24 +00001589}
1590
Kate Stoneb9c1b512016-09-06 20:57:50 +00001591lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1592 ((Debugger *)arg)->DefaultEventHandler();
1593 return NULL;
Greg Clayton44d93782014-01-27 23:43:24 +00001594}
1595
Kate Stoneb9c1b512016-09-06 20:57:50 +00001596bool Debugger::StartEventHandlerThread() {
1597 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001598 // We must synchronize with the DefaultEventHandler() thread to ensure it
1599 // is up and running and listening to events before we return from this
1600 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001602 ConstString full_name("lldb.debugger.event-handler");
1603 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1605 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001606
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001607 auto thread_name =
1608 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1609 full_name.AsCString() : "dbg.evt-handler";
1610
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 // Use larger 8MB stack for this thread
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001612 m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name,
1613 EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001614
Adrian Prantl05097242018-04-30 16:49:04 +00001615 // Make sure DefaultEventHandler() is running and listening to events
1616 // before we return from this function. We are only listening for events of
1617 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1618 // event, we just need to wait an infinite amount of time for it (nullptr
1619 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001621 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622 }
1623 return m_event_handler_thread.IsJoinable();
1624}
1625
1626void Debugger::StopEventHandlerThread() {
1627 if (m_event_handler_thread.IsJoinable()) {
1628 GetCommandInterpreter().BroadcastEvent(
1629 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1630 m_event_handler_thread.Join(nullptr);
1631 }
1632}
1633
1634lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1635 Debugger *debugger = (Debugger *)arg;
1636 debugger->ExecuteIOHandlers();
1637 debugger->StopEventHandlerThread();
1638 return NULL;
1639}
1640
1641bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1642
1643bool Debugger::StartIOHandlerThread() {
1644 if (!m_io_handler_thread.IsJoinable())
1645 m_io_handler_thread = ThreadLauncher::LaunchThread(
1646 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1647 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1648 return m_io_handler_thread.IsJoinable();
1649}
1650
1651void Debugger::StopIOHandlerThread() {
1652 if (m_io_handler_thread.IsJoinable()) {
1653 if (m_input_file_sp)
1654 m_input_file_sp->GetFile().Close();
1655 m_io_handler_thread.Join(nullptr);
1656 }
1657}
1658
1659void Debugger::JoinIOHandlerThread() {
1660 if (HasIOHandlerThread()) {
1661 thread_result_t result;
1662 m_io_handler_thread.Join(&result);
1663 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1664 }
1665}
1666
1667Target *Debugger::GetDummyTarget() {
1668 return m_target_list.GetDummyTarget(*this).get();
1669}
1670
1671Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1672 Target *target = nullptr;
1673 if (!prefer_dummy) {
1674 target = m_target_list.GetSelectedTarget().get();
1675 if (target)
1676 return target;
1677 }
1678
1679 return GetDummyTarget();
1680}
1681
Zachary Turner97206d52017-05-12 04:51:55 +00001682Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1683 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001684 FileSpec repl_executable;
1685
1686 if (language == eLanguageTypeUnknown) {
1687 std::set<LanguageType> repl_languages;
1688
1689 Language::GetLanguagesSupportingREPLs(repl_languages);
1690
1691 if (repl_languages.size() == 1) {
1692 language = *repl_languages.begin();
1693 } else if (repl_languages.empty()) {
1694 err.SetErrorStringWithFormat(
1695 "LLDB isn't configured with REPL support for any languages.");
1696 return err;
1697 } else {
1698 err.SetErrorStringWithFormat(
1699 "Multiple possible REPL languages. Please specify a language.");
1700 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001701 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702 }
Greg Clayton44d93782014-01-27 23:43:24 +00001703
Kate Stoneb9c1b512016-09-06 20:57:50 +00001704 Target *const target =
1705 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001706
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001708
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001710 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 }
1712
1713 if (!repl_sp) {
1714 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1715 Language::GetNameForLanguageType(language));
1716 return err;
1717 }
1718
1719 repl_sp->SetCompilerOptions(repl_options);
1720 repl_sp->RunLoop();
1721
1722 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001723}