blob: 1aeec7bdb7943b5eadd88217246c3f04af85ab23 [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"
281 "information for threads from thread backtrace unique."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000282 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, {}, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000283
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284enum {
285 ePropertyAutoConfirm = 0,
286 ePropertyDisassemblyFormat,
287 ePropertyFrameFormat,
288 ePropertyNotiftVoid,
289 ePropertyPrompt,
290 ePropertyScriptLanguage,
291 ePropertyStopDisassemblyCount,
292 ePropertyStopDisassemblyDisplay,
293 ePropertyStopLineCountAfter,
294 ePropertyStopLineCountBefore,
Raphael Isemann566afa02018-08-02 00:30:15 +0000295 ePropertyHighlightSource,
Todd Fiala9666ba72016-09-21 20:13:14 +0000296 ePropertyStopShowColumn,
297 ePropertyStopShowColumnAnsiPrefix,
298 ePropertyStopShowColumnAnsiSuffix,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 ePropertyTerminalWidth,
300 ePropertyThreadFormat,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000301 ePropertyThreadStopFormat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 ePropertyUseExternalEditor,
303 ePropertyUseColor,
304 ePropertyAutoOneLineSummaries,
305 ePropertyAutoIndent,
306 ePropertyPrintDecls,
307 ePropertyTabSize,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000308 ePropertyEscapeNonPrintables,
309 ePropertyFrameFormatUnique,
Greg Clayton67cc0632012-08-22 17:17:09 +0000310};
311
Eugene Zelenkodf370552016-03-02 02:18:18 +0000312LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000313
Zachary Turner97206d52017-05-12 04:51:55 +0000314Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
315 VarSetOperationType op,
316 llvm::StringRef property_path,
317 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000318 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
319 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 TargetSP target_sp;
321 LoadScriptFromSymFile load_script_old_value;
322 if (is_load_script && exe_ctx->GetTargetSP()) {
323 target_sp = exe_ctx->GetTargetSP();
324 load_script_old_value =
325 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
326 }
Zachary Turner97206d52017-05-12 04:51:55 +0000327 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (error.Success()) {
329 // FIXME it would be nice to have "on-change" callbacks for properties
Zachary Turner31d97a52016-11-17 18:08:12 +0000330 if (property_path == g_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000331 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
333 new_prompt, GetUseColor());
334 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000335 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000337 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
338 auto prompt_change_event_sp = std::make_shared<Event>(
339 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Zachary Turner31d97a52016-11-17 18:08:12 +0000341 } else if (property_path == g_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 // use-color changed. Ping the prompt so it can reset the ansi terminal
343 // codes.
344 SetPrompt(GetPrompt());
345 } else if (is_load_script && target_sp &&
346 load_script_old_value == eLoadScriptFromSymFileWarn) {
347 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
348 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000349 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 StreamString feedback_stream;
351 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
352 StreamFileSP stream_sp(GetErrorFile());
353 if (stream_sp) {
354 for (auto error : errors) {
355 stream_sp->Printf("%s\n", error.AsCString());
356 }
357 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000358 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 }
360 }
361 }
362 } else if (is_escape_non_printables) {
363 DataVisualization::ForceUpdate();
364 }
365 }
366 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369bool Debugger::GetAutoConfirm() const {
370 const uint32_t idx = ePropertyAutoConfirm;
371 return m_collection_sp->GetPropertyAtIndexAsBoolean(
372 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000373}
374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
376 const uint32_t idx = ePropertyDisassemblyFormat;
377 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000378}
379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380const FormatEntity::Entry *Debugger::GetFrameFormat() const {
381 const uint32_t idx = ePropertyFrameFormat;
382 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000383}
384
Pavel Labath7f1c1212017-06-12 16:25:24 +0000385const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
386 const uint32_t idx = ePropertyFrameFormatUnique;
387 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
388}
389
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390bool Debugger::GetNotifyVoid() const {
391 const uint32_t idx = ePropertyNotiftVoid;
392 return m_collection_sp->GetPropertyAtIndexAsBoolean(
393 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000394}
395
Zachary Turner514d8cd2016-09-23 18:06:53 +0000396llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 const uint32_t idx = ePropertyPrompt;
398 return m_collection_sp->GetPropertyAtIndexAsString(
399 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000400}
401
Zachary Turner514d8cd2016-09-23 18:06:53 +0000402void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 const uint32_t idx = ePropertyPrompt;
404 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000405 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 std::string str =
407 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
408 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000409 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000411}
412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413const FormatEntity::Entry *Debugger::GetThreadFormat() const {
414 const uint32_t idx = ePropertyThreadFormat;
415 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000416}
417
Jim Ingham6a9767c2016-11-08 20:36:40 +0000418const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
419 const uint32_t idx = ePropertyThreadStopFormat;
420 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
421}
422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
424 const uint32_t idx = ePropertyScriptLanguage;
425 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
426 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000427}
428
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
430 const uint32_t idx = ePropertyScriptLanguage;
431 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
432 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000433}
434
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435uint32_t Debugger::GetTerminalWidth() const {
436 const uint32_t idx = ePropertyTerminalWidth;
437 return m_collection_sp->GetPropertyAtIndexAsSInt64(
438 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000439}
440
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441bool Debugger::SetTerminalWidth(uint32_t term_width) {
442 const uint32_t idx = ePropertyTerminalWidth;
443 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000444}
445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446bool Debugger::GetUseExternalEditor() const {
447 const uint32_t idx = ePropertyUseExternalEditor;
448 return m_collection_sp->GetPropertyAtIndexAsBoolean(
449 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000450}
Greg Claytone372b982011-11-21 21:44:34 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452bool Debugger::SetUseExternalEditor(bool b) {
453 const uint32_t idx = ePropertyUseExternalEditor;
454 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000455}
Enrico Granata553fad52013-10-25 23:09:40 +0000456
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457bool Debugger::GetUseColor() const {
458 const uint32_t idx = ePropertyUseColor;
459 return m_collection_sp->GetPropertyAtIndexAsBoolean(
460 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000461}
462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463bool Debugger::SetUseColor(bool b) {
464 const uint32_t idx = ePropertyUseColor;
465 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
466 SetPrompt(GetPrompt());
467 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000468}
469
Raphael Isemann566afa02018-08-02 00:30:15 +0000470bool Debugger::GetHighlightSource() const {
471 const uint32_t idx = ePropertyHighlightSource;
472 return m_collection_sp->GetPropertyAtIndexAsBoolean(
473 nullptr, idx, g_properties[idx].default_uint_value);
474}
475
Todd Fiala9666ba72016-09-21 20:13:14 +0000476StopShowColumn Debugger::GetStopShowColumn() const {
477 const uint32_t idx = ePropertyStopShowColumn;
478 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
479 nullptr, idx, g_properties[idx].default_uint_value);
480}
481
Raphael Isemann20786322018-08-30 00:09:21 +0000482llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000483 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000484 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000485}
486
Raphael Isemann20786322018-08-30 00:09:21 +0000487llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000488 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000489 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000490}
491
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492uint32_t Debugger::GetStopSourceLineCount(bool before) const {
493 const uint32_t idx =
494 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
495 return m_collection_sp->GetPropertyAtIndexAsSInt64(
496 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000497}
498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
500 const uint32_t idx = ePropertyStopDisassemblyDisplay;
501 return (Debugger::StopDisassemblyType)
502 m_collection_sp->GetPropertyAtIndexAsEnumeration(
503 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000504}
505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506uint32_t Debugger::GetDisassemblyLineCount() const {
507 const uint32_t idx = ePropertyStopDisassemblyCount;
508 return m_collection_sp->GetPropertyAtIndexAsSInt64(
509 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000510}
511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512bool Debugger::GetAutoOneLineSummaries() const {
513 const uint32_t idx = ePropertyAutoOneLineSummaries;
514 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000515}
516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517bool Debugger::GetEscapeNonPrintables() const {
518 const uint32_t idx = ePropertyEscapeNonPrintables;
519 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
520}
521
522bool Debugger::GetAutoIndent() const {
523 const uint32_t idx = ePropertyAutoIndent;
524 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
525}
526
527bool Debugger::SetAutoIndent(bool b) {
528 const uint32_t idx = ePropertyAutoIndent;
529 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
530}
531
532bool Debugger::GetPrintDecls() const {
533 const uint32_t idx = ePropertyPrintDecls;
534 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
535}
536
537bool Debugger::SetPrintDecls(bool b) {
538 const uint32_t idx = ePropertyPrintDecls;
539 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
540}
541
542uint32_t Debugger::GetTabSize() const {
543 const uint32_t idx = ePropertyTabSize;
544 return m_collection_sp->GetPropertyAtIndexAsUInt64(
545 nullptr, idx, g_properties[idx].default_uint_value);
546}
547
548bool Debugger::SetTabSize(uint32_t tab_size) {
549 const uint32_t idx = ePropertyTabSize;
550 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000551}
552
Greg Clayton1b654882010-09-19 02:33:57 +0000553#pragma mark Debugger
554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555// const DebuggerPropertiesSP &
556// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000557//{
558// return m_properties_sp;
559//}
560//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
563 assert(g_debugger_list_ptr == nullptr &&
564 "Debugger::Initialize called more than once!");
565 g_debugger_list_mutex_ptr = new std::recursive_mutex();
566 g_debugger_list_ptr = new DebuggerList();
567 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000568}
569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570void Debugger::Terminate() {
571 assert(g_debugger_list_ptr &&
572 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
575 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000576 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
578 for (const auto &debugger : *g_debugger_list_ptr)
579 debugger->Clear();
580 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583}
584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000586
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000588
Zachary Turner97206d52017-05-12 04:51:55 +0000589bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 if (g_load_plugin_callback) {
591 llvm::sys::DynamicLibrary dynlib =
592 g_load_plugin_callback(shared_from_this(), spec, error);
593 if (dynlib.isValid()) {
594 m_loaded_plugins.push_back(dynlib);
595 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000596 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000598 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
599 // if the public API layer isn't available (code is linking against all of
600 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601 error.SetErrorString("Public API layer is not available");
602 }
603 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000604}
605
606static FileSpec::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000607LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 const FileSpec &file_spec) {
Zachary Turner97206d52017-05-12 04:51:55 +0000609 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000610
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000611 static ConstString g_dylibext(".dylib");
612 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613
614 if (!baton)
615 return FileSpec::eEnumerateDirectoryResultQuit;
616
617 Debugger *debugger = (Debugger *)baton;
618
Zachary Turner7d86ee52017-03-08 17:56:08 +0000619 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000620 // If we have a regular file, a symbolic link or unknown file type, try and
621 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 // enumeration might be enumerating a file system that doesn't have correct
623 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000624 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
625 ft == fs::file_type::type_unknown) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 FileSpec plugin_file_spec(file_spec);
627 plugin_file_spec.ResolvePath();
628
629 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
630 plugin_file_spec.GetFileNameExtension() != g_solibext) {
631 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000632 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633
Zachary Turner97206d52017-05-12 04:51:55 +0000634 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
636
Enrico Granata21dfcd92012-09-28 23:57:51 +0000637 return FileSpec::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000638 } else if (ft == fs::file_type::directory_file ||
639 ft == fs::file_type::symlink_file ||
640 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000641 // Try and recurse into anything that a directory or symbolic link. We must
642 // also do this for unknown as sometimes the directory enumeration might be
643 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 // information.
645 return FileSpec::eEnumerateDirectoryResultEnter;
646 }
647
648 return FileSpec::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000649}
650
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 const bool find_directories = true;
653 const bool find_files = true;
654 const bool find_other = true;
655 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000656 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
658 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
659 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000660 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000662
Pavel Labath60f028f2018-06-19 15:09:07 +0000663 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) {
665 FileSpec::EnumerateDirectory(dir_path, find_directories, find_files,
666 find_other, LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000667 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 }
669
670 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000671}
672
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
674 void *baton) {
675 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
676 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
677 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
678 g_debugger_list_ptr->push_back(debugger_sp);
679 }
680 debugger_sp->InstanceInitialize();
681 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000682}
683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684void Debugger::Destroy(DebuggerSP &debugger_sp) {
685 if (!debugger_sp)
686 return;
687
688 debugger_sp->Clear();
689
690 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
691 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
692 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
693 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
694 if ((*pos).get() == debugger_sp.get()) {
695 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000696 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000698 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000700}
701
Greg Clayton4d122c42011-09-17 08:33:22 +0000702DebuggerSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
704 DebuggerSP debugger_sp;
705 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
706 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
707 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
708 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
709 if ((*pos)->m_instance_name == instance_name) {
710 debugger_sp = *pos;
711 break;
712 }
Greg Clayton6920b522012-08-22 18:39:03 +0000713 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 }
715 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000716}
Greg Clayton66111032010-06-23 01:19:29 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
719 TargetSP target_sp;
720 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
721 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
722 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
723 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
724 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
725 if (target_sp)
726 break;
Greg Clayton66111032010-06-23 01:19:29 +0000727 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 }
729 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000730}
731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732TargetSP Debugger::FindTargetWithProcess(Process *process) {
733 TargetSP target_sp;
734 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
735 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
736 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
737 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
738 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
739 if (target_sp)
740 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000741 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 }
743 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000744}
745
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
747 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000748 Properties(std::make_shared<OptionValueProperties>()),
749 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
750 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
751 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
753 m_terminal_state(), m_target_list(*this), m_platform_list(),
754 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
755 m_source_manager_ap(), m_source_file_cache(),
Zachary Turner2f3df612017-04-06 21:28:29 +0000756 m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>(
757 *this, eScriptLanguageDefault, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
759 m_event_handler_thread(), m_io_handler_thread(),
760 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
761 m_forward_listener_sp(), m_clear_once() {
762 char instance_cstr[256];
763 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
764 m_instance_name.SetCString(instance_cstr);
765 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000766 m_log_callback_stream_sp =
767 std::make_shared<StreamCallback>(log_callback, baton);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 m_command_interpreter_ap->Initialize();
769 // Always add our default platform to the platform list
770 PlatformSP default_platform_sp(Platform::GetHostPlatform());
771 assert(default_platform_sp);
772 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000773
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774 m_collection_sp->Initialize(g_properties);
775 m_collection_sp->AppendProperty(
776 ConstString("target"),
777 ConstString("Settings specify to debugging targets."), true,
778 Target::GetGlobalProperties()->GetValueProperties());
779 m_collection_sp->AppendProperty(
780 ConstString("platform"), ConstString("Platform settings."), true,
781 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000782 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000783 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
784 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 if (m_command_interpreter_ap) {
786 m_collection_sp->AppendProperty(
787 ConstString("interpreter"),
788 ConstString("Settings specify to the debugger's command interpreter."),
789 true, m_command_interpreter_ap->GetValueProperties());
790 }
791 OptionValueSInt64 *term_width =
792 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
793 nullptr, ePropertyTerminalWidth);
794 term_width->SetMinimumValue(10);
795 term_width->SetMaximumValue(1024);
796
797 // Turn off use-color if this is a dumb terminal.
798 const char *term = getenv("TERM");
799 if (term && !strcmp(term, "dumb"))
800 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000801 // Turn off use-color if we don't write to a terminal with color support.
802 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
803 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000804
805#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
806 // Enabling use of ANSI color codes because LLDB is using them to highlight
807 // text.
808 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000809#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810}
811
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000813
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814void Debugger::Clear() {
815 //----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000816 // Make sure we call this function only once. With the C++ global destructor
817 // chain having a list of debuggers and with code that can be running on
818 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 //
820 // The following functions call Debugger::Clear():
821 // Debugger::~Debugger();
822 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
823 // static void Debugger::Terminate();
824 //----------------------------------------------------------------------
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000825 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000826 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 StopIOHandlerThread();
828 StopEventHandlerThread();
829 m_listener_sp->Clear();
830 int num_targets = m_target_list.GetNumTargets();
831 for (int i = 0; i < num_targets; i++) {
832 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
833 if (target_sp) {
834 ProcessSP process_sp(target_sp->GetProcessSP());
835 if (process_sp)
836 process_sp->Finalize();
837 target_sp->Destroy();
838 }
Greg Clayton577508d2014-06-20 00:23:57 +0000839 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840 m_broadcaster_manager_sp->Clear();
841
842 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000843 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 m_terminal_state.Clear();
845 if (m_input_file_sp)
846 m_input_file_sp->GetFile().Close();
847
848 m_command_interpreter_ap->Clear();
849 });
Greg Clayton44d93782014-01-27 23:43:24 +0000850}
851
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852bool Debugger::GetCloseInputOnEOF() const {
853 // return m_input_comm.GetCloseOnEOF();
854 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000855}
856
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857void Debugger::SetCloseInputOnEOF(bool b) {
858 // m_input_comm.SetCloseOnEOF(b);
859}
860
861bool Debugger::GetAsyncExecution() {
862 return !m_command_interpreter_ap->GetSynchronous();
863}
864
865void Debugger::SetAsyncExecution(bool async_execution) {
866 m_command_interpreter_ap->SetSynchronous(!async_execution);
867}
868
869void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
870 if (m_input_file_sp)
871 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
872 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000873 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874
875 File &in_file = m_input_file_sp->GetFile();
876 if (!in_file.IsValid())
877 in_file.SetStream(stdin, true);
878
Adrian Prantl05097242018-04-30 16:49:04 +0000879 // Save away the terminal state if that is relevant, so that we can restore
880 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 SaveInputTerminalState();
882}
883
884void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
885 if (m_output_file_sp)
886 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
887 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000888 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889
890 File &out_file = m_output_file_sp->GetFile();
891 if (!out_file.IsValid())
892 out_file.SetStream(stdout, false);
893
Adrian Prantl05097242018-04-30 16:49:04 +0000894 // do not create the ScriptInterpreter just for setting the output file
895 // handle as the constructor will know how to do the right thing on its own
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 const bool can_create = false;
897 ScriptInterpreter *script_interpreter =
898 GetCommandInterpreter().GetScriptInterpreter(can_create);
899 if (script_interpreter)
900 script_interpreter->ResetOutputFileHandle(fh);
901}
902
903void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
904 if (m_error_file_sp)
905 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
906 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000907 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908
909 File &err_file = m_error_file_sp->GetFile();
910 if (!err_file.IsValid())
911 err_file.SetStream(stderr, false);
912}
913
914void Debugger::SaveInputTerminalState() {
915 if (m_input_file_sp) {
916 File &in_file = m_input_file_sp->GetFile();
917 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
918 m_terminal_state.Save(in_file.GetDescriptor(), true);
919 }
920}
921
922void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
923
924ExecutionContext Debugger::GetSelectedExecutionContext() {
925 ExecutionContext exe_ctx;
926 TargetSP target_sp(GetSelectedTarget());
927 exe_ctx.SetTargetSP(target_sp);
928
929 if (target_sp) {
930 ProcessSP process_sp(target_sp->GetProcessSP());
931 exe_ctx.SetProcessSP(process_sp);
932 if (process_sp && !process_sp->IsRunning()) {
933 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
934 if (thread_sp) {
935 exe_ctx.SetThreadSP(thread_sp);
936 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
937 if (exe_ctx.GetFramePtr() == nullptr)
938 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
939 }
940 }
941 }
942 return exe_ctx;
943}
944
945void Debugger::DispatchInputInterrupt() {
946 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
947 IOHandlerSP reader_sp(m_input_reader_stack.Top());
948 if (reader_sp)
949 reader_sp->Interrupt();
950}
951
952void Debugger::DispatchInputEndOfFile() {
953 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
954 IOHandlerSP reader_sp(m_input_reader_stack.Top());
955 if (reader_sp)
956 reader_sp->GotEOF();
957}
958
959void Debugger::ClearIOHandlers() {
960 // The bottom input reader should be the main debugger input reader. We do
961 // not want to close that one here.
962 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
963 while (m_input_reader_stack.GetSize() > 1) {
964 IOHandlerSP reader_sp(m_input_reader_stack.Top());
965 if (reader_sp)
966 PopIOHandler(reader_sp);
967 }
968}
969
970void Debugger::ExecuteIOHandlers() {
971 while (true) {
972 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000975
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000977
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 // Remove all input readers that are done from the top of the stack
979 while (true) {
980 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
981 if (top_reader_sp && top_reader_sp->GetIsDone())
982 PopIOHandler(top_reader_sp);
983 else
984 break;
985 }
986 }
987 ClearIOHandlers();
988}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
991 return m_input_reader_stack.IsTop(reader_sp);
992}
Greg Clayton44d93782014-01-27 23:43:24 +0000993
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
995 IOHandler::Type second_top_type) {
996 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
997}
998
999void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1000 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
1001 m_input_reader_stack.PrintAsync(stream.get(), s, len);
1002}
1003
1004ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1005 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
1006}
1007
1008const char *Debugger::GetIOHandlerCommandPrefix() {
1009 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
1010}
1011
1012const char *Debugger::GetIOHandlerHelpPrologue() {
1013 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1014}
1015
1016void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1017 PushIOHandler(reader_sp);
1018
1019 IOHandlerSP top_reader_sp = reader_sp;
1020 while (top_reader_sp) {
1021 top_reader_sp->Run();
1022
1023 if (top_reader_sp.get() == reader_sp.get()) {
1024 if (PopIOHandler(reader_sp))
1025 break;
1026 }
1027
1028 while (true) {
1029 top_reader_sp = m_input_reader_stack.Top();
1030 if (top_reader_sp && top_reader_sp->GetIsDone())
1031 PopIOHandler(top_reader_sp);
1032 else
1033 break;
1034 }
1035 }
1036}
1037
1038void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1039 StreamFileSP &out,
1040 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +00001041 // Before an IOHandler runs, it must have in/out/err streams. This function
1042 // is called when one ore more of the streams are nullptr. We use the top
1043 // input reader's in/out/err streams, or fall back to the debugger file
1044 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045
1046 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1047 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1048 // If no STDIN has been set, then set it appropriately
1049 if (!in) {
1050 if (top_reader_sp)
1051 in = top_reader_sp->GetInputStreamFile();
1052 else
1053 in = GetInputFile();
1054
1055 // If there is nothing, use stdin
1056 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001057 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 }
1059 // If no STDOUT has been set, then set it appropriately
1060 if (!out) {
1061 if (top_reader_sp)
1062 out = top_reader_sp->GetOutputStreamFile();
1063 else
1064 out = GetOutputFile();
1065
1066 // If there is nothing, use stdout
1067 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001068 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 }
1070 // If no STDERR has been set, then set it appropriately
1071 if (!err) {
1072 if (top_reader_sp)
1073 err = top_reader_sp->GetErrorStreamFile();
1074 else
1075 err = GetErrorFile();
1076
1077 // If there is nothing, use stderr
1078 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001079 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 }
1081}
1082
Raphael Isemannc01783a2018-08-29 22:50:54 +00001083void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1084 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 if (!reader_sp)
1086 return;
1087
1088 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1089
1090 // Get the current top input reader...
1091 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1092
1093 // Don't push the same IO handler twice...
1094 if (reader_sp == top_reader_sp)
1095 return;
1096
1097 // Push our new input reader
1098 m_input_reader_stack.Push(reader_sp);
1099 reader_sp->Activate();
1100
Adrian Prantl05097242018-04-30 16:49:04 +00001101 // Interrupt the top input reader to it will exit its Run() function and let
1102 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 if (top_reader_sp) {
1104 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001105 if (cancel_top_handler)
1106 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 }
1108}
1109
1110bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1111 if (!pop_reader_sp)
1112 return false;
1113
1114 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1115
Adrian Prantl05097242018-04-30 16:49:04 +00001116 // The reader on the stop of the stack is done, so let the next read on the
1117 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 if (m_input_reader_stack.IsEmpty())
1119 return false;
1120
1121 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1122
1123 if (pop_reader_sp != reader_sp)
1124 return false;
1125
1126 reader_sp->Deactivate();
1127 reader_sp->Cancel();
1128 m_input_reader_stack.Pop();
1129
1130 reader_sp = m_input_reader_stack.Top();
1131 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001132 reader_sp->Activate();
1133
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 return true;
1135}
1136
1137StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001138 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139}
1140
1141StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001142 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143}
1144
1145size_t Debugger::GetNumDebuggers() {
1146 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1147 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1148 return g_debugger_list_ptr->size();
1149 }
1150 return 0;
1151}
1152
1153lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1154 DebuggerSP debugger_sp;
1155
1156 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1157 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1158 if (index < g_debugger_list_ptr->size())
1159 debugger_sp = g_debugger_list_ptr->at(index);
1160 }
1161
1162 return debugger_sp;
1163}
1164
1165DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1166 DebuggerSP debugger_sp;
1167
1168 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1169 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1170 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1171 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1172 if ((*pos)->GetID() == id) {
1173 debugger_sp = *pos;
1174 break;
1175 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001176 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 }
1178 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001179}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001180
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1182 const SymbolContext *sc,
1183 const SymbolContext *prev_sc,
1184 const ExecutionContext *exe_ctx,
1185 const Address *addr, Stream &s) {
1186 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001187
Kate Stoneb9c1b512016-09-06 20:57:50 +00001188 if (format == nullptr) {
1189 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1190 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1191 if (format == nullptr) {
1192 FormatEntity::Parse("${addr}: ", format_entry);
1193 format = &format_entry;
1194 }
1195 }
1196 bool function_changed = false;
1197 bool initial_function = false;
1198 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1199 if (sc && (sc->function || sc->symbol)) {
1200 if (prev_sc->symbol && sc->symbol) {
1201 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1202 prev_sc->symbol->GetType())) {
1203 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001204 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 } else if (prev_sc->function && sc->function) {
1206 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1207 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001208 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001210 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 }
Adrian Prantl05097242018-04-30 16:49:04 +00001212 // The first context on a list of instructions will have a prev_sc that has
1213 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 // would return false. But we do get a prev_sc pointer.
1215 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1216 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1217 initial_function = true;
1218 }
1219 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1220 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001221}
1222
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1224 void *baton) {
1225 // For simplicity's sake, I am not going to deal with how to close down any
1226 // open logging streams, I just redirect everything from here on out to the
1227 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001228 m_log_callback_stream_sp =
1229 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001230}
1231
Pavel Labath5e336902017-03-01 10:08:40 +00001232bool Debugger::EnableLog(llvm::StringRef channel,
1233 llvm::ArrayRef<const char *> categories,
1234 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001235 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001236 const bool should_close = true;
1237 const bool unbuffered = true;
1238
1239 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 if (m_log_callback_stream_sp) {
1241 log_stream_sp = m_log_callback_stream_sp;
1242 // For now when using the callback mode you always get thread & timestamp.
1243 log_options |=
1244 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001245 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001246 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1247 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001249 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 if (pos != m_log_streams.end())
1251 log_stream_sp = pos->second.lock();
1252 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001253 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1254 if (log_options & LLDB_LOG_OPTION_APPEND)
1255 flags |= llvm::sys::fs::F_Append;
1256 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001257 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1258 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001259 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001260 return false;
1261 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001262 log_stream_sp =
1263 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001265 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 }
1267 assert(log_stream_sp);
1268
1269 if (log_options == 0)
1270 log_options =
1271 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1272
1273 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1274 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001275}
1276
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277SourceManager &Debugger::GetSourceManager() {
1278 if (!m_source_manager_ap)
Zachary Turner2f3df612017-04-06 21:28:29 +00001279 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 return *m_source_manager_ap;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001281}
1282
Greg Clayton44d93782014-01-27 23:43:24 +00001283// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1285 using namespace lldb;
1286 const uint32_t event_type =
1287 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1288 event_sp);
1289
1290 // if (event_type & eBreakpointEventTypeAdded
1291 // || event_type & eBreakpointEventTypeRemoved
1292 // || event_type & eBreakpointEventTypeEnabled
1293 // || event_type & eBreakpointEventTypeDisabled
1294 // || event_type & eBreakpointEventTypeCommandChanged
1295 // || event_type & eBreakpointEventTypeConditionChanged
1296 // || event_type & eBreakpointEventTypeIgnoreChanged
1297 // || event_type & eBreakpointEventTypeLocationsResolved)
1298 // {
1299 // // Don't do anything about these events, since the breakpoint
1300 // commands already echo these actions.
1301 // }
1302 //
1303 if (event_type & eBreakpointEventTypeLocationsAdded) {
1304 uint32_t num_new_locations =
1305 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1306 event_sp);
1307 if (num_new_locations > 0) {
1308 BreakpointSP breakpoint =
1309 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1310 StreamSP output_sp(GetAsyncOutputStream());
1311 if (output_sp) {
1312 output_sp->Printf("%d location%s added to breakpoint %d\n",
1313 num_new_locations, num_new_locations == 1 ? "" : "s",
1314 breakpoint->GetID());
1315 output_sp->Flush();
1316 }
Greg Clayton44d93782014-01-27 23:43:24 +00001317 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001318 }
1319 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1320 // {
1321 // // These locations just get disabled, not sure it is worth spamming
1322 // folks about this on the command line.
1323 // }
1324 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1325 // {
1326 // // This might be an interesting thing to note, but I'm going to
1327 // leave it quiet for now, it just looked noisy.
1328 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001329}
1330
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1332 size_t total_bytes = 0;
1333 if (stream == nullptr)
1334 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001335
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 if (stream) {
1337 // The process has stuff waiting for stdout; get it and write it out to the
1338 // appropriate place.
1339 if (process == nullptr) {
1340 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1341 if (target_sp)
1342 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001343 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001345 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346 size_t len;
1347 char stdio_buffer[1024];
1348 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1349 error)) > 0) {
1350 stream->Write(stdio_buffer, len);
1351 total_bytes += len;
1352 }
1353 }
1354 stream->Flush();
1355 }
1356 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001357}
1358
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1360 size_t total_bytes = 0;
1361 if (stream == nullptr)
1362 stream = GetOutputFile().get();
1363
1364 if (stream) {
1365 // The process has stuff waiting for stderr; get it and write it out to the
1366 // appropriate place.
1367 if (process == nullptr) {
1368 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1369 if (target_sp)
1370 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001371 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001373 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374 size_t len;
1375 char stdio_buffer[1024];
1376 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1377 error)) > 0) {
1378 stream->Write(stdio_buffer, len);
1379 total_bytes += len;
1380 }
1381 }
1382 stream->Flush();
1383 }
1384 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001385}
1386
1387// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1389 using namespace lldb;
1390 const uint32_t event_type = event_sp->GetType();
1391 ProcessSP process_sp =
1392 (event_type == Process::eBroadcastBitStructuredData)
1393 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1394 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001395
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396 StreamSP output_stream_sp = GetAsyncOutputStream();
1397 StreamSP error_stream_sp = GetAsyncErrorStream();
1398 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001399
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 if (!gui_enabled) {
1401 bool pop_process_io_handler = false;
1402 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001403
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404 bool state_is_stopped = false;
1405 const bool got_state_changed =
1406 (event_type & Process::eBroadcastBitStateChanged) != 0;
1407 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1408 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1409 const bool got_structured_data =
1410 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001411
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412 if (got_state_changed) {
1413 StateType event_state =
1414 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1415 state_is_stopped = StateIsStoppedState(event_state, false);
1416 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001417
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 // Display running state changes first before any STDIO
1419 if (got_state_changed && !state_is_stopped) {
1420 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1421 pop_process_io_handler);
1422 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 // Now display and STDOUT
1425 if (got_stdout || got_state_changed) {
1426 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1427 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 // Now display and STDERR
1430 if (got_stderr || got_state_changed) {
1431 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1432 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001433
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 // Give structured data events an opportunity to display.
1435 if (got_structured_data) {
1436 StructuredDataPluginSP plugin_sp =
1437 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1438 if (plugin_sp) {
1439 auto structured_data_sp =
1440 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1441 if (output_stream_sp) {
1442 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001443 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 plugin_sp->GetDescription(structured_data_sp, content_stream);
1445 if (error.Success()) {
1446 if (!content_stream.GetString().empty()) {
1447 // Add newline.
1448 content_stream.PutChar('\n');
1449 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001450
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001452 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 } else {
1455 error_stream_sp->Printf("Failed to print structured "
1456 "data with plugin %s: %s",
1457 plugin_sp->GetPluginName().AsCString(),
1458 error.AsCString());
1459 }
Todd Fiala75930012016-08-19 04:21:48 +00001460 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001462 }
Greg Clayton44d93782014-01-27 23:43:24 +00001463
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 // Now display any stopped state changes after any STDIO
1465 if (got_state_changed && state_is_stopped) {
1466 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1467 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469
1470 output_stream_sp->Flush();
1471 error_stream_sp->Flush();
1472
1473 if (pop_process_io_handler)
1474 process_sp->PopProcessIOHandler();
1475 }
Greg Clayton44d93782014-01-27 23:43:24 +00001476}
1477
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001479 // At present the only thread event we handle is the Frame Changed event, and
1480 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 using namespace lldb;
1482 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001483 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 if (event_type == Thread::eBroadcastBitStackChanged ||
1485 event_type == Thread::eBroadcastBitThreadSelected) {
1486 ThreadSP thread_sp(
1487 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1488 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001489 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490 }
1491 }
Greg Clayton44d93782014-01-27 23:43:24 +00001492}
1493
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1495
1496void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1497 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001498}
1499
Kate Stoneb9c1b512016-09-06 20:57:50 +00001500void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1501 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001502}
1503
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504void Debugger::DefaultEventHandler() {
1505 ListenerSP listener_sp(GetListener());
1506 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1507 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1508 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1509 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1510 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001511
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512 BroadcastEventSpec process_event_spec(
1513 broadcaster_class_process,
1514 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1515 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001516
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1518 Thread::eBroadcastBitStackChanged |
1519 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001520
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1522 target_event_spec);
1523 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1524 process_event_spec);
1525 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1526 thread_event_spec);
1527 listener_sp->StartListeningForEvents(
1528 m_command_interpreter_ap.get(),
1529 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1530 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1531 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001532
Adrian Prantl05097242018-04-30 16:49:04 +00001533 // Let the thread that spawned us know that we have started up and that we
1534 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001535 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001536
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537 bool done = false;
1538 while (!done) {
1539 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001540 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 if (event_sp) {
1542 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1543 if (broadcaster) {
1544 uint32_t event_type = event_sp->GetType();
1545 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1546 if (broadcaster_class == broadcaster_class_process) {
1547 HandleProcessEvent(event_sp);
1548 } else if (broadcaster_class == broadcaster_class_target) {
1549 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1550 event_sp.get())) {
1551 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 } else if (broadcaster_class == broadcaster_class_thread) {
1554 HandleThreadEvent(event_sp);
1555 } else if (broadcaster == m_command_interpreter_ap.get()) {
1556 if (event_type &
1557 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1558 done = true;
1559 } else if (event_type &
1560 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1561 const char *data = reinterpret_cast<const char *>(
1562 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1563 if (data && data[0]) {
1564 StreamSP error_sp(GetAsyncErrorStream());
1565 if (error_sp) {
1566 error_sp->PutCString(data);
1567 error_sp->Flush();
1568 }
1569 }
1570 } else if (event_type & CommandInterpreter::
1571 eBroadcastBitAsynchronousOutputData) {
1572 const char *data = reinterpret_cast<const char *>(
1573 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1574 if (data && data[0]) {
1575 StreamSP output_sp(GetAsyncOutputStream());
1576 if (output_sp) {
1577 output_sp->PutCString(data);
1578 output_sp->Flush();
1579 }
1580 }
1581 }
1582 }
Greg Clayton44d93782014-01-27 23:43:24 +00001583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584
1585 if (m_forward_listener_sp)
1586 m_forward_listener_sp->AddEvent(event_sp);
1587 }
Greg Clayton44d93782014-01-27 23:43:24 +00001588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 }
Greg Clayton44d93782014-01-27 23:43:24 +00001590}
1591
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1593 ((Debugger *)arg)->DefaultEventHandler();
1594 return NULL;
Greg Clayton44d93782014-01-27 23:43:24 +00001595}
1596
Kate Stoneb9c1b512016-09-06 20:57:50 +00001597bool Debugger::StartEventHandlerThread() {
1598 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001599 // We must synchronize with the DefaultEventHandler() thread to ensure it
1600 // is up and running and listening to events before we return from this
1601 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001603 ConstString full_name("lldb.debugger.event-handler");
1604 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1606 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001607
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001608 auto thread_name =
1609 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1610 full_name.AsCString() : "dbg.evt-handler";
1611
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612 // Use larger 8MB stack for this thread
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001613 m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name,
1614 EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001615
Adrian Prantl05097242018-04-30 16:49:04 +00001616 // Make sure DefaultEventHandler() is running and listening to events
1617 // before we return from this function. We are only listening for events of
1618 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1619 // event, we just need to wait an infinite amount of time for it (nullptr
1620 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001621 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001622 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 }
1624 return m_event_handler_thread.IsJoinable();
1625}
1626
1627void Debugger::StopEventHandlerThread() {
1628 if (m_event_handler_thread.IsJoinable()) {
1629 GetCommandInterpreter().BroadcastEvent(
1630 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1631 m_event_handler_thread.Join(nullptr);
1632 }
1633}
1634
1635lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1636 Debugger *debugger = (Debugger *)arg;
1637 debugger->ExecuteIOHandlers();
1638 debugger->StopEventHandlerThread();
1639 return NULL;
1640}
1641
1642bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1643
1644bool Debugger::StartIOHandlerThread() {
1645 if (!m_io_handler_thread.IsJoinable())
1646 m_io_handler_thread = ThreadLauncher::LaunchThread(
1647 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1648 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1649 return m_io_handler_thread.IsJoinable();
1650}
1651
1652void Debugger::StopIOHandlerThread() {
1653 if (m_io_handler_thread.IsJoinable()) {
1654 if (m_input_file_sp)
1655 m_input_file_sp->GetFile().Close();
1656 m_io_handler_thread.Join(nullptr);
1657 }
1658}
1659
1660void Debugger::JoinIOHandlerThread() {
1661 if (HasIOHandlerThread()) {
1662 thread_result_t result;
1663 m_io_handler_thread.Join(&result);
1664 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1665 }
1666}
1667
1668Target *Debugger::GetDummyTarget() {
1669 return m_target_list.GetDummyTarget(*this).get();
1670}
1671
1672Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1673 Target *target = nullptr;
1674 if (!prefer_dummy) {
1675 target = m_target_list.GetSelectedTarget().get();
1676 if (target)
1677 return target;
1678 }
1679
1680 return GetDummyTarget();
1681}
1682
Zachary Turner97206d52017-05-12 04:51:55 +00001683Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1684 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 FileSpec repl_executable;
1686
1687 if (language == eLanguageTypeUnknown) {
1688 std::set<LanguageType> repl_languages;
1689
1690 Language::GetLanguagesSupportingREPLs(repl_languages);
1691
1692 if (repl_languages.size() == 1) {
1693 language = *repl_languages.begin();
1694 } else if (repl_languages.empty()) {
1695 err.SetErrorStringWithFormat(
1696 "LLDB isn't configured with REPL support for any languages.");
1697 return err;
1698 } else {
1699 err.SetErrorStringWithFormat(
1700 "Multiple possible REPL languages. Please specify a language.");
1701 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001702 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 }
Greg Clayton44d93782014-01-27 23:43:24 +00001704
Kate Stoneb9c1b512016-09-06 20:57:50 +00001705 Target *const target =
1706 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001707
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001709
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001711 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712 }
1713
1714 if (!repl_sp) {
1715 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1716 Language::GetNameForLanguageType(language));
1717 return err;
1718 }
1719
1720 repl_sp->SetCompilerOptions(repl_options);
1721 repl_sp->RunLoop();
1722
1723 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001724}