blob: 0afdf0690214d07d18792f08ce5bf784815bd749 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Clayton4a33d312011-06-23 17:59:56 +00009#include "lldb/Core/Debugger.h"
10
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000011#include "lldb/Breakpoint/Breakpoint.h"
Greg Clayton554f68d2015-02-04 22:00:53 +000012#include "lldb/Core/FormatEntity.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000013#include "lldb/Core/Mangled.h"
14#include "lldb/Core/ModuleList.h"
Greg Claytone8cd0c92012-10-19 18:02:49 +000015#include "lldb/Core/PluginManager.h"
Jim Ingham5b52f0c2011-06-02 23:58:26 +000016#include "lldb/Core/StreamAsynchronousIO.h"
Greg Clayton44d93782014-01-27 23:43:24 +000017#include "lldb/Core/StreamFile.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000018#include "lldb/DataFormatters/DataVisualization.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000019#include "lldb/Expression/REPL.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000020#include "lldb/Host/File.h"
Jonas Devlieghere35e4c842018-11-01 00:33:27 +000021#include "lldb/Host/FileSystem.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000022#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000023#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000024#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000026#include "lldb/Interpreter/OptionValue.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000027#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000028#include "lldb/Interpreter/OptionValueSInt64.h"
29#include "lldb/Interpreter/OptionValueString.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000030#include "lldb/Interpreter/Property.h"
31#include "lldb/Interpreter/ScriptInterpreter.h"
Greg Clayton1f746072012-08-29 21:13:06 +000032#include "lldb/Symbol/Function.h"
33#include "lldb/Symbol/Symbol.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000034#include "lldb/Symbol/SymbolContext.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000035#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Target/Process.h"
Todd Fiala75930012016-08-19 04:21:48 +000037#include "lldb/Target/StructuredDataPlugin.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000038#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#include "lldb/Target/TargetList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/Thread.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000041#include "lldb/Target/ThreadList.h"
Greg Clayton5a314712011-10-14 07:41:33 +000042#include "lldb/Utility/AnsiTerminal.h"
Pavel Labath181b8232018-12-14 15:59:49 +000043#include "lldb/Utility/Event.h"
44#include "lldb/Utility/Listener.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000045#include "lldb/Utility/Log.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000046#include "lldb/Utility/Reproducer.h"
Pavel Labathd821c992018-08-07 11:07:21 +000047#include "lldb/Utility/State.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000048#include "lldb/Utility/Stream.h"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000049#include "lldb/Utility/StreamCallback.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000050#include "lldb/Utility/StreamString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000051
Nico Weberb1cb0b792018-04-10 13:33:45 +000052#if defined(_WIN32)
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000053#include "lldb/Host/windows/PosixApi.h"
David Bolvansky8aa23612018-09-05 22:06:58 +000054#include "lldb/Host/windows/windows.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000055#endif
56
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000057#include "llvm/ADT/None.h"
58#include "llvm/ADT/STLExtras.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000059#include "llvm/ADT/StringRef.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000060#include "llvm/ADT/iterator.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000061#include "llvm/Support/DynamicLibrary.h"
62#include "llvm/Support/FileSystem.h"
David Bolvansky8aa23612018-09-05 22:06:58 +000063#include "llvm/Support/Process.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000064#include "llvm/Support/Threading.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000065#include "llvm/Support/raw_ostream.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000066
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000067#include <list>
68#include <memory>
Zachary Turner2f3df612017-04-06 21:28:29 +000069#include <mutex>
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000070#include <set>
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#include <string>
75#include <system_error>
Zachary Turner2f3df612017-04-06 21:28:29 +000076
77namespace lldb_private {
78class Address;
79}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080
81using namespace lldb;
82using namespace lldb_private;
83
Caroline Ticeebc1bb22010-06-30 16:22:25 +000084static lldb::user_id_t g_unique_id = 1;
Zachary Turner7c2896a2014-10-24 22:06:29 +000085static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000086
Greg Clayton1b654882010-09-19 02:33:57 +000087#pragma mark Static Functions
88
Greg Clayton1b654882010-09-19 02:33:57 +000089typedef std::vector<DebuggerSP> DebuggerList;
Kate Stoneb9c1b512016-09-06 20:57:50 +000090static std::recursive_mutex *g_debugger_list_mutex_ptr =
91 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
92static DebuggerList *g_debugger_list_ptr =
93 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
Greg Claytone372b982011-11-21 21:44:34 +000094
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000095static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 {Debugger::eStopDisassemblyTypeNever, "never",
97 "Never show disassembly when displaying a stop context."},
98 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
99 "Show disassembly when there is no debug information."},
100 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
101 "Show disassembly when there is no source information, or the source file "
102 "is missing when displaying a stop context."},
103 {Debugger::eStopDisassemblyTypeAlways, "always",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000104 "Always show disassembly when displaying a stop context."} };
Greg Claytone372b982011-11-21 21:44:34 +0000105
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000106static constexpr OptionEnumValueElement g_language_enumerators[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 {eScriptLanguageNone, "none", "Disable scripting languages."},
108 {eScriptLanguagePython, "python",
109 "Select python as the default scripting language."},
110 {eScriptLanguageDefault, "default",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000111 "Select the lldb default as the default scripting language."} };
Greg Claytone372b982011-11-21 21:44:34 +0000112
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113#define MODULE_WITH_FUNC \
114 "{ " \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000115 "${module.file.basename}{`${function.name-with-args}" \
116 "{${frame.no-debug}${function.pc-offset}}}}"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000117
118#define MODULE_WITH_FUNC_NO_ARGS \
119 "{ " \
120 "${module.file.basename}{`${function.name-without-args}" \
121 "{${frame.no-debug}${function.pc-offset}}}}"
122
Adrian Prantl4954f6a2018-09-05 23:52:08 +0000123#define FILE_AND_LINE \
124 "{ at ${line.file.basename}:${line.number}{:${line.column}}}"
Jason Molenda6ab659a2015-07-29 00:42:47 +0000125#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000126
Vedant Kumar4b36f792018-10-05 23:23:15 +0000127#define IS_ARTIFICIAL "{${frame.is-artificial} [artificial]}"
128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129#define DEFAULT_THREAD_FORMAT \
130 "thread #${thread.index}: tid = ${thread.id%tid}" \
131 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
132 "{, name = '${thread.name}'}" \
133 "{, queue = '${thread.queue}'}" \
134 "{, activity = '${thread.info.activity.name}'}" \
135 "{, ${thread.info.trace_messages} messages}" \
136 "{, stop reason = ${thread.stop-reason}}" \
137 "{\\nReturn value: ${thread.return-value}}" \
138 "{\\nCompleted expression: ${thread.completed-expression}}" \
139 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000140
Jim Ingham6a9767c2016-11-08 20:36:40 +0000141#define DEFAULT_THREAD_STOP_FORMAT \
142 "thread #${thread.index}{, name = '${thread.name}'}" \
143 "{, queue = '${thread.queue}'}" \
144 "{, activity = '${thread.info.activity.name}'}" \
145 "{, ${thread.info.trace_messages} messages}" \
146 "{, stop reason = ${thread.stop-reason}}" \
147 "{\\nReturn value: ${thread.return-value}}" \
148 "{\\nCompleted expression: ${thread.completed-expression}}" \
149 "\\n"
150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151#define DEFAULT_FRAME_FORMAT \
Jason Molenda270e8222017-01-28 02:54:10 +0000152 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC FILE_AND_LINE \
Vedant Kumar4b36f792018-10-05 23:23:15 +0000153 IS_OPTIMIZED IS_ARTIFICIAL "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000154
Pavel Labath7f1c1212017-06-12 16:25:24 +0000155#define DEFAULT_FRAME_FORMAT_NO_ARGS \
156 "frame #${frame.index}: ${frame.pc}" MODULE_WITH_FUNC_NO_ARGS FILE_AND_LINE \
Vedant Kumar4b36f792018-10-05 23:23:15 +0000157 IS_OPTIMIZED IS_ARTIFICIAL "\\n"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000158
Jason Molendac980fa92015-02-13 23:24:21 +0000159// Three parts to this disassembly format specification:
160// 1. If this is a new function/symbol (no previous symbol/function), print
161// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162// 2. If this is a symbol context change (different from previous
163// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000164// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165// 3. print
166// address <+offset>:
167#define DEFAULT_DISASSEMBLY_FORMAT \
168 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
Jonas Devliegheree43be152018-10-01 13:20:15 +0000169 "without-args}}:\\n}{${function.changed}\\n{${module.file.basename}`}{${" \
170 "function.name-without-args}}:\\n}{${current-pc-arrow} " \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 "}${addr-file-or-load}{ " \
172 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000173
Adrian Prantl05097242018-04-30 16:49:04 +0000174// gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
175// file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
176// offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000177
178// lldb's original format for disassembly would look like this format string -
Adrian Prantl05097242018-04-30 16:49:04 +0000179// {${function.initial-function}{${module.file.basename}`}{${function.name-
180// without-
181// args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
182// without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000183
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000184static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
Todd Fiala9666ba72016-09-21 20:13:14 +0000185 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
186 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
187 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
188 "\"caret-only\" mode was selected."},
189 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
190 "terminal codes when running LLDB with "
191 "color/ANSI enabled."},
192 {eStopShowColumnCaret, "caret",
193 "Highlight the stop column with a caret character (^) underneath the stop "
194 "column. This method introduces a new line in source listings that "
195 "display thread stop locations."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000196 {eStopShowColumnNone, "none", "Do not highlight the stop column."}};
Todd Fiala9666ba72016-09-21 20:13:14 +0000197
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000198static constexpr PropertyDefinition g_properties[] = {
199 {"auto-confirm", OptionValue::eTypeBoolean, true, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 "If true all confirmation prompts will receive their default reply."},
201 {"disassembly-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000202 DEFAULT_DISASSEMBLY_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000203 "The default disassembly format "
204 "string to use when disassembling "
205 "instruction sequences."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 {"frame-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000207 DEFAULT_FRAME_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000208 "The default frame format string to use "
209 "when displaying stack frame information "
210 "for threads."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000211 {"notify-void", OptionValue::eTypeBoolean, true, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 "Notify the user explicitly if an expression returns void (default: "
213 "false)."},
214 {"prompt", OptionValue::eTypeString, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000215 OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", {},
216 "The debugger command line prompt displayed for the user."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 {"script-lang", OptionValue::eTypeEnum, true, eScriptLanguagePython,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000218 nullptr, OptionEnumValues(g_language_enumerators),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 "The script language to be used for evaluating user-written scripts."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000220 {"stop-disassembly-count", OptionValue::eTypeSInt64, true, 4, nullptr, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000221 "The number of disassembly lines to show when displaying a "
222 "stopped context."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 {"stop-disassembly-display", OptionValue::eTypeEnum, true,
224 Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000225 OptionEnumValues(g_show_disassembly_enum_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 "Control when to display disassembly when displaying a stopped context."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000227 {"stop-line-count-after", OptionValue::eTypeSInt64, true, 3, nullptr, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000228 "The number of sources lines to display that come after the "
229 "current source line when displaying a stopped context."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000230 {"stop-line-count-before", OptionValue::eTypeSInt64, true, 3, nullptr, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000231 "The number of sources lines to display that come before the "
232 "current source line when displaying a stopped context."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000233 {"highlight-source", OptionValue::eTypeBoolean, true, true, nullptr, {},
234 "If true, LLDB will highlight the displayed source code."},
Todd Fiala9666ba72016-09-21 20:13:14 +0000235 {"stop-show-column", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000236 eStopShowColumnAnsiOrCaret, nullptr, OptionEnumValues(s_stop_show_column_values),
Todd Fiala9666ba72016-09-21 20:13:14 +0000237 "If true, LLDB will use the column information from the debug info to "
238 "mark the current position when displaying a stopped context."},
Raphael Isemann20786322018-08-30 00:09:21 +0000239 {"stop-show-column-ansi-prefix", OptionValue::eTypeString, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000240 "${ansi.underline}", {},
Todd Fiala9666ba72016-09-21 20:13:14 +0000241 "When displaying the column marker in a color-enabled (i.e. ANSI) "
242 "terminal, use the ANSI terminal code specified in this format at the "
243 "immediately before the column to be marked."},
Raphael Isemann20786322018-08-30 00:09:21 +0000244 {"stop-show-column-ansi-suffix", OptionValue::eTypeString, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000245 "${ansi.normal}", {},
Todd Fiala9666ba72016-09-21 20:13:14 +0000246 "When displaying the column marker in a color-enabled (i.e. ANSI) "
247 "terminal, use the ANSI terminal code specified in this format "
248 "immediately after the column to be marked."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000249 {"term-width", OptionValue::eTypeSInt64, true, 80, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 "The maximum number of columns to use for displaying text."},
251 {"thread-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000252 DEFAULT_THREAD_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000253 "The default thread format string to use "
254 "when displaying thread information."},
Jim Ingham6a9767c2016-11-08 20:36:40 +0000255 {"thread-stop-format", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000256 DEFAULT_THREAD_STOP_FORMAT, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000257 "The default thread format "
258 "string to use when displaying thread "
259 "information as part of the stop display."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000260 {"use-external-editor", OptionValue::eTypeBoolean, true, false, nullptr, {},
261 "Whether to use an external editor or not."},
262 {"use-color", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263 "Whether to use Ansi color codes or not."},
264 {"auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000265 {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000266 "If true, LLDB will automatically display small structs in "
267 "one-liner format (default: true)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000268 {"auto-indent", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 "If true, LLDB will auto indent/outdent code. Currently only supported in "
270 "the REPL (default: true)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000271 {"print-decls", OptionValue::eTypeBoolean, true, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 "If true, LLDB will print the values of variables declared in an "
273 "expression. Currently only supported in the REPL (default: true)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000274 {"tab-size", OptionValue::eTypeUInt64, true, 4, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 "The tab size to use when indenting code in multi-line input mode "
276 "(default: 4)."},
277 {"escape-non-printables", OptionValue::eTypeBoolean, true, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000278 {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000279 "If true, LLDB will automatically escape non-printable and "
280 "escape characters when formatting strings."},
281 {"frame-format-unique", OptionValue::eTypeFormatEntity, true, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000282 DEFAULT_FRAME_FORMAT_NO_ARGS, {},
Pavel Labath7f1c1212017-06-12 16:25:24 +0000283 "The default frame format string to use when displaying stack frame"
Tatyana Krasnukhae40db052018-09-27 07:11:58 +0000284 "information for threads from thread backtrace unique."}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000285
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286enum {
287 ePropertyAutoConfirm = 0,
288 ePropertyDisassemblyFormat,
289 ePropertyFrameFormat,
290 ePropertyNotiftVoid,
291 ePropertyPrompt,
292 ePropertyScriptLanguage,
293 ePropertyStopDisassemblyCount,
294 ePropertyStopDisassemblyDisplay,
295 ePropertyStopLineCountAfter,
296 ePropertyStopLineCountBefore,
Raphael Isemann566afa02018-08-02 00:30:15 +0000297 ePropertyHighlightSource,
Todd Fiala9666ba72016-09-21 20:13:14 +0000298 ePropertyStopShowColumn,
299 ePropertyStopShowColumnAnsiPrefix,
300 ePropertyStopShowColumnAnsiSuffix,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 ePropertyTerminalWidth,
302 ePropertyThreadFormat,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000303 ePropertyThreadStopFormat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 ePropertyUseExternalEditor,
305 ePropertyUseColor,
306 ePropertyAutoOneLineSummaries,
307 ePropertyAutoIndent,
308 ePropertyPrintDecls,
309 ePropertyTabSize,
Pavel Labath7f1c1212017-06-12 16:25:24 +0000310 ePropertyEscapeNonPrintables,
311 ePropertyFrameFormatUnique,
Greg Clayton67cc0632012-08-22 17:17:09 +0000312};
313
Eugene Zelenkodf370552016-03-02 02:18:18 +0000314LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000315
Zachary Turner97206d52017-05-12 04:51:55 +0000316Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
317 VarSetOperationType op,
318 llvm::StringRef property_path,
319 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000320 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
321 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 TargetSP target_sp;
323 LoadScriptFromSymFile load_script_old_value;
324 if (is_load_script && exe_ctx->GetTargetSP()) {
325 target_sp = exe_ctx->GetTargetSP();
326 load_script_old_value =
327 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
328 }
Zachary Turner97206d52017-05-12 04:51:55 +0000329 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 if (error.Success()) {
331 // FIXME it would be nice to have "on-change" callbacks for properties
Zachary Turner31d97a52016-11-17 18:08:12 +0000332 if (property_path == g_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000333 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
335 new_prompt, GetUseColor());
336 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000337 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000339 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
340 auto prompt_change_event_sp = std::make_shared<Event>(
341 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Zachary Turner31d97a52016-11-17 18:08:12 +0000343 } else if (property_path == g_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 // use-color changed. Ping the prompt so it can reset the ansi terminal
345 // codes.
346 SetPrompt(GetPrompt());
347 } else if (is_load_script && target_sp &&
348 load_script_old_value == eLoadScriptFromSymFileWarn) {
349 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
350 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000351 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 StreamString feedback_stream;
353 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
354 StreamFileSP stream_sp(GetErrorFile());
355 if (stream_sp) {
356 for (auto error : errors) {
357 stream_sp->Printf("%s\n", error.AsCString());
358 }
359 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000360 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 }
362 }
363 }
364 } else if (is_escape_non_printables) {
365 DataVisualization::ForceUpdate();
366 }
367 }
368 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000369}
370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371bool Debugger::GetAutoConfirm() const {
372 const uint32_t idx = ePropertyAutoConfirm;
373 return m_collection_sp->GetPropertyAtIndexAsBoolean(
374 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000375}
376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
378 const uint32_t idx = ePropertyDisassemblyFormat;
379 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000380}
381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382const FormatEntity::Entry *Debugger::GetFrameFormat() const {
383 const uint32_t idx = ePropertyFrameFormat;
384 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000385}
386
Pavel Labath7f1c1212017-06-12 16:25:24 +0000387const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
388 const uint32_t idx = ePropertyFrameFormatUnique;
389 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
390}
391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392bool Debugger::GetNotifyVoid() const {
393 const uint32_t idx = ePropertyNotiftVoid;
394 return m_collection_sp->GetPropertyAtIndexAsBoolean(
395 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000396}
397
Zachary Turner514d8cd2016-09-23 18:06:53 +0000398llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 const uint32_t idx = ePropertyPrompt;
400 return m_collection_sp->GetPropertyAtIndexAsString(
401 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000402}
403
Zachary Turner514d8cd2016-09-23 18:06:53 +0000404void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 const uint32_t idx = ePropertyPrompt;
406 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000407 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 std::string str =
409 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
410 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000411 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000413}
414
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000415llvm::StringRef Debugger::GetReproducerPath() const {
416 auto &r = repro::Reproducer::Instance();
417 return r.GetReproducerPath().GetCString();
418}
419
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420const FormatEntity::Entry *Debugger::GetThreadFormat() const {
421 const uint32_t idx = ePropertyThreadFormat;
422 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000423}
424
Jim Ingham6a9767c2016-11-08 20:36:40 +0000425const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
426 const uint32_t idx = ePropertyThreadStopFormat;
427 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
428}
429
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
431 const uint32_t idx = ePropertyScriptLanguage;
432 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
433 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000434}
435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
437 const uint32_t idx = ePropertyScriptLanguage;
438 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
439 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000440}
441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442uint32_t Debugger::GetTerminalWidth() const {
443 const uint32_t idx = ePropertyTerminalWidth;
444 return m_collection_sp->GetPropertyAtIndexAsSInt64(
445 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000446}
447
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448bool Debugger::SetTerminalWidth(uint32_t term_width) {
449 const uint32_t idx = ePropertyTerminalWidth;
450 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000451}
452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453bool Debugger::GetUseExternalEditor() const {
454 const uint32_t idx = ePropertyUseExternalEditor;
455 return m_collection_sp->GetPropertyAtIndexAsBoolean(
456 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000457}
Greg Claytone372b982011-11-21 21:44:34 +0000458
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459bool Debugger::SetUseExternalEditor(bool b) {
460 const uint32_t idx = ePropertyUseExternalEditor;
461 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000462}
Enrico Granata553fad52013-10-25 23:09:40 +0000463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464bool Debugger::GetUseColor() const {
465 const uint32_t idx = ePropertyUseColor;
466 return m_collection_sp->GetPropertyAtIndexAsBoolean(
467 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000468}
469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470bool Debugger::SetUseColor(bool b) {
471 const uint32_t idx = ePropertyUseColor;
472 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
473 SetPrompt(GetPrompt());
474 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000475}
476
Raphael Isemann566afa02018-08-02 00:30:15 +0000477bool Debugger::GetHighlightSource() const {
478 const uint32_t idx = ePropertyHighlightSource;
479 return m_collection_sp->GetPropertyAtIndexAsBoolean(
480 nullptr, idx, g_properties[idx].default_uint_value);
481}
482
Todd Fiala9666ba72016-09-21 20:13:14 +0000483StopShowColumn Debugger::GetStopShowColumn() const {
484 const uint32_t idx = ePropertyStopShowColumn;
485 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
486 nullptr, idx, g_properties[idx].default_uint_value);
487}
488
Raphael Isemann20786322018-08-30 00:09:21 +0000489llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000490 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000491 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000492}
493
Raphael Isemann20786322018-08-30 00:09:21 +0000494llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000495 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000496 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000497}
498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499uint32_t Debugger::GetStopSourceLineCount(bool before) const {
500 const uint32_t idx =
501 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
502 return m_collection_sp->GetPropertyAtIndexAsSInt64(
503 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000504}
505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
507 const uint32_t idx = ePropertyStopDisassemblyDisplay;
508 return (Debugger::StopDisassemblyType)
509 m_collection_sp->GetPropertyAtIndexAsEnumeration(
510 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000511}
512
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513uint32_t Debugger::GetDisassemblyLineCount() const {
514 const uint32_t idx = ePropertyStopDisassemblyCount;
515 return m_collection_sp->GetPropertyAtIndexAsSInt64(
516 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000517}
518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519bool Debugger::GetAutoOneLineSummaries() const {
520 const uint32_t idx = ePropertyAutoOneLineSummaries;
521 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000522}
523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524bool Debugger::GetEscapeNonPrintables() const {
525 const uint32_t idx = ePropertyEscapeNonPrintables;
526 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
527}
528
529bool Debugger::GetAutoIndent() const {
530 const uint32_t idx = ePropertyAutoIndent;
531 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
532}
533
534bool Debugger::SetAutoIndent(bool b) {
535 const uint32_t idx = ePropertyAutoIndent;
536 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
537}
538
539bool Debugger::GetPrintDecls() const {
540 const uint32_t idx = ePropertyPrintDecls;
541 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
542}
543
544bool Debugger::SetPrintDecls(bool b) {
545 const uint32_t idx = ePropertyPrintDecls;
546 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
547}
548
549uint32_t Debugger::GetTabSize() const {
550 const uint32_t idx = ePropertyTabSize;
551 return m_collection_sp->GetPropertyAtIndexAsUInt64(
552 nullptr, idx, g_properties[idx].default_uint_value);
553}
554
555bool Debugger::SetTabSize(uint32_t tab_size) {
556 const uint32_t idx = ePropertyTabSize;
557 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000558}
559
Greg Clayton1b654882010-09-19 02:33:57 +0000560#pragma mark Debugger
561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562// const DebuggerPropertiesSP &
563// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000564//{
565// return m_properties_sp;
566//}
567//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
570 assert(g_debugger_list_ptr == nullptr &&
571 "Debugger::Initialize called more than once!");
572 g_debugger_list_mutex_ptr = new std::recursive_mutex();
573 g_debugger_list_ptr = new DebuggerList();
574 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575}
576
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577void Debugger::Terminate() {
578 assert(g_debugger_list_ptr &&
579 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000580
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
582 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000583 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
585 for (const auto &debugger : *g_debugger_list_ptr)
586 debugger->Clear();
587 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000588 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000590}
591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000595
Zachary Turner97206d52017-05-12 04:51:55 +0000596bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 if (g_load_plugin_callback) {
598 llvm::sys::DynamicLibrary dynlib =
599 g_load_plugin_callback(shared_from_this(), spec, error);
600 if (dynlib.isValid()) {
601 m_loaded_plugins.push_back(dynlib);
602 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000603 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000605 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
606 // if the public API layer isn't available (code is linking against all of
607 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 error.SetErrorString("Public API layer is not available");
609 }
610 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000611}
612
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000613static FileSystem::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000614LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000615 llvm::StringRef path) {
Zachary Turner97206d52017-05-12 04:51:55 +0000616 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000617
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000618 static ConstString g_dylibext(".dylib");
619 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620
621 if (!baton)
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000622 return FileSystem::eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623
624 Debugger *debugger = (Debugger *)baton;
625
Zachary Turner7d86ee52017-03-08 17:56:08 +0000626 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000627 // If we have a regular file, a symbolic link or unknown file type, try and
628 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 // enumeration might be enumerating a file system that doesn't have correct
630 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000631 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
632 ft == fs::file_type::type_unknown) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000633 FileSpec plugin_file_spec(path);
634 FileSystem::Instance().Resolve(plugin_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635
636 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
637 plugin_file_spec.GetFileNameExtension() != g_solibext) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000638 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000639 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640
Zachary Turner97206d52017-05-12 04:51:55 +0000641 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
643
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000644 return FileSystem::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000645 } else if (ft == fs::file_type::directory_file ||
646 ft == fs::file_type::symlink_file ||
647 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000648 // Try and recurse into anything that a directory or symbolic link. We must
649 // also do this for unknown as sometimes the directory enumeration might be
650 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 // information.
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000652 return FileSystem::eEnumerateDirectoryResultEnter;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 }
654
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000655 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000656}
657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 const bool find_directories = true;
660 const bool find_files = true;
661 const bool find_other = true;
662 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000663 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000664 if (FileSystem::Instance().Exists(dir_spec) &&
665 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000666 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
667 find_files, find_other,
668 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000669 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000671
Pavel Labath60f028f2018-06-19 15:09:07 +0000672 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000673 if (FileSystem::Instance().Exists(dir_spec) &&
674 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000675 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
676 find_files, find_other,
677 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000678 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 }
680
681 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000682}
683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
685 void *baton) {
686 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
687 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
688 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
689 g_debugger_list_ptr->push_back(debugger_sp);
690 }
691 debugger_sp->InstanceInitialize();
692 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000693}
694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695void Debugger::Destroy(DebuggerSP &debugger_sp) {
696 if (!debugger_sp)
697 return;
698
699 debugger_sp->Clear();
700
701 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
702 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
703 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
704 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
705 if ((*pos).get() == debugger_sp.get()) {
706 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000707 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000709 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000711}
712
Greg Clayton4d122c42011-09-17 08:33:22 +0000713DebuggerSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +0000714Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 DebuggerSP debugger_sp;
716 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
717 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
718 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
719 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
720 if ((*pos)->m_instance_name == instance_name) {
721 debugger_sp = *pos;
722 break;
723 }
Greg Clayton6920b522012-08-22 18:39:03 +0000724 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 }
726 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000727}
Greg Clayton66111032010-06-23 01:19:29 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
730 TargetSP target_sp;
731 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
732 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
733 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
734 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
735 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
736 if (target_sp)
737 break;
Greg Clayton66111032010-06-23 01:19:29 +0000738 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 }
740 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000741}
742
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743TargetSP Debugger::FindTargetWithProcess(Process *process) {
744 TargetSP target_sp;
745 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
746 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
747 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
748 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
749 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
750 if (target_sp)
751 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000752 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 }
754 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000755}
756
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
758 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000759 Properties(std::make_shared<OptionValueProperties>()),
760 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
761 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
762 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000763 m_input_recorder(nullptr),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
765 m_terminal_state(), m_target_list(*this), m_platform_list(),
766 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000767 m_source_manager_up(), m_source_file_cache(),
Jonas Devliegheref20dd1d2019-04-26 20:03:22 +0000768 m_command_interpreter_up(
769 llvm::make_unique<CommandInterpreter>(*this, false)),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000770 m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(),
771 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
773 m_forward_listener_sp(), m_clear_once() {
774 char instance_cstr[256];
775 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
776 m_instance_name.SetCString(instance_cstr);
777 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000778 m_log_callback_stream_sp =
779 std::make_shared<StreamCallback>(log_callback, baton);
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000780 m_command_interpreter_up->Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 // Always add our default platform to the platform list
782 PlatformSP default_platform_sp(Platform::GetHostPlatform());
783 assert(default_platform_sp);
784 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000785
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 m_collection_sp->Initialize(g_properties);
787 m_collection_sp->AppendProperty(
788 ConstString("target"),
789 ConstString("Settings specify to debugging targets."), true,
790 Target::GetGlobalProperties()->GetValueProperties());
791 m_collection_sp->AppendProperty(
792 ConstString("platform"), ConstString("Platform settings."), true,
793 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000794 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000795 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
796 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000797 if (m_command_interpreter_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 m_collection_sp->AppendProperty(
799 ConstString("interpreter"),
800 ConstString("Settings specify to the debugger's command interpreter."),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000801 true, m_command_interpreter_up->GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 }
803 OptionValueSInt64 *term_width =
804 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
805 nullptr, ePropertyTerminalWidth);
806 term_width->SetMinimumValue(10);
807 term_width->SetMaximumValue(1024);
808
809 // Turn off use-color if this is a dumb terminal.
810 const char *term = getenv("TERM");
811 if (term && !strcmp(term, "dumb"))
812 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000813 // Turn off use-color if we don't write to a terminal with color support.
814 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
815 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000816
817#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
818 // Enabling use of ANSI color codes because LLDB is using them to highlight
819 // text.
820 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000821#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822}
823
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000825
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826void Debugger::Clear() {
Adrian Prantl05097242018-04-30 16:49:04 +0000827 // Make sure we call this function only once. With the C++ global destructor
828 // chain having a list of debuggers and with code that can be running on
829 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 //
831 // The following functions call Debugger::Clear():
832 // Debugger::~Debugger();
833 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
834 // static void Debugger::Terminate();
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000835 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000836 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 StopIOHandlerThread();
838 StopEventHandlerThread();
839 m_listener_sp->Clear();
840 int num_targets = m_target_list.GetNumTargets();
841 for (int i = 0; i < num_targets; i++) {
842 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
843 if (target_sp) {
844 ProcessSP process_sp(target_sp->GetProcessSP());
845 if (process_sp)
846 process_sp->Finalize();
847 target_sp->Destroy();
848 }
Greg Clayton577508d2014-06-20 00:23:57 +0000849 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 m_broadcaster_manager_sp->Clear();
851
852 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000853 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 m_terminal_state.Clear();
855 if (m_input_file_sp)
856 m_input_file_sp->GetFile().Close();
857
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000858 m_command_interpreter_up->Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 });
Greg Clayton44d93782014-01-27 23:43:24 +0000860}
861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862bool Debugger::GetCloseInputOnEOF() const {
863 // return m_input_comm.GetCloseOnEOF();
864 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000865}
866
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867void Debugger::SetCloseInputOnEOF(bool b) {
868 // m_input_comm.SetCloseOnEOF(b);
869}
870
871bool Debugger::GetAsyncExecution() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000872 return !m_command_interpreter_up->GetSynchronous();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873}
874
875void Debugger::SetAsyncExecution(bool async_execution) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000876 m_command_interpreter_up->SetSynchronous(!async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877}
878
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000879repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
880
881void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership,
882 repro::DataRecorder *recorder) {
883 m_input_recorder = recorder;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 if (m_input_file_sp)
885 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
886 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000887 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888
889 File &in_file = m_input_file_sp->GetFile();
890 if (!in_file.IsValid())
891 in_file.SetStream(stdin, true);
892
Adrian Prantl05097242018-04-30 16:49:04 +0000893 // Save away the terminal state if that is relevant, so that we can restore
894 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 SaveInputTerminalState();
896}
897
898void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
899 if (m_output_file_sp)
900 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
901 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000902 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903
904 File &out_file = m_output_file_sp->GetFile();
905 if (!out_file.IsValid())
906 out_file.SetStream(stdout, false);
907
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000908 // Do not create the ScriptInterpreter just for setting the output file
909 // handle as the constructor will know how to do the right thing on its own.
910 if (ScriptInterpreter *script_interpreter =
911 GetScriptInterpreter(/*can_create=*/false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 script_interpreter->ResetOutputFileHandle(fh);
913}
914
915void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
916 if (m_error_file_sp)
917 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
918 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000919 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920
921 File &err_file = m_error_file_sp->GetFile();
922 if (!err_file.IsValid())
923 err_file.SetStream(stderr, false);
924}
925
926void Debugger::SaveInputTerminalState() {
927 if (m_input_file_sp) {
928 File &in_file = m_input_file_sp->GetFile();
929 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
930 m_terminal_state.Save(in_file.GetDescriptor(), true);
931 }
932}
933
934void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
935
936ExecutionContext Debugger::GetSelectedExecutionContext() {
937 ExecutionContext exe_ctx;
938 TargetSP target_sp(GetSelectedTarget());
939 exe_ctx.SetTargetSP(target_sp);
940
941 if (target_sp) {
942 ProcessSP process_sp(target_sp->GetProcessSP());
943 exe_ctx.SetProcessSP(process_sp);
944 if (process_sp && !process_sp->IsRunning()) {
945 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
946 if (thread_sp) {
947 exe_ctx.SetThreadSP(thread_sp);
948 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
949 if (exe_ctx.GetFramePtr() == nullptr)
950 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
951 }
952 }
953 }
954 return exe_ctx;
955}
956
957void Debugger::DispatchInputInterrupt() {
958 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
959 IOHandlerSP reader_sp(m_input_reader_stack.Top());
960 if (reader_sp)
961 reader_sp->Interrupt();
962}
963
964void Debugger::DispatchInputEndOfFile() {
965 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
966 IOHandlerSP reader_sp(m_input_reader_stack.Top());
967 if (reader_sp)
968 reader_sp->GotEOF();
969}
970
971void Debugger::ClearIOHandlers() {
972 // The bottom input reader should be the main debugger input reader. We do
973 // not want to close that one here.
974 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
975 while (m_input_reader_stack.GetSize() > 1) {
976 IOHandlerSP reader_sp(m_input_reader_stack.Top());
977 if (reader_sp)
978 PopIOHandler(reader_sp);
979 }
980}
981
982void Debugger::ExecuteIOHandlers() {
983 while (true) {
984 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000987
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 // Remove all input readers that are done from the top of the stack
991 while (true) {
992 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
993 if (top_reader_sp && top_reader_sp->GetIsDone())
994 PopIOHandler(top_reader_sp);
995 else
996 break;
997 }
998 }
999 ClearIOHandlers();
1000}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
1003 return m_input_reader_stack.IsTop(reader_sp);
1004}
Greg Clayton44d93782014-01-27 23:43:24 +00001005
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
1007 IOHandler::Type second_top_type) {
1008 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1009}
1010
1011void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1012 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
1013 m_input_reader_stack.PrintAsync(stream.get(), s, len);
1014}
1015
1016ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1017 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
1018}
1019
1020const char *Debugger::GetIOHandlerCommandPrefix() {
1021 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
1022}
1023
1024const char *Debugger::GetIOHandlerHelpPrologue() {
1025 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1026}
1027
1028void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1029 PushIOHandler(reader_sp);
1030
1031 IOHandlerSP top_reader_sp = reader_sp;
1032 while (top_reader_sp) {
1033 top_reader_sp->Run();
1034
1035 if (top_reader_sp.get() == reader_sp.get()) {
1036 if (PopIOHandler(reader_sp))
1037 break;
1038 }
1039
1040 while (true) {
1041 top_reader_sp = m_input_reader_stack.Top();
1042 if (top_reader_sp && top_reader_sp->GetIsDone())
1043 PopIOHandler(top_reader_sp);
1044 else
1045 break;
1046 }
1047 }
1048}
1049
1050void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1051 StreamFileSP &out,
1052 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +00001053 // Before an IOHandler runs, it must have in/out/err streams. This function
1054 // is called when one ore more of the streams are nullptr. We use the top
1055 // input reader's in/out/err streams, or fall back to the debugger file
1056 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057
1058 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1059 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1060 // If no STDIN has been set, then set it appropriately
1061 if (!in) {
1062 if (top_reader_sp)
1063 in = top_reader_sp->GetInputStreamFile();
1064 else
1065 in = GetInputFile();
1066
1067 // If there is nothing, use stdin
1068 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001069 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 }
1071 // If no STDOUT has been set, then set it appropriately
1072 if (!out) {
1073 if (top_reader_sp)
1074 out = top_reader_sp->GetOutputStreamFile();
1075 else
1076 out = GetOutputFile();
1077
1078 // If there is nothing, use stdout
1079 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001080 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 }
1082 // If no STDERR has been set, then set it appropriately
1083 if (!err) {
1084 if (top_reader_sp)
1085 err = top_reader_sp->GetErrorStreamFile();
1086 else
1087 err = GetErrorFile();
1088
1089 // If there is nothing, use stderr
1090 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001091 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 }
1093}
1094
Raphael Isemannc01783a2018-08-29 22:50:54 +00001095void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1096 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 if (!reader_sp)
1098 return;
1099
1100 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1101
1102 // Get the current top input reader...
1103 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1104
1105 // Don't push the same IO handler twice...
1106 if (reader_sp == top_reader_sp)
1107 return;
1108
1109 // Push our new input reader
1110 m_input_reader_stack.Push(reader_sp);
1111 reader_sp->Activate();
1112
Adrian Prantl05097242018-04-30 16:49:04 +00001113 // Interrupt the top input reader to it will exit its Run() function and let
1114 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 if (top_reader_sp) {
1116 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001117 if (cancel_top_handler)
1118 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 }
1120}
1121
1122bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1123 if (!pop_reader_sp)
1124 return false;
1125
1126 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1127
Adrian Prantl05097242018-04-30 16:49:04 +00001128 // The reader on the stop of the stack is done, so let the next read on the
1129 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (m_input_reader_stack.IsEmpty())
1131 return false;
1132
1133 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1134
1135 if (pop_reader_sp != reader_sp)
1136 return false;
1137
1138 reader_sp->Deactivate();
1139 reader_sp->Cancel();
1140 m_input_reader_stack.Pop();
1141
1142 reader_sp = m_input_reader_stack.Top();
1143 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001144 reader_sp->Activate();
1145
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 return true;
1147}
1148
1149StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001150 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151}
1152
1153StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001154 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155}
1156
1157size_t Debugger::GetNumDebuggers() {
1158 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1159 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1160 return g_debugger_list_ptr->size();
1161 }
1162 return 0;
1163}
1164
1165lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
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 if (index < g_debugger_list_ptr->size())
1171 debugger_sp = g_debugger_list_ptr->at(index);
1172 }
1173
1174 return debugger_sp;
1175}
1176
1177DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1178 DebuggerSP debugger_sp;
1179
1180 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1181 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1182 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1183 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1184 if ((*pos)->GetID() == id) {
1185 debugger_sp = *pos;
1186 break;
1187 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001188 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 }
1190 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001191}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001192
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1194 const SymbolContext *sc,
1195 const SymbolContext *prev_sc,
1196 const ExecutionContext *exe_ctx,
1197 const Address *addr, Stream &s) {
1198 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001199
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 if (format == nullptr) {
1201 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1202 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1203 if (format == nullptr) {
1204 FormatEntity::Parse("${addr}: ", format_entry);
1205 format = &format_entry;
1206 }
1207 }
1208 bool function_changed = false;
1209 bool initial_function = false;
1210 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1211 if (sc && (sc->function || sc->symbol)) {
1212 if (prev_sc->symbol && sc->symbol) {
1213 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1214 prev_sc->symbol->GetType())) {
1215 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 } else if (prev_sc->function && sc->function) {
1218 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1219 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001220 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 }
Adrian Prantl05097242018-04-30 16:49:04 +00001224 // The first context on a list of instructions will have a prev_sc that has
1225 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 // would return false. But we do get a prev_sc pointer.
1227 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1228 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1229 initial_function = true;
1230 }
1231 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1232 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001233}
1234
Kate Stoneb9c1b512016-09-06 20:57:50 +00001235void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1236 void *baton) {
1237 // For simplicity's sake, I am not going to deal with how to close down any
1238 // open logging streams, I just redirect everything from here on out to the
1239 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001240 m_log_callback_stream_sp =
1241 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001242}
1243
Pavel Labath5e336902017-03-01 10:08:40 +00001244bool Debugger::EnableLog(llvm::StringRef channel,
1245 llvm::ArrayRef<const char *> categories,
1246 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001247 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001248 const bool should_close = true;
1249 const bool unbuffered = true;
1250
1251 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 if (m_log_callback_stream_sp) {
1253 log_stream_sp = m_log_callback_stream_sp;
1254 // For now when using the callback mode you always get thread & timestamp.
1255 log_options |=
1256 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001257 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001258 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1259 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001261 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 if (pos != m_log_streams.end())
1263 log_stream_sp = pos->second.lock();
1264 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001265 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1266 if (log_options & LLDB_LOG_OPTION_APPEND)
1267 flags |= llvm::sys::fs::F_Append;
1268 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001269 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1270 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001271 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001272 return false;
1273 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001274 log_stream_sp =
1275 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001277 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 }
1279 assert(log_stream_sp);
1280
1281 if (log_options == 0)
1282 log_options =
1283 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1284
1285 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1286 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001287}
1288
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00001289ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) {
1290 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1291
1292 if (!m_script_interpreter_sp) {
1293 if (!can_create)
1294 return nullptr;
1295 m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(
1296 GetScriptLanguage(), *this);
1297 }
1298
1299 return m_script_interpreter_sp.get();
1300}
1301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302SourceManager &Debugger::GetSourceManager() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001303 if (!m_source_manager_up)
1304 m_source_manager_up = llvm::make_unique<SourceManager>(shared_from_this());
1305 return *m_source_manager_up;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001306}
1307
Greg Clayton44d93782014-01-27 23:43:24 +00001308// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1310 using namespace lldb;
1311 const uint32_t event_type =
1312 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1313 event_sp);
1314
1315 // if (event_type & eBreakpointEventTypeAdded
1316 // || event_type & eBreakpointEventTypeRemoved
1317 // || event_type & eBreakpointEventTypeEnabled
1318 // || event_type & eBreakpointEventTypeDisabled
1319 // || event_type & eBreakpointEventTypeCommandChanged
1320 // || event_type & eBreakpointEventTypeConditionChanged
1321 // || event_type & eBreakpointEventTypeIgnoreChanged
1322 // || event_type & eBreakpointEventTypeLocationsResolved)
1323 // {
1324 // // Don't do anything about these events, since the breakpoint
1325 // commands already echo these actions.
1326 // }
1327 //
1328 if (event_type & eBreakpointEventTypeLocationsAdded) {
1329 uint32_t num_new_locations =
1330 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1331 event_sp);
1332 if (num_new_locations > 0) {
1333 BreakpointSP breakpoint =
1334 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1335 StreamSP output_sp(GetAsyncOutputStream());
1336 if (output_sp) {
1337 output_sp->Printf("%d location%s added to breakpoint %d\n",
1338 num_new_locations, num_new_locations == 1 ? "" : "s",
1339 breakpoint->GetID());
1340 output_sp->Flush();
1341 }
Greg Clayton44d93782014-01-27 23:43:24 +00001342 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 }
1344 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1345 // {
1346 // // These locations just get disabled, not sure it is worth spamming
1347 // folks about this on the command line.
1348 // }
1349 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1350 // {
1351 // // This might be an interesting thing to note, but I'm going to
1352 // leave it quiet for now, it just looked noisy.
1353 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001354}
1355
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1357 size_t total_bytes = 0;
1358 if (stream == nullptr)
1359 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001360
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361 if (stream) {
1362 // The process has stuff waiting for stdout; get it and write it out to the
1363 // appropriate place.
1364 if (process == nullptr) {
1365 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1366 if (target_sp)
1367 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001368 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001369 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001370 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 size_t len;
1372 char stdio_buffer[1024];
1373 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1374 error)) > 0) {
1375 stream->Write(stdio_buffer, len);
1376 total_bytes += len;
1377 }
1378 }
1379 stream->Flush();
1380 }
1381 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001382}
1383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1385 size_t total_bytes = 0;
1386 if (stream == nullptr)
1387 stream = GetOutputFile().get();
1388
1389 if (stream) {
1390 // The process has stuff waiting for stderr; get it and write it out to the
1391 // appropriate place.
1392 if (process == nullptr) {
1393 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1394 if (target_sp)
1395 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001396 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001398 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 size_t len;
1400 char stdio_buffer[1024];
1401 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1402 error)) > 0) {
1403 stream->Write(stdio_buffer, len);
1404 total_bytes += len;
1405 }
1406 }
1407 stream->Flush();
1408 }
1409 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001410}
1411
1412// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1414 using namespace lldb;
1415 const uint32_t event_type = event_sp->GetType();
1416 ProcessSP process_sp =
1417 (event_type == Process::eBroadcastBitStructuredData)
1418 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1419 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001420
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 StreamSP output_stream_sp = GetAsyncOutputStream();
1422 StreamSP error_stream_sp = GetAsyncErrorStream();
1423 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001424
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 if (!gui_enabled) {
1426 bool pop_process_io_handler = false;
1427 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 bool state_is_stopped = false;
1430 const bool got_state_changed =
1431 (event_type & Process::eBroadcastBitStateChanged) != 0;
1432 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1433 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1434 const bool got_structured_data =
1435 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001436
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 if (got_state_changed) {
1438 StateType event_state =
1439 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1440 state_is_stopped = StateIsStoppedState(event_state, false);
1441 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 // Display running state changes first before any STDIO
1444 if (got_state_changed && !state_is_stopped) {
1445 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1446 pop_process_io_handler);
1447 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 // Now display and STDOUT
1450 if (got_stdout || got_state_changed) {
1451 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1452 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001453
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 // Now display and STDERR
1455 if (got_stderr || got_state_changed) {
1456 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1457 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001458
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459 // Give structured data events an opportunity to display.
1460 if (got_structured_data) {
1461 StructuredDataPluginSP plugin_sp =
1462 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1463 if (plugin_sp) {
1464 auto structured_data_sp =
1465 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1466 if (output_stream_sp) {
1467 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001468 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 plugin_sp->GetDescription(structured_data_sp, content_stream);
1470 if (error.Success()) {
1471 if (!content_stream.GetString().empty()) {
1472 // Add newline.
1473 content_stream.PutChar('\n');
1474 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001475
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001477 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 } else {
1480 error_stream_sp->Printf("Failed to print structured "
1481 "data with plugin %s: %s",
1482 plugin_sp->GetPluginName().AsCString(),
1483 error.AsCString());
1484 }
Todd Fiala75930012016-08-19 04:21:48 +00001485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001487 }
Greg Clayton44d93782014-01-27 23:43:24 +00001488
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 // Now display any stopped state changes after any STDIO
1490 if (got_state_changed && state_is_stopped) {
1491 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1492 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001493 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494
1495 output_stream_sp->Flush();
1496 error_stream_sp->Flush();
1497
1498 if (pop_process_io_handler)
1499 process_sp->PopProcessIOHandler();
1500 }
Greg Clayton44d93782014-01-27 23:43:24 +00001501}
1502
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001504 // At present the only thread event we handle is the Frame Changed event, and
1505 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506 using namespace lldb;
1507 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001508 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 if (event_type == Thread::eBroadcastBitStackChanged ||
1510 event_type == Thread::eBroadcastBitThreadSelected) {
1511 ThreadSP thread_sp(
1512 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1513 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001514 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 }
1516 }
Greg Clayton44d93782014-01-27 23:43:24 +00001517}
1518
Kate Stoneb9c1b512016-09-06 20:57:50 +00001519bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1520
1521void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1522 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001523}
1524
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1526 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001527}
1528
Kate Stoneb9c1b512016-09-06 20:57:50 +00001529void Debugger::DefaultEventHandler() {
1530 ListenerSP listener_sp(GetListener());
1531 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1532 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1533 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1534 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1535 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001536
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537 BroadcastEventSpec process_event_spec(
1538 broadcaster_class_process,
1539 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1540 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001541
Kate Stoneb9c1b512016-09-06 20:57:50 +00001542 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1543 Thread::eBroadcastBitStackChanged |
1544 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001545
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1547 target_event_spec);
1548 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1549 process_event_spec);
1550 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1551 thread_event_spec);
1552 listener_sp->StartListeningForEvents(
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001553 m_command_interpreter_up.get(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1555 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1556 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001557
Adrian Prantl05097242018-04-30 16:49:04 +00001558 // Let the thread that spawned us know that we have started up and that we
1559 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001560 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001561
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562 bool done = false;
1563 while (!done) {
1564 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001565 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 if (event_sp) {
1567 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1568 if (broadcaster) {
1569 uint32_t event_type = event_sp->GetType();
1570 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1571 if (broadcaster_class == broadcaster_class_process) {
1572 HandleProcessEvent(event_sp);
1573 } else if (broadcaster_class == broadcaster_class_target) {
1574 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1575 event_sp.get())) {
1576 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001577 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 } else if (broadcaster_class == broadcaster_class_thread) {
1579 HandleThreadEvent(event_sp);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001580 } else if (broadcaster == m_command_interpreter_up.get()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 if (event_type &
1582 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1583 done = true;
1584 } else if (event_type &
1585 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1586 const char *data = reinterpret_cast<const char *>(
1587 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1588 if (data && data[0]) {
1589 StreamSP error_sp(GetAsyncErrorStream());
1590 if (error_sp) {
1591 error_sp->PutCString(data);
1592 error_sp->Flush();
1593 }
1594 }
1595 } else if (event_type & CommandInterpreter::
1596 eBroadcastBitAsynchronousOutputData) {
1597 const char *data = reinterpret_cast<const char *>(
1598 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1599 if (data && data[0]) {
1600 StreamSP output_sp(GetAsyncOutputStream());
1601 if (output_sp) {
1602 output_sp->PutCString(data);
1603 output_sp->Flush();
1604 }
1605 }
1606 }
1607 }
Greg Clayton44d93782014-01-27 23:43:24 +00001608 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609
1610 if (m_forward_listener_sp)
1611 m_forward_listener_sp->AddEvent(event_sp);
1612 }
Greg Clayton44d93782014-01-27 23:43:24 +00001613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 }
Greg Clayton44d93782014-01-27 23:43:24 +00001615}
1616
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1618 ((Debugger *)arg)->DefaultEventHandler();
Konrad Kleine85200642019-05-23 15:17:39 +00001619 return {};
Greg Clayton44d93782014-01-27 23:43:24 +00001620}
1621
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622bool Debugger::StartEventHandlerThread() {
1623 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001624 // We must synchronize with the DefaultEventHandler() thread to ensure it
1625 // is up and running and listening to events before we return from this
1626 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001628 ConstString full_name("lldb.debugger.event-handler");
1629 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1631 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001632
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001633 auto thread_name =
1634 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1635 full_name.AsCString() : "dbg.evt-handler";
1636
Kate Stoneb9c1b512016-09-06 20:57:50 +00001637 // Use larger 8MB stack for this thread
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001638 m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name,
1639 EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001640
Adrian Prantl05097242018-04-30 16:49:04 +00001641 // Make sure DefaultEventHandler() is running and listening to events
1642 // before we return from this function. We are only listening for events of
1643 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1644 // event, we just need to wait an infinite amount of time for it (nullptr
1645 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001647 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 }
1649 return m_event_handler_thread.IsJoinable();
1650}
1651
1652void Debugger::StopEventHandlerThread() {
1653 if (m_event_handler_thread.IsJoinable()) {
1654 GetCommandInterpreter().BroadcastEvent(
1655 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1656 m_event_handler_thread.Join(nullptr);
1657 }
1658}
1659
1660lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1661 Debugger *debugger = (Debugger *)arg;
1662 debugger->ExecuteIOHandlers();
1663 debugger->StopEventHandlerThread();
Konrad Kleine85200642019-05-23 15:17:39 +00001664 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665}
1666
1667bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1668
1669bool Debugger::StartIOHandlerThread() {
1670 if (!m_io_handler_thread.IsJoinable())
1671 m_io_handler_thread = ThreadLauncher::LaunchThread(
1672 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1673 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1674 return m_io_handler_thread.IsJoinable();
1675}
1676
1677void Debugger::StopIOHandlerThread() {
1678 if (m_io_handler_thread.IsJoinable()) {
1679 if (m_input_file_sp)
1680 m_input_file_sp->GetFile().Close();
1681 m_io_handler_thread.Join(nullptr);
1682 }
1683}
1684
1685void Debugger::JoinIOHandlerThread() {
1686 if (HasIOHandlerThread()) {
1687 thread_result_t result;
1688 m_io_handler_thread.Join(&result);
1689 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1690 }
1691}
1692
1693Target *Debugger::GetDummyTarget() {
1694 return m_target_list.GetDummyTarget(*this).get();
1695}
1696
1697Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1698 Target *target = nullptr;
1699 if (!prefer_dummy) {
1700 target = m_target_list.GetSelectedTarget().get();
1701 if (target)
1702 return target;
1703 }
1704
1705 return GetDummyTarget();
1706}
1707
Zachary Turner97206d52017-05-12 04:51:55 +00001708Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1709 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 FileSpec repl_executable;
1711
1712 if (language == eLanguageTypeUnknown) {
1713 std::set<LanguageType> repl_languages;
1714
1715 Language::GetLanguagesSupportingREPLs(repl_languages);
1716
1717 if (repl_languages.size() == 1) {
1718 language = *repl_languages.begin();
1719 } else if (repl_languages.empty()) {
1720 err.SetErrorStringWithFormat(
1721 "LLDB isn't configured with REPL support for any languages.");
1722 return err;
1723 } else {
1724 err.SetErrorStringWithFormat(
1725 "Multiple possible REPL languages. Please specify a language.");
1726 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001727 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 }
Greg Clayton44d93782014-01-27 23:43:24 +00001729
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 Target *const target =
1731 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001732
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001734
Kate Stoneb9c1b512016-09-06 20:57:50 +00001735 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001736 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 }
1738
1739 if (!repl_sp) {
1740 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1741 Language::GetNameForLanguageType(language));
1742 return err;
1743 }
1744
1745 repl_sp->SetCompilerOptions(repl_options);
1746 repl_sp->RunLoop();
1747
1748 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001749}