blob: 5b88246017a04e95ad8182be3c2556c7f82d784e [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...
Jonas Devlieghere35e4c842018-11-01 00:33:27 +000024#include "lldb/Host/FileSystem.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000025#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000026#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000027#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000029#include "lldb/Interpreter/OptionValue.h" // for OptionValue, Opt...
Zachary Turner633a29c2015-03-04 01:58:01 +000030#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000031#include "lldb/Interpreter/OptionValueSInt64.h"
32#include "lldb/Interpreter/OptionValueString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000033#include "lldb/Interpreter/Property.h" // for PropertyDefinition
34#include "lldb/Interpreter/ScriptInterpreter.h" // for ScriptInterpreter
Greg Clayton1f746072012-08-29 21:13:06 +000035#include "lldb/Symbol/Function.h"
36#include "lldb/Symbol/Symbol.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000037#include "lldb/Symbol/SymbolContext.h" // for SymbolContext
Sean Callanan3e7e9152015-10-20 00:23:46 +000038#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Target/Process.h"
Todd Fiala75930012016-08-19 04:21:48 +000040#include "lldb/Target/StructuredDataPlugin.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000041#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000042#include "lldb/Target/TargetList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/Thread.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000044#include "lldb/Target/ThreadList.h" // for ThreadList
Greg Clayton5a314712011-10-14 07:41:33 +000045#include "lldb/Utility/AnsiTerminal.h"
Pavel Labathd821c992018-08-07 11:07:21 +000046#include "lldb/Utility/Log.h" // for LLDB_LOG_OPTION_...
47#include "lldb/Utility/State.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000048#include "lldb/Utility/Stream.h" // for Stream
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)
Zachary Turner2f3df612017-04-06 21:28:29 +000053#include "lldb/Host/windows/PosixApi.h" // for PATH_MAX
David Bolvansky8aa23612018-09-05 22:06:58 +000054#include "lldb/Host/windows/windows.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000055#endif
56
57#include "llvm/ADT/None.h" // for None
58#include "llvm/ADT/STLExtras.h" // for make_unique
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/iterator.h" // for iterator_facade_...
61#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"
65#include "llvm/Support/raw_ostream.h" // for raw_fd_ostream
66
67#include <list> // for list
68#include <memory> // for make_shared
69#include <mutex>
70#include <set> // for set
71#include <stdio.h> // for size_t, NULL
72#include <stdlib.h> // for getenv
73#include <string.h> // for strcmp
74#include <string> // for string
75#include <system_error> // for error_code
76
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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415const FormatEntity::Entry *Debugger::GetThreadFormat() const {
416 const uint32_t idx = ePropertyThreadFormat;
417 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000418}
419
Jim Ingham6a9767c2016-11-08 20:36:40 +0000420const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
421 const uint32_t idx = ePropertyThreadStopFormat;
422 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
423}
424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
426 const uint32_t idx = ePropertyScriptLanguage;
427 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
428 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000429}
430
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
432 const uint32_t idx = ePropertyScriptLanguage;
433 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
434 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000435}
436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437uint32_t Debugger::GetTerminalWidth() const {
438 const uint32_t idx = ePropertyTerminalWidth;
439 return m_collection_sp->GetPropertyAtIndexAsSInt64(
440 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000441}
442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443bool Debugger::SetTerminalWidth(uint32_t term_width) {
444 const uint32_t idx = ePropertyTerminalWidth;
445 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000446}
447
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448bool Debugger::GetUseExternalEditor() const {
449 const uint32_t idx = ePropertyUseExternalEditor;
450 return m_collection_sp->GetPropertyAtIndexAsBoolean(
451 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000452}
Greg Claytone372b982011-11-21 21:44:34 +0000453
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454bool Debugger::SetUseExternalEditor(bool b) {
455 const uint32_t idx = ePropertyUseExternalEditor;
456 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000457}
Enrico Granata553fad52013-10-25 23:09:40 +0000458
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459bool Debugger::GetUseColor() const {
460 const uint32_t idx = ePropertyUseColor;
461 return m_collection_sp->GetPropertyAtIndexAsBoolean(
462 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000463}
464
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465bool Debugger::SetUseColor(bool b) {
466 const uint32_t idx = ePropertyUseColor;
467 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
468 SetPrompt(GetPrompt());
469 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000470}
471
Raphael Isemann566afa02018-08-02 00:30:15 +0000472bool Debugger::GetHighlightSource() const {
473 const uint32_t idx = ePropertyHighlightSource;
474 return m_collection_sp->GetPropertyAtIndexAsBoolean(
475 nullptr, idx, g_properties[idx].default_uint_value);
476}
477
Todd Fiala9666ba72016-09-21 20:13:14 +0000478StopShowColumn Debugger::GetStopShowColumn() const {
479 const uint32_t idx = ePropertyStopShowColumn;
480 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
481 nullptr, idx, g_properties[idx].default_uint_value);
482}
483
Raphael Isemann20786322018-08-30 00:09:21 +0000484llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000485 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000486 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000487}
488
Raphael Isemann20786322018-08-30 00:09:21 +0000489llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000490 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000491 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000492}
493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494uint32_t Debugger::GetStopSourceLineCount(bool before) const {
495 const uint32_t idx =
496 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
497 return m_collection_sp->GetPropertyAtIndexAsSInt64(
498 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000499}
500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
502 const uint32_t idx = ePropertyStopDisassemblyDisplay;
503 return (Debugger::StopDisassemblyType)
504 m_collection_sp->GetPropertyAtIndexAsEnumeration(
505 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000506}
507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508uint32_t Debugger::GetDisassemblyLineCount() const {
509 const uint32_t idx = ePropertyStopDisassemblyCount;
510 return m_collection_sp->GetPropertyAtIndexAsSInt64(
511 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000512}
513
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514bool Debugger::GetAutoOneLineSummaries() const {
515 const uint32_t idx = ePropertyAutoOneLineSummaries;
516 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000517}
518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519bool Debugger::GetEscapeNonPrintables() const {
520 const uint32_t idx = ePropertyEscapeNonPrintables;
521 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
522}
523
524bool Debugger::GetAutoIndent() const {
525 const uint32_t idx = ePropertyAutoIndent;
526 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
527}
528
529bool Debugger::SetAutoIndent(bool b) {
530 const uint32_t idx = ePropertyAutoIndent;
531 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
532}
533
534bool Debugger::GetPrintDecls() const {
535 const uint32_t idx = ePropertyPrintDecls;
536 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
537}
538
539bool Debugger::SetPrintDecls(bool b) {
540 const uint32_t idx = ePropertyPrintDecls;
541 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
542}
543
544uint32_t Debugger::GetTabSize() const {
545 const uint32_t idx = ePropertyTabSize;
546 return m_collection_sp->GetPropertyAtIndexAsUInt64(
547 nullptr, idx, g_properties[idx].default_uint_value);
548}
549
550bool Debugger::SetTabSize(uint32_t tab_size) {
551 const uint32_t idx = ePropertyTabSize;
552 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000553}
554
Greg Clayton1b654882010-09-19 02:33:57 +0000555#pragma mark Debugger
556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557// const DebuggerPropertiesSP &
558// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000559//{
560// return m_properties_sp;
561//}
562//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
565 assert(g_debugger_list_ptr == nullptr &&
566 "Debugger::Initialize called more than once!");
567 g_debugger_list_mutex_ptr = new std::recursive_mutex();
568 g_debugger_list_ptr = new DebuggerList();
569 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000570}
571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572void Debugger::Terminate() {
573 assert(g_debugger_list_ptr &&
574 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
577 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000578 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
580 for (const auto &debugger : *g_debugger_list_ptr)
581 debugger->Clear();
582 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000585}
586
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000590
Zachary Turner97206d52017-05-12 04:51:55 +0000591bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 if (g_load_plugin_callback) {
593 llvm::sys::DynamicLibrary dynlib =
594 g_load_plugin_callback(shared_from_this(), spec, error);
595 if (dynlib.isValid()) {
596 m_loaded_plugins.push_back(dynlib);
597 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000598 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000600 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
601 // if the public API layer isn't available (code is linking against all of
602 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 error.SetErrorString("Public API layer is not available");
604 }
605 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000606}
607
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000608static FileSystem::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000609LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000610 llvm::StringRef path) {
Zachary Turner97206d52017-05-12 04:51:55 +0000611 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000612
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000613 static ConstString g_dylibext(".dylib");
614 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615
616 if (!baton)
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000617 return FileSystem::eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618
619 Debugger *debugger = (Debugger *)baton;
620
Zachary Turner7d86ee52017-03-08 17:56:08 +0000621 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000622 // If we have a regular file, a symbolic link or unknown file type, try and
623 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 // enumeration might be enumerating a file system that doesn't have correct
625 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000626 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
627 ft == fs::file_type::type_unknown) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000628 FileSpec plugin_file_spec(path, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 plugin_file_spec.ResolvePath();
630
631 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
632 plugin_file_spec.GetFileNameExtension() != g_solibext) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000633 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000634 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635
Zachary Turner97206d52017-05-12 04:51:55 +0000636 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
638
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000639 return FileSystem::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000640 } else if (ft == fs::file_type::directory_file ||
641 ft == fs::file_type::symlink_file ||
642 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000643 // Try and recurse into anything that a directory or symbolic link. We must
644 // also do this for unknown as sometimes the directory enumeration might be
645 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 // information.
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000647 return FileSystem::eEnumerateDirectoryResultEnter;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 }
649
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000650 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000651}
652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 const bool find_directories = true;
655 const bool find_files = true;
656 const bool find_other = true;
657 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000658 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000659 if (FileSystem::Instance().Exists(dir_spec) &&
660 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000661 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
662 find_files, find_other,
663 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000664 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000666
Pavel Labath60f028f2018-06-19 15:09:07 +0000667 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000668 if (FileSystem::Instance().Exists(dir_spec) &&
669 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000670 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
671 find_files, find_other,
672 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000673 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 }
675
676 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000677}
678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
680 void *baton) {
681 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
682 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
683 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
684 g_debugger_list_ptr->push_back(debugger_sp);
685 }
686 debugger_sp->InstanceInitialize();
687 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000688}
689
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690void Debugger::Destroy(DebuggerSP &debugger_sp) {
691 if (!debugger_sp)
692 return;
693
694 debugger_sp->Clear();
695
696 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
697 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
698 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
699 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
700 if ((*pos).get() == debugger_sp.get()) {
701 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000702 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000704 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000706}
707
Greg Clayton4d122c42011-09-17 08:33:22 +0000708DebuggerSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709Debugger::FindDebuggerWithInstanceName(const ConstString &instance_name) {
710 DebuggerSP debugger_sp;
711 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
712 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
713 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
714 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
715 if ((*pos)->m_instance_name == instance_name) {
716 debugger_sp = *pos;
717 break;
718 }
Greg Clayton6920b522012-08-22 18:39:03 +0000719 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 }
721 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000722}
Greg Clayton66111032010-06-23 01:19:29 +0000723
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
725 TargetSP target_sp;
726 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
727 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
728 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
729 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
730 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
731 if (target_sp)
732 break;
Greg Clayton66111032010-06-23 01:19:29 +0000733 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 }
735 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000736}
737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738TargetSP Debugger::FindTargetWithProcess(Process *process) {
739 TargetSP target_sp;
740 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
741 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
742 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
743 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
744 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
745 if (target_sp)
746 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748 }
749 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000750}
751
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
753 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000754 Properties(std::make_shared<OptionValueProperties>()),
755 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
756 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
757 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
759 m_terminal_state(), m_target_list(*this), m_platform_list(),
760 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
761 m_source_manager_ap(), m_source_file_cache(),
Zachary Turner2f3df612017-04-06 21:28:29 +0000762 m_command_interpreter_ap(llvm::make_unique<CommandInterpreter>(
763 *this, eScriptLanguageDefault, false)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 m_input_reader_stack(), m_instance_name(), m_loaded_plugins(),
765 m_event_handler_thread(), m_io_handler_thread(),
766 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
767 m_forward_listener_sp(), m_clear_once() {
768 char instance_cstr[256];
769 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
770 m_instance_name.SetCString(instance_cstr);
771 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000772 m_log_callback_stream_sp =
773 std::make_shared<StreamCallback>(log_callback, baton);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774 m_command_interpreter_ap->Initialize();
775 // Always add our default platform to the platform list
776 PlatformSP default_platform_sp(Platform::GetHostPlatform());
777 assert(default_platform_sp);
778 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000779
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 m_collection_sp->Initialize(g_properties);
781 m_collection_sp->AppendProperty(
782 ConstString("target"),
783 ConstString("Settings specify to debugging targets."), true,
784 Target::GetGlobalProperties()->GetValueProperties());
785 m_collection_sp->AppendProperty(
786 ConstString("platform"), ConstString("Platform settings."), true,
787 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000788 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000789 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
790 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 if (m_command_interpreter_ap) {
792 m_collection_sp->AppendProperty(
793 ConstString("interpreter"),
794 ConstString("Settings specify to the debugger's command interpreter."),
795 true, m_command_interpreter_ap->GetValueProperties());
796 }
797 OptionValueSInt64 *term_width =
798 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
799 nullptr, ePropertyTerminalWidth);
800 term_width->SetMinimumValue(10);
801 term_width->SetMaximumValue(1024);
802
803 // Turn off use-color if this is a dumb terminal.
804 const char *term = getenv("TERM");
805 if (term && !strcmp(term, "dumb"))
806 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000807 // Turn off use-color if we don't write to a terminal with color support.
808 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
809 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000810
811#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
812 // Enabling use of ANSI color codes because LLDB is using them to highlight
813 // text.
814 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000815#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816}
817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000819
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820void Debugger::Clear() {
821 //----------------------------------------------------------------------
Adrian Prantl05097242018-04-30 16:49:04 +0000822 // Make sure we call this function only once. With the C++ global destructor
823 // chain having a list of debuggers and with code that can be running on
824 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 //
826 // The following functions call Debugger::Clear():
827 // Debugger::~Debugger();
828 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
829 // static void Debugger::Terminate();
830 //----------------------------------------------------------------------
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000831 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000832 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 StopIOHandlerThread();
834 StopEventHandlerThread();
835 m_listener_sp->Clear();
836 int num_targets = m_target_list.GetNumTargets();
837 for (int i = 0; i < num_targets; i++) {
838 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
839 if (target_sp) {
840 ProcessSP process_sp(target_sp->GetProcessSP());
841 if (process_sp)
842 process_sp->Finalize();
843 target_sp->Destroy();
844 }
Greg Clayton577508d2014-06-20 00:23:57 +0000845 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 m_broadcaster_manager_sp->Clear();
847
848 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000849 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 m_terminal_state.Clear();
851 if (m_input_file_sp)
852 m_input_file_sp->GetFile().Close();
853
854 m_command_interpreter_ap->Clear();
855 });
Greg Clayton44d93782014-01-27 23:43:24 +0000856}
857
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858bool Debugger::GetCloseInputOnEOF() const {
859 // return m_input_comm.GetCloseOnEOF();
860 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000861}
862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863void Debugger::SetCloseInputOnEOF(bool b) {
864 // m_input_comm.SetCloseOnEOF(b);
865}
866
867bool Debugger::GetAsyncExecution() {
868 return !m_command_interpreter_ap->GetSynchronous();
869}
870
871void Debugger::SetAsyncExecution(bool async_execution) {
872 m_command_interpreter_ap->SetSynchronous(!async_execution);
873}
874
875void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership) {
876 if (m_input_file_sp)
877 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
878 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000879 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880
881 File &in_file = m_input_file_sp->GetFile();
882 if (!in_file.IsValid())
883 in_file.SetStream(stdin, true);
884
Adrian Prantl05097242018-04-30 16:49:04 +0000885 // Save away the terminal state if that is relevant, so that we can restore
886 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 SaveInputTerminalState();
888}
889
890void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
891 if (m_output_file_sp)
892 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
893 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000894 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895
896 File &out_file = m_output_file_sp->GetFile();
897 if (!out_file.IsValid())
898 out_file.SetStream(stdout, false);
899
Adrian Prantl05097242018-04-30 16:49:04 +0000900 // do not create the ScriptInterpreter just for setting the output file
901 // handle as the constructor will know how to do the right thing on its own
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 const bool can_create = false;
903 ScriptInterpreter *script_interpreter =
904 GetCommandInterpreter().GetScriptInterpreter(can_create);
905 if (script_interpreter)
906 script_interpreter->ResetOutputFileHandle(fh);
907}
908
909void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
910 if (m_error_file_sp)
911 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
912 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000913 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914
915 File &err_file = m_error_file_sp->GetFile();
916 if (!err_file.IsValid())
917 err_file.SetStream(stderr, false);
918}
919
920void Debugger::SaveInputTerminalState() {
921 if (m_input_file_sp) {
922 File &in_file = m_input_file_sp->GetFile();
923 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
924 m_terminal_state.Save(in_file.GetDescriptor(), true);
925 }
926}
927
928void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
929
930ExecutionContext Debugger::GetSelectedExecutionContext() {
931 ExecutionContext exe_ctx;
932 TargetSP target_sp(GetSelectedTarget());
933 exe_ctx.SetTargetSP(target_sp);
934
935 if (target_sp) {
936 ProcessSP process_sp(target_sp->GetProcessSP());
937 exe_ctx.SetProcessSP(process_sp);
938 if (process_sp && !process_sp->IsRunning()) {
939 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
940 if (thread_sp) {
941 exe_ctx.SetThreadSP(thread_sp);
942 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
943 if (exe_ctx.GetFramePtr() == nullptr)
944 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
945 }
946 }
947 }
948 return exe_ctx;
949}
950
951void Debugger::DispatchInputInterrupt() {
952 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
953 IOHandlerSP reader_sp(m_input_reader_stack.Top());
954 if (reader_sp)
955 reader_sp->Interrupt();
956}
957
958void Debugger::DispatchInputEndOfFile() {
959 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
960 IOHandlerSP reader_sp(m_input_reader_stack.Top());
961 if (reader_sp)
962 reader_sp->GotEOF();
963}
964
965void Debugger::ClearIOHandlers() {
966 // The bottom input reader should be the main debugger input reader. We do
967 // not want to close that one here.
968 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
969 while (m_input_reader_stack.GetSize() > 1) {
970 IOHandlerSP reader_sp(m_input_reader_stack.Top());
971 if (reader_sp)
972 PopIOHandler(reader_sp);
973 }
974}
975
976void Debugger::ExecuteIOHandlers() {
977 while (true) {
978 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000981
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000983
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 // Remove all input readers that are done from the top of the stack
985 while (true) {
986 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
987 if (top_reader_sp && top_reader_sp->GetIsDone())
988 PopIOHandler(top_reader_sp);
989 else
990 break;
991 }
992 }
993 ClearIOHandlers();
994}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000995
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
997 return m_input_reader_stack.IsTop(reader_sp);
998}
Greg Clayton44d93782014-01-27 23:43:24 +0000999
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
1001 IOHandler::Type second_top_type) {
1002 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1003}
1004
1005void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1006 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
1007 m_input_reader_stack.PrintAsync(stream.get(), s, len);
1008}
1009
1010ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1011 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
1012}
1013
1014const char *Debugger::GetIOHandlerCommandPrefix() {
1015 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
1016}
1017
1018const char *Debugger::GetIOHandlerHelpPrologue() {
1019 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1020}
1021
1022void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
1023 PushIOHandler(reader_sp);
1024
1025 IOHandlerSP top_reader_sp = reader_sp;
1026 while (top_reader_sp) {
1027 top_reader_sp->Run();
1028
1029 if (top_reader_sp.get() == reader_sp.get()) {
1030 if (PopIOHandler(reader_sp))
1031 break;
1032 }
1033
1034 while (true) {
1035 top_reader_sp = m_input_reader_stack.Top();
1036 if (top_reader_sp && top_reader_sp->GetIsDone())
1037 PopIOHandler(top_reader_sp);
1038 else
1039 break;
1040 }
1041 }
1042}
1043
1044void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
1045 StreamFileSP &out,
1046 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +00001047 // Before an IOHandler runs, it must have in/out/err streams. This function
1048 // is called when one ore more of the streams are nullptr. We use the top
1049 // input reader's in/out/err streams, or fall back to the debugger file
1050 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051
1052 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1053 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1054 // If no STDIN has been set, then set it appropriately
1055 if (!in) {
1056 if (top_reader_sp)
1057 in = top_reader_sp->GetInputStreamFile();
1058 else
1059 in = GetInputFile();
1060
1061 // If there is nothing, use stdin
1062 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001063 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 }
1065 // If no STDOUT has been set, then set it appropriately
1066 if (!out) {
1067 if (top_reader_sp)
1068 out = top_reader_sp->GetOutputStreamFile();
1069 else
1070 out = GetOutputFile();
1071
1072 // If there is nothing, use stdout
1073 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001074 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 }
1076 // If no STDERR has been set, then set it appropriately
1077 if (!err) {
1078 if (top_reader_sp)
1079 err = top_reader_sp->GetErrorStreamFile();
1080 else
1081 err = GetErrorFile();
1082
1083 // If there is nothing, use stderr
1084 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001085 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 }
1087}
1088
Raphael Isemannc01783a2018-08-29 22:50:54 +00001089void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1090 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001091 if (!reader_sp)
1092 return;
1093
1094 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1095
1096 // Get the current top input reader...
1097 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1098
1099 // Don't push the same IO handler twice...
1100 if (reader_sp == top_reader_sp)
1101 return;
1102
1103 // Push our new input reader
1104 m_input_reader_stack.Push(reader_sp);
1105 reader_sp->Activate();
1106
Adrian Prantl05097242018-04-30 16:49:04 +00001107 // Interrupt the top input reader to it will exit its Run() function and let
1108 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 if (top_reader_sp) {
1110 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001111 if (cancel_top_handler)
1112 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 }
1114}
1115
1116bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1117 if (!pop_reader_sp)
1118 return false;
1119
1120 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1121
Adrian Prantl05097242018-04-30 16:49:04 +00001122 // The reader on the stop of the stack is done, so let the next read on the
1123 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 if (m_input_reader_stack.IsEmpty())
1125 return false;
1126
1127 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1128
1129 if (pop_reader_sp != reader_sp)
1130 return false;
1131
1132 reader_sp->Deactivate();
1133 reader_sp->Cancel();
1134 m_input_reader_stack.Pop();
1135
1136 reader_sp = m_input_reader_stack.Top();
1137 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001138 reader_sp->Activate();
1139
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 return true;
1141}
1142
1143StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001144 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145}
1146
1147StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001148 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149}
1150
1151size_t Debugger::GetNumDebuggers() {
1152 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1153 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1154 return g_debugger_list_ptr->size();
1155 }
1156 return 0;
1157}
1158
1159lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1160 DebuggerSP debugger_sp;
1161
1162 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1163 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1164 if (index < g_debugger_list_ptr->size())
1165 debugger_sp = g_debugger_list_ptr->at(index);
1166 }
1167
1168 return debugger_sp;
1169}
1170
1171DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1172 DebuggerSP debugger_sp;
1173
1174 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1175 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1176 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1177 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1178 if ((*pos)->GetID() == id) {
1179 debugger_sp = *pos;
1180 break;
1181 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001182 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 }
1184 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001185}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001186
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1188 const SymbolContext *sc,
1189 const SymbolContext *prev_sc,
1190 const ExecutionContext *exe_ctx,
1191 const Address *addr, Stream &s) {
1192 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001193
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 if (format == nullptr) {
1195 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1196 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1197 if (format == nullptr) {
1198 FormatEntity::Parse("${addr}: ", format_entry);
1199 format = &format_entry;
1200 }
1201 }
1202 bool function_changed = false;
1203 bool initial_function = false;
1204 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1205 if (sc && (sc->function || sc->symbol)) {
1206 if (prev_sc->symbol && sc->symbol) {
1207 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1208 prev_sc->symbol->GetType())) {
1209 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001210 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 } else if (prev_sc->function && sc->function) {
1212 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1213 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001214 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 }
Adrian Prantl05097242018-04-30 16:49:04 +00001218 // The first context on a list of instructions will have a prev_sc that has
1219 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 // would return false. But we do get a prev_sc pointer.
1221 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1222 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1223 initial_function = true;
1224 }
1225 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1226 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001227}
1228
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1230 void *baton) {
1231 // For simplicity's sake, I am not going to deal with how to close down any
1232 // open logging streams, I just redirect everything from here on out to the
1233 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001234 m_log_callback_stream_sp =
1235 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001236}
1237
Pavel Labath5e336902017-03-01 10:08:40 +00001238bool Debugger::EnableLog(llvm::StringRef channel,
1239 llvm::ArrayRef<const char *> categories,
1240 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001241 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001242 const bool should_close = true;
1243 const bool unbuffered = true;
1244
1245 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 if (m_log_callback_stream_sp) {
1247 log_stream_sp = m_log_callback_stream_sp;
1248 // For now when using the callback mode you always get thread & timestamp.
1249 log_options |=
1250 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001251 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001252 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1253 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001255 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 if (pos != m_log_streams.end())
1257 log_stream_sp = pos->second.lock();
1258 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001259 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1260 if (log_options & LLDB_LOG_OPTION_APPEND)
1261 flags |= llvm::sys::fs::F_Append;
1262 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001263 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1264 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001265 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001266 return false;
1267 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001268 log_stream_sp =
1269 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001271 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 }
1273 assert(log_stream_sp);
1274
1275 if (log_options == 0)
1276 log_options =
1277 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1278
1279 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1280 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001281}
1282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283SourceManager &Debugger::GetSourceManager() {
1284 if (!m_source_manager_ap)
Zachary Turner2f3df612017-04-06 21:28:29 +00001285 m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 return *m_source_manager_ap;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001287}
1288
Greg Clayton44d93782014-01-27 23:43:24 +00001289// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1291 using namespace lldb;
1292 const uint32_t event_type =
1293 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1294 event_sp);
1295
1296 // if (event_type & eBreakpointEventTypeAdded
1297 // || event_type & eBreakpointEventTypeRemoved
1298 // || event_type & eBreakpointEventTypeEnabled
1299 // || event_type & eBreakpointEventTypeDisabled
1300 // || event_type & eBreakpointEventTypeCommandChanged
1301 // || event_type & eBreakpointEventTypeConditionChanged
1302 // || event_type & eBreakpointEventTypeIgnoreChanged
1303 // || event_type & eBreakpointEventTypeLocationsResolved)
1304 // {
1305 // // Don't do anything about these events, since the breakpoint
1306 // commands already echo these actions.
1307 // }
1308 //
1309 if (event_type & eBreakpointEventTypeLocationsAdded) {
1310 uint32_t num_new_locations =
1311 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1312 event_sp);
1313 if (num_new_locations > 0) {
1314 BreakpointSP breakpoint =
1315 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1316 StreamSP output_sp(GetAsyncOutputStream());
1317 if (output_sp) {
1318 output_sp->Printf("%d location%s added to breakpoint %d\n",
1319 num_new_locations, num_new_locations == 1 ? "" : "s",
1320 breakpoint->GetID());
1321 output_sp->Flush();
1322 }
Greg Clayton44d93782014-01-27 23:43:24 +00001323 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 }
1325 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1326 // {
1327 // // These locations just get disabled, not sure it is worth spamming
1328 // folks about this on the command line.
1329 // }
1330 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1331 // {
1332 // // This might be an interesting thing to note, but I'm going to
1333 // leave it quiet for now, it just looked noisy.
1334 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001335}
1336
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1338 size_t total_bytes = 0;
1339 if (stream == nullptr)
1340 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001341
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342 if (stream) {
1343 // The process has stuff waiting for stdout; get it and write it out to the
1344 // appropriate place.
1345 if (process == nullptr) {
1346 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1347 if (target_sp)
1348 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001349 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001351 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 size_t len;
1353 char stdio_buffer[1024];
1354 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1355 error)) > 0) {
1356 stream->Write(stdio_buffer, len);
1357 total_bytes += len;
1358 }
1359 }
1360 stream->Flush();
1361 }
1362 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001363}
1364
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1366 size_t total_bytes = 0;
1367 if (stream == nullptr)
1368 stream = GetOutputFile().get();
1369
1370 if (stream) {
1371 // The process has stuff waiting for stderr; get it and write it out to the
1372 // appropriate place.
1373 if (process == nullptr) {
1374 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1375 if (target_sp)
1376 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001377 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001379 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 size_t len;
1381 char stdio_buffer[1024];
1382 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1383 error)) > 0) {
1384 stream->Write(stdio_buffer, len);
1385 total_bytes += len;
1386 }
1387 }
1388 stream->Flush();
1389 }
1390 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001391}
1392
1393// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001394void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1395 using namespace lldb;
1396 const uint32_t event_type = event_sp->GetType();
1397 ProcessSP process_sp =
1398 (event_type == Process::eBroadcastBitStructuredData)
1399 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1400 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 StreamSP output_stream_sp = GetAsyncOutputStream();
1403 StreamSP error_stream_sp = GetAsyncErrorStream();
1404 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001405
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 if (!gui_enabled) {
1407 bool pop_process_io_handler = false;
1408 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 bool state_is_stopped = false;
1411 const bool got_state_changed =
1412 (event_type & Process::eBroadcastBitStateChanged) != 0;
1413 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1414 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1415 const bool got_structured_data =
1416 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001417
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 if (got_state_changed) {
1419 StateType event_state =
1420 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1421 state_is_stopped = StateIsStoppedState(event_state, false);
1422 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 // Display running state changes first before any STDIO
1425 if (got_state_changed && !state_is_stopped) {
1426 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1427 pop_process_io_handler);
1428 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001429
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 // Now display and STDOUT
1431 if (got_stdout || got_state_changed) {
1432 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1433 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001434
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435 // Now display and STDERR
1436 if (got_stderr || got_state_changed) {
1437 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1438 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001439
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 // Give structured data events an opportunity to display.
1441 if (got_structured_data) {
1442 StructuredDataPluginSP plugin_sp =
1443 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1444 if (plugin_sp) {
1445 auto structured_data_sp =
1446 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1447 if (output_stream_sp) {
1448 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001449 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 plugin_sp->GetDescription(structured_data_sp, content_stream);
1451 if (error.Success()) {
1452 if (!content_stream.GetString().empty()) {
1453 // Add newline.
1454 content_stream.PutChar('\n');
1455 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001456
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001458 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001459 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 } else {
1461 error_stream_sp->Printf("Failed to print structured "
1462 "data with plugin %s: %s",
1463 plugin_sp->GetPluginName().AsCString(),
1464 error.AsCString());
1465 }
Todd Fiala75930012016-08-19 04:21:48 +00001466 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001468 }
Greg Clayton44d93782014-01-27 23:43:24 +00001469
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 // Now display any stopped state changes after any STDIO
1471 if (got_state_changed && state_is_stopped) {
1472 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1473 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001474 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475
1476 output_stream_sp->Flush();
1477 error_stream_sp->Flush();
1478
1479 if (pop_process_io_handler)
1480 process_sp->PopProcessIOHandler();
1481 }
Greg Clayton44d93782014-01-27 23:43:24 +00001482}
1483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001485 // At present the only thread event we handle is the Frame Changed event, and
1486 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 using namespace lldb;
1488 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001489 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490 if (event_type == Thread::eBroadcastBitStackChanged ||
1491 event_type == Thread::eBroadcastBitThreadSelected) {
1492 ThreadSP thread_sp(
1493 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1494 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001495 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001496 }
1497 }
Greg Clayton44d93782014-01-27 23:43:24 +00001498}
1499
Kate Stoneb9c1b512016-09-06 20:57:50 +00001500bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1501
1502void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1503 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001504}
1505
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1507 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001508}
1509
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510void Debugger::DefaultEventHandler() {
1511 ListenerSP listener_sp(GetListener());
1512 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1513 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1514 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1515 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1516 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001517
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 BroadcastEventSpec process_event_spec(
1519 broadcaster_class_process,
1520 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1521 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001522
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1524 Thread::eBroadcastBitStackChanged |
1525 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001526
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1528 target_event_spec);
1529 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1530 process_event_spec);
1531 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1532 thread_event_spec);
1533 listener_sp->StartListeningForEvents(
1534 m_command_interpreter_ap.get(),
1535 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1536 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1537 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001538
Adrian Prantl05097242018-04-30 16:49:04 +00001539 // Let the thread that spawned us know that we have started up and that we
1540 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001542
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543 bool done = false;
1544 while (!done) {
1545 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001546 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 if (event_sp) {
1548 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1549 if (broadcaster) {
1550 uint32_t event_type = event_sp->GetType();
1551 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1552 if (broadcaster_class == broadcaster_class_process) {
1553 HandleProcessEvent(event_sp);
1554 } else if (broadcaster_class == broadcaster_class_target) {
1555 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1556 event_sp.get())) {
1557 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001558 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559 } else if (broadcaster_class == broadcaster_class_thread) {
1560 HandleThreadEvent(event_sp);
1561 } else if (broadcaster == m_command_interpreter_ap.get()) {
1562 if (event_type &
1563 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1564 done = true;
1565 } else if (event_type &
1566 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1567 const char *data = reinterpret_cast<const char *>(
1568 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1569 if (data && data[0]) {
1570 StreamSP error_sp(GetAsyncErrorStream());
1571 if (error_sp) {
1572 error_sp->PutCString(data);
1573 error_sp->Flush();
1574 }
1575 }
1576 } else if (event_type & CommandInterpreter::
1577 eBroadcastBitAsynchronousOutputData) {
1578 const char *data = reinterpret_cast<const char *>(
1579 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1580 if (data && data[0]) {
1581 StreamSP output_sp(GetAsyncOutputStream());
1582 if (output_sp) {
1583 output_sp->PutCString(data);
1584 output_sp->Flush();
1585 }
1586 }
1587 }
1588 }
Greg Clayton44d93782014-01-27 23:43:24 +00001589 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590
1591 if (m_forward_listener_sp)
1592 m_forward_listener_sp->AddEvent(event_sp);
1593 }
Greg Clayton44d93782014-01-27 23:43:24 +00001594 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 }
Greg Clayton44d93782014-01-27 23:43:24 +00001596}
1597
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1599 ((Debugger *)arg)->DefaultEventHandler();
1600 return NULL;
Greg Clayton44d93782014-01-27 23:43:24 +00001601}
1602
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603bool Debugger::StartEventHandlerThread() {
1604 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001605 // We must synchronize with the DefaultEventHandler() thread to ensure it
1606 // is up and running and listening to events before we return from this
1607 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001609 ConstString full_name("lldb.debugger.event-handler");
1610 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1612 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001613
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001614 auto thread_name =
1615 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1616 full_name.AsCString() : "dbg.evt-handler";
1617
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618 // Use larger 8MB stack for this thread
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001619 m_event_handler_thread = ThreadLauncher::LaunchThread(thread_name,
1620 EventHandlerThread, this, nullptr, g_debugger_event_thread_stack_bytes);
Greg Claytonafa91e332014-12-01 22:41:27 +00001621
Adrian Prantl05097242018-04-30 16:49:04 +00001622 // Make sure DefaultEventHandler() is running and listening to events
1623 // before we return from this function. We are only listening for events of
1624 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1625 // event, we just need to wait an infinite amount of time for it (nullptr
1626 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001628 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 }
1630 return m_event_handler_thread.IsJoinable();
1631}
1632
1633void Debugger::StopEventHandlerThread() {
1634 if (m_event_handler_thread.IsJoinable()) {
1635 GetCommandInterpreter().BroadcastEvent(
1636 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1637 m_event_handler_thread.Join(nullptr);
1638 }
1639}
1640
1641lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1642 Debugger *debugger = (Debugger *)arg;
1643 debugger->ExecuteIOHandlers();
1644 debugger->StopEventHandlerThread();
1645 return NULL;
1646}
1647
1648bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1649
1650bool Debugger::StartIOHandlerThread() {
1651 if (!m_io_handler_thread.IsJoinable())
1652 m_io_handler_thread = ThreadLauncher::LaunchThread(
1653 "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1654 8 * 1024 * 1024); // Use larger 8MB stack for this thread
1655 return m_io_handler_thread.IsJoinable();
1656}
1657
1658void Debugger::StopIOHandlerThread() {
1659 if (m_io_handler_thread.IsJoinable()) {
1660 if (m_input_file_sp)
1661 m_input_file_sp->GetFile().Close();
1662 m_io_handler_thread.Join(nullptr);
1663 }
1664}
1665
1666void Debugger::JoinIOHandlerThread() {
1667 if (HasIOHandlerThread()) {
1668 thread_result_t result;
1669 m_io_handler_thread.Join(&result);
1670 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1671 }
1672}
1673
1674Target *Debugger::GetDummyTarget() {
1675 return m_target_list.GetDummyTarget(*this).get();
1676}
1677
1678Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1679 Target *target = nullptr;
1680 if (!prefer_dummy) {
1681 target = m_target_list.GetSelectedTarget().get();
1682 if (target)
1683 return target;
1684 }
1685
1686 return GetDummyTarget();
1687}
1688
Zachary Turner97206d52017-05-12 04:51:55 +00001689Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1690 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 FileSpec repl_executable;
1692
1693 if (language == eLanguageTypeUnknown) {
1694 std::set<LanguageType> repl_languages;
1695
1696 Language::GetLanguagesSupportingREPLs(repl_languages);
1697
1698 if (repl_languages.size() == 1) {
1699 language = *repl_languages.begin();
1700 } else if (repl_languages.empty()) {
1701 err.SetErrorStringWithFormat(
1702 "LLDB isn't configured with REPL support for any languages.");
1703 return err;
1704 } else {
1705 err.SetErrorStringWithFormat(
1706 "Multiple possible REPL languages. Please specify a language.");
1707 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709 }
Greg Clayton44d93782014-01-27 23:43:24 +00001710
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 Target *const target =
1712 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001713
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001715
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001717 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 }
1719
1720 if (!repl_sp) {
1721 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1722 Language::GetNameForLanguageType(language));
1723 return err;
1724 }
1725
1726 repl_sp->SetCompilerOptions(repl_options);
1727 repl_sp->RunLoop();
1728
1729 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001730}