blob: e3cd18aa35e334b3a9aa72f04b14fbc1b9831031 [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[] = {
Jonas Devliegheree063ecc2019-08-02 00:18:44 +000096 {
97 Debugger::eStopDisassemblyTypeNever,
98 "never",
99 "Never show disassembly when displaying a stop context.",
100 },
101 {
102 Debugger::eStopDisassemblyTypeNoDebugInfo,
103 "no-debuginfo",
104 "Show disassembly when there is no debug information.",
105 },
106 {
107 Debugger::eStopDisassemblyTypeNoSource,
108 "no-source",
109 "Show disassembly when there is no source information, or the source "
110 "file "
111 "is missing when displaying a stop context.",
112 },
113 {
114 Debugger::eStopDisassemblyTypeAlways,
115 "always",
116 "Always show disassembly when displaying a stop context.",
117 },
118};
Greg Claytone372b982011-11-21 21:44:34 +0000119
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000120static constexpr OptionEnumValueElement g_language_enumerators[] = {
Jonas Devliegheree063ecc2019-08-02 00:18:44 +0000121 {
122 eScriptLanguageNone,
123 "none",
124 "Disable scripting languages.",
125 },
126 {
127 eScriptLanguagePython,
128 "python",
129 "Select python as the default scripting language.",
130 },
131 {
132 eScriptLanguageDefault,
133 "default",
134 "Select the lldb default as the default scripting language.",
135 },
136};
Greg Claytone372b982011-11-21 21:44:34 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138#define MODULE_WITH_FUNC \
139 "{ " \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000140 "${module.file.basename}{`${function.name-with-args}" \
141 "{${frame.no-debug}${function.pc-offset}}}}"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000142
143#define MODULE_WITH_FUNC_NO_ARGS \
144 "{ " \
145 "${module.file.basename}{`${function.name-without-args}" \
146 "{${frame.no-debug}${function.pc-offset}}}}"
147
Adrian Prantl4954f6a2018-09-05 23:52:08 +0000148#define FILE_AND_LINE \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000149 "{ at ${ansi.fg.cyan}${line.file.basename}${ansi.normal}" \
150 ":${ansi.fg.yellow}${line.number}${ansi.normal}" \
151 "{:${ansi.fg.yellow}${line.column}${ansi.normal}}}"
152
Jason Molenda6ab659a2015-07-29 00:42:47 +0000153#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000154
Vedant Kumar4b36f792018-10-05 23:23:15 +0000155#define IS_ARTIFICIAL "{${frame.is-artificial} [artificial]}"
156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157#define DEFAULT_THREAD_FORMAT \
158 "thread #${thread.index}: tid = ${thread.id%tid}" \
159 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000160 "{, name = ${ansi.fg.green}'${thread.name}'${ansi.normal}}" \
161 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
162 "{, activity = " \
163 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 "{, ${thread.info.trace_messages} messages}" \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000165 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 "{\\nReturn value: ${thread.return-value}}" \
167 "{\\nCompleted expression: ${thread.completed-expression}}" \
168 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000169
Jim Ingham6a9767c2016-11-08 20:36:40 +0000170#define DEFAULT_THREAD_STOP_FORMAT \
171 "thread #${thread.index}{, name = '${thread.name}'}" \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000172 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
173 "{, activity = " \
174 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000175 "{, ${thread.info.trace_messages} messages}" \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000176 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000177 "{\\nReturn value: ${thread.return-value}}" \
178 "{\\nCompleted expression: ${thread.completed-expression}}" \
179 "\\n"
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181#define DEFAULT_FRAME_FORMAT \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000182 "frame #${frame.index}: " \
183 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC FILE_AND_LINE \
Vedant Kumar4b36f792018-10-05 23:23:15 +0000184 IS_OPTIMIZED IS_ARTIFICIAL "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000185
Pavel Labath7f1c1212017-06-12 16:25:24 +0000186#define DEFAULT_FRAME_FORMAT_NO_ARGS \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000187 "frame #${frame.index}: " \
188 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC_NO_ARGS \
189 FILE_AND_LINE IS_OPTIMIZED IS_ARTIFICIAL "\\n"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000190
Jason Molendac980fa92015-02-13 23:24:21 +0000191// Three parts to this disassembly format specification:
192// 1. If this is a new function/symbol (no previous symbol/function), print
193// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194// 2. If this is a symbol context change (different from previous
195// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000196// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197// 3. print
198// address <+offset>:
199#define DEFAULT_DISASSEMBLY_FORMAT \
200 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
Jonas Devliegheree43be152018-10-01 13:20:15 +0000201 "without-args}}:\\n}{${function.changed}\\n{${module.file.basename}`}{${" \
202 "function.name-without-args}}:\\n}{${current-pc-arrow} " \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 "}${addr-file-or-load}{ " \
204 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000205
Adrian Prantl05097242018-04-30 16:49:04 +0000206// gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
207// file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
208// offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000209
210// lldb's original format for disassembly would look like this format string -
Adrian Prantl05097242018-04-30 16:49:04 +0000211// {${function.initial-function}{${module.file.basename}`}{${function.name-
212// without-
213// args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
214// without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000215
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000216static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
Jonas Devliegheree063ecc2019-08-02 00:18:44 +0000217 {
218 eStopShowColumnAnsiOrCaret,
219 "ansi-or-caret",
220 "Highlight the stop column with ANSI terminal codes when color/ANSI "
221 "mode is enabled; otherwise, fall back to using a text-only caret (^) "
222 "as if \"caret-only\" mode was selected.",
223 },
224 {
225 eStopShowColumnAnsi,
226 "ansi",
227 "Highlight the stop column with ANSI terminal codes when running LLDB "
228 "with color/ANSI enabled.",
229 },
230 {
231 eStopShowColumnCaret,
232 "caret",
233 "Highlight the stop column with a caret character (^) underneath the "
234 "stop column. This method introduces a new line in source listings "
235 "that display thread stop locations.",
236 },
237 {
238 eStopShowColumnNone,
239 "none",
240 "Do not highlight the stop column.",
241 },
242};
Todd Fiala9666ba72016-09-21 20:13:14 +0000243
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000244#define LLDB_PROPERTIES_debugger
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000245#include "CoreProperties.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000248#define LLDB_PROPERTIES_debugger
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000249#include "CorePropertiesEnum.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000250};
251
Eugene Zelenkodf370552016-03-02 02:18:18 +0000252LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000253
Zachary Turner97206d52017-05-12 04:51:55 +0000254Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
255 VarSetOperationType op,
256 llvm::StringRef property_path,
257 llvm::StringRef value) {
Jonas Devliegheree063ecc2019-08-02 00:18:44 +0000258 bool is_load_script =
259 (property_path == "target.load-script-from-symbol-file");
Zachary Turner31d97a52016-11-17 18:08:12 +0000260 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 TargetSP target_sp;
262 LoadScriptFromSymFile load_script_old_value;
263 if (is_load_script && exe_ctx->GetTargetSP()) {
264 target_sp = exe_ctx->GetTargetSP();
265 load_script_old_value =
266 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
267 }
Zachary Turner97206d52017-05-12 04:51:55 +0000268 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 if (error.Success()) {
270 // FIXME it would be nice to have "on-change" callbacks for properties
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000271 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000272 llvm::StringRef new_prompt = GetPrompt();
Jonas Devlieghere4b3c0fd2019-08-21 00:50:46 +0000273 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 new_prompt, GetUseColor());
275 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000276 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 GetCommandInterpreter().UpdatePrompt(new_prompt);
Jonas Devliegherea8f3ae72019-08-14 22:19:23 +0000278 auto bytes = std::make_unique<EventDataBytes>(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000279 auto prompt_change_event_sp = std::make_shared<Event>(
280 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000282 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 // use-color changed. Ping the prompt so it can reset the ansi terminal
284 // codes.
285 SetPrompt(GetPrompt());
286 } else if (is_load_script && target_sp &&
287 load_script_old_value == eLoadScriptFromSymFileWarn) {
288 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
289 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000290 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 StreamString feedback_stream;
292 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
293 StreamFileSP stream_sp(GetErrorFile());
294 if (stream_sp) {
295 for (auto error : errors) {
296 stream_sp->Printf("%s\n", error.AsCString());
297 }
298 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000299 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 }
301 }
302 }
303 } else if (is_escape_non_printables) {
304 DataVisualization::ForceUpdate();
305 }
306 }
307 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000308}
309
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310bool Debugger::GetAutoConfirm() const {
311 const uint32_t idx = ePropertyAutoConfirm;
312 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000313 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000314}
315
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
317 const uint32_t idx = ePropertyDisassemblyFormat;
318 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000319}
320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321const FormatEntity::Entry *Debugger::GetFrameFormat() const {
322 const uint32_t idx = ePropertyFrameFormat;
323 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000324}
325
Pavel Labath7f1c1212017-06-12 16:25:24 +0000326const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
327 const uint32_t idx = ePropertyFrameFormatUnique;
328 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
329}
330
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331bool Debugger::GetNotifyVoid() const {
332 const uint32_t idx = ePropertyNotiftVoid;
333 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000334 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000335}
336
Zachary Turner514d8cd2016-09-23 18:06:53 +0000337llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 const uint32_t idx = ePropertyPrompt;
339 return m_collection_sp->GetPropertyAtIndexAsString(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000340 nullptr, idx, g_debugger_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000341}
342
Zachary Turner514d8cd2016-09-23 18:06:53 +0000343void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 const uint32_t idx = ePropertyPrompt;
345 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000346 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 std::string str =
Jonas Devlieghere4b3c0fd2019-08-21 00:50:46 +0000348 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000350 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000352}
353
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000354llvm::StringRef Debugger::GetReproducerPath() const {
355 auto &r = repro::Reproducer::Instance();
356 return r.GetReproducerPath().GetCString();
357}
358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359const FormatEntity::Entry *Debugger::GetThreadFormat() const {
360 const uint32_t idx = ePropertyThreadFormat;
361 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000362}
363
Jim Ingham6a9767c2016-11-08 20:36:40 +0000364const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
365 const uint32_t idx = ePropertyThreadStopFormat;
366 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
370 const uint32_t idx = ePropertyScriptLanguage;
371 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000372 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000373}
374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
376 const uint32_t idx = ePropertyScriptLanguage;
377 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
378 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000379}
380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381uint32_t Debugger::GetTerminalWidth() const {
382 const uint32_t idx = ePropertyTerminalWidth;
383 return m_collection_sp->GetPropertyAtIndexAsSInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000384 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000385}
386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387bool Debugger::SetTerminalWidth(uint32_t term_width) {
388 const uint32_t idx = ePropertyTerminalWidth;
389 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000390}
391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392bool Debugger::GetUseExternalEditor() const {
393 const uint32_t idx = ePropertyUseExternalEditor;
394 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000395 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000396}
Greg Claytone372b982011-11-21 21:44:34 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398bool Debugger::SetUseExternalEditor(bool b) {
399 const uint32_t idx = ePropertyUseExternalEditor;
400 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000401}
Enrico Granata553fad52013-10-25 23:09:40 +0000402
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403bool Debugger::GetUseColor() const {
404 const uint32_t idx = ePropertyUseColor;
405 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000406 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000407}
408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409bool Debugger::SetUseColor(bool b) {
410 const uint32_t idx = ePropertyUseColor;
411 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
412 SetPrompt(GetPrompt());
413 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000414}
415
Raphael Isemann566afa02018-08-02 00:30:15 +0000416bool Debugger::GetHighlightSource() const {
417 const uint32_t idx = ePropertyHighlightSource;
418 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000419 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Raphael Isemann566afa02018-08-02 00:30:15 +0000420}
421
Todd Fiala9666ba72016-09-21 20:13:14 +0000422StopShowColumn Debugger::GetStopShowColumn() const {
423 const uint32_t idx = ePropertyStopShowColumn;
424 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000425 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Todd Fiala9666ba72016-09-21 20:13:14 +0000426}
427
Raphael Isemann20786322018-08-30 00:09:21 +0000428llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000429 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000430 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000431}
432
Raphael Isemann20786322018-08-30 00:09:21 +0000433llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000434 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000435 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000436}
437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438uint32_t Debugger::GetStopSourceLineCount(bool before) const {
439 const uint32_t idx =
440 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
441 return m_collection_sp->GetPropertyAtIndexAsSInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000442 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000443}
444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
446 const uint32_t idx = ePropertyStopDisassemblyDisplay;
447 return (Debugger::StopDisassemblyType)
448 m_collection_sp->GetPropertyAtIndexAsEnumeration(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000449 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000450}
451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452uint32_t Debugger::GetDisassemblyLineCount() const {
453 const uint32_t idx = ePropertyStopDisassemblyCount;
454 return m_collection_sp->GetPropertyAtIndexAsSInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000455 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000456}
457
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458bool Debugger::GetAutoOneLineSummaries() const {
459 const uint32_t idx = ePropertyAutoOneLineSummaries;
460 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000461}
462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463bool Debugger::GetEscapeNonPrintables() const {
464 const uint32_t idx = ePropertyEscapeNonPrintables;
465 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
466}
467
468bool Debugger::GetAutoIndent() const {
469 const uint32_t idx = ePropertyAutoIndent;
470 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
471}
472
473bool Debugger::SetAutoIndent(bool b) {
474 const uint32_t idx = ePropertyAutoIndent;
475 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
476}
477
478bool Debugger::GetPrintDecls() const {
479 const uint32_t idx = ePropertyPrintDecls;
480 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
481}
482
483bool Debugger::SetPrintDecls(bool b) {
484 const uint32_t idx = ePropertyPrintDecls;
485 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
486}
487
488uint32_t Debugger::GetTabSize() const {
489 const uint32_t idx = ePropertyTabSize;
490 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000491 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492}
493
494bool Debugger::SetTabSize(uint32_t tab_size) {
495 const uint32_t idx = ePropertyTabSize;
496 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000497}
498
Greg Clayton1b654882010-09-19 02:33:57 +0000499#pragma mark Debugger
500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501// const DebuggerPropertiesSP &
502// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000503//{
504// return m_properties_sp;
505//}
506//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
509 assert(g_debugger_list_ptr == nullptr &&
510 "Debugger::Initialize called more than once!");
511 g_debugger_list_mutex_ptr = new std::recursive_mutex();
512 g_debugger_list_ptr = new DebuggerList();
513 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000514}
515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516void Debugger::Terminate() {
517 assert(g_debugger_list_ptr &&
518 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
521 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000522 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
524 for (const auto &debugger : *g_debugger_list_ptr)
525 debugger->Clear();
526 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000527 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000529}
530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000534
Zachary Turner97206d52017-05-12 04:51:55 +0000535bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 if (g_load_plugin_callback) {
537 llvm::sys::DynamicLibrary dynlib =
538 g_load_plugin_callback(shared_from_this(), spec, error);
539 if (dynlib.isValid()) {
540 m_loaded_plugins.push_back(dynlib);
541 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000542 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000544 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
545 // if the public API layer isn't available (code is linking against all of
546 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 error.SetErrorString("Public API layer is not available");
548 }
549 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000550}
551
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000552static FileSystem::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000553LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000554 llvm::StringRef path) {
Zachary Turner97206d52017-05-12 04:51:55 +0000555 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000556
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000557 static ConstString g_dylibext(".dylib");
558 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559
560 if (!baton)
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000561 return FileSystem::eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562
563 Debugger *debugger = (Debugger *)baton;
564
Zachary Turner7d86ee52017-03-08 17:56:08 +0000565 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000566 // If we have a regular file, a symbolic link or unknown file type, try and
567 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 // enumeration might be enumerating a file system that doesn't have correct
569 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000570 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
571 ft == fs::file_type::type_unknown) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000572 FileSpec plugin_file_spec(path);
573 FileSystem::Instance().Resolve(plugin_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574
575 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
576 plugin_file_spec.GetFileNameExtension() != g_solibext) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000577 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579
Zachary Turner97206d52017-05-12 04:51:55 +0000580 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
582
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000583 return FileSystem::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000584 } else if (ft == fs::file_type::directory_file ||
585 ft == fs::file_type::symlink_file ||
586 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000587 // Try and recurse into anything that a directory or symbolic link. We must
588 // also do this for unknown as sometimes the directory enumeration might be
589 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 // information.
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000591 return FileSystem::eEnumerateDirectoryResultEnter;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 }
593
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000594 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000595}
596
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 const bool find_directories = true;
599 const bool find_files = true;
600 const bool find_other = true;
601 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000602 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000603 if (FileSystem::Instance().Exists(dir_spec) &&
604 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000605 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
606 find_files, find_other,
607 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000608 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000610
Pavel Labath60f028f2018-06-19 15:09:07 +0000611 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000612 if (FileSystem::Instance().Exists(dir_spec) &&
613 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000614 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
615 find_files, find_other,
616 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000617 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 }
619
620 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000621}
622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
624 void *baton) {
625 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
626 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
627 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
628 g_debugger_list_ptr->push_back(debugger_sp);
629 }
630 debugger_sp->InstanceInitialize();
631 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000632}
633
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634void Debugger::Destroy(DebuggerSP &debugger_sp) {
635 if (!debugger_sp)
636 return;
637
638 debugger_sp->Clear();
639
640 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
641 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
642 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
643 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
644 if ((*pos).get() == debugger_sp.get()) {
645 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000646 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000650}
651
Jonas Devliegheree063ecc2019-08-02 00:18:44 +0000652DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 DebuggerSP debugger_sp;
654 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
655 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
656 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
657 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
658 if ((*pos)->m_instance_name == instance_name) {
659 debugger_sp = *pos;
660 break;
661 }
Greg Clayton6920b522012-08-22 18:39:03 +0000662 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 }
664 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000665}
Greg Clayton66111032010-06-23 01:19:29 +0000666
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
668 TargetSP target_sp;
669 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
670 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
671 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
672 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
673 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
674 if (target_sp)
675 break;
Greg Clayton66111032010-06-23 01:19:29 +0000676 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 }
678 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000679}
680
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681TargetSP Debugger::FindTargetWithProcess(Process *process) {
682 TargetSP target_sp;
683 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
684 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
685 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
686 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
687 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
688 if (target_sp)
689 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 }
692 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000693}
694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
696 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000697 Properties(std::make_shared<OptionValueProperties>()),
698 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
699 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
700 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000701 m_input_recorder(nullptr),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
703 m_terminal_state(), m_target_list(*this), m_platform_list(),
704 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000705 m_source_manager_up(), m_source_file_cache(),
Jonas Devliegheref20dd1d2019-04-26 20:03:22 +0000706 m_command_interpreter_up(
Jonas Devliegherea8f3ae72019-08-14 22:19:23 +0000707 std::make_unique<CommandInterpreter>(*this, false)),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000708 m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(),
709 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
711 m_forward_listener_sp(), m_clear_once() {
712 char instance_cstr[256];
713 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
714 m_instance_name.SetCString(instance_cstr);
715 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000716 m_log_callback_stream_sp =
717 std::make_shared<StreamCallback>(log_callback, baton);
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000718 m_command_interpreter_up->Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 // Always add our default platform to the platform list
720 PlatformSP default_platform_sp(Platform::GetHostPlatform());
721 assert(default_platform_sp);
722 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000723
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000724 m_collection_sp->Initialize(g_debugger_properties);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 m_collection_sp->AppendProperty(
726 ConstString("target"),
727 ConstString("Settings specify to debugging targets."), true,
728 Target::GetGlobalProperties()->GetValueProperties());
729 m_collection_sp->AppendProperty(
730 ConstString("platform"), ConstString("Platform settings."), true,
731 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000732 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000733 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
734 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000735 if (m_command_interpreter_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 m_collection_sp->AppendProperty(
737 ConstString("interpreter"),
738 ConstString("Settings specify to the debugger's command interpreter."),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000739 true, m_command_interpreter_up->GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 }
741 OptionValueSInt64 *term_width =
742 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
743 nullptr, ePropertyTerminalWidth);
744 term_width->SetMinimumValue(10);
745 term_width->SetMaximumValue(1024);
746
747 // Turn off use-color if this is a dumb terminal.
748 const char *term = getenv("TERM");
749 if (term && !strcmp(term, "dumb"))
750 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000751 // Turn off use-color if we don't write to a terminal with color support.
752 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
753 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000754
755#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
756 // Enabling use of ANSI color codes because LLDB is using them to highlight
757 // text.
758 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000759#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760}
761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000763
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764void Debugger::Clear() {
Adrian Prantl05097242018-04-30 16:49:04 +0000765 // Make sure we call this function only once. With the C++ global destructor
766 // chain having a list of debuggers and with code that can be running on
767 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 //
769 // The following functions call Debugger::Clear():
770 // Debugger::~Debugger();
771 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
772 // static void Debugger::Terminate();
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000773 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000774 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 StopIOHandlerThread();
776 StopEventHandlerThread();
777 m_listener_sp->Clear();
778 int num_targets = m_target_list.GetNumTargets();
779 for (int i = 0; i < num_targets; i++) {
780 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
781 if (target_sp) {
782 ProcessSP process_sp(target_sp->GetProcessSP());
783 if (process_sp)
784 process_sp->Finalize();
785 target_sp->Destroy();
786 }
Greg Clayton577508d2014-06-20 00:23:57 +0000787 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 m_broadcaster_manager_sp->Clear();
789
790 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000791 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 m_terminal_state.Clear();
793 if (m_input_file_sp)
794 m_input_file_sp->GetFile().Close();
795
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000796 m_command_interpreter_up->Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 });
Greg Clayton44d93782014-01-27 23:43:24 +0000798}
799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800bool Debugger::GetCloseInputOnEOF() const {
801 // return m_input_comm.GetCloseOnEOF();
802 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000803}
804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805void Debugger::SetCloseInputOnEOF(bool b) {
806 // m_input_comm.SetCloseOnEOF(b);
807}
808
809bool Debugger::GetAsyncExecution() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000810 return !m_command_interpreter_up->GetSynchronous();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811}
812
813void Debugger::SetAsyncExecution(bool async_execution) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000814 m_command_interpreter_up->SetSynchronous(!async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815}
816
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000817repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
818
819void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership,
820 repro::DataRecorder *recorder) {
821 m_input_recorder = recorder;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 if (m_input_file_sp)
823 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
824 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000825 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826
827 File &in_file = m_input_file_sp->GetFile();
828 if (!in_file.IsValid())
829 in_file.SetStream(stdin, true);
830
Adrian Prantl05097242018-04-30 16:49:04 +0000831 // Save away the terminal state if that is relevant, so that we can restore
832 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 SaveInputTerminalState();
834}
835
836void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
837 if (m_output_file_sp)
838 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
839 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000840 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841
842 File &out_file = m_output_file_sp->GetFile();
843 if (!out_file.IsValid())
844 out_file.SetStream(stdout, false);
845
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000846 // Do not create the ScriptInterpreter just for setting the output file
847 // handle as the constructor will know how to do the right thing on its own.
848 if (ScriptInterpreter *script_interpreter =
849 GetScriptInterpreter(/*can_create=*/false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 script_interpreter->ResetOutputFileHandle(fh);
851}
852
853void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
854 if (m_error_file_sp)
855 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
856 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000857 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858
859 File &err_file = m_error_file_sp->GetFile();
860 if (!err_file.IsValid())
861 err_file.SetStream(stderr, false);
862}
863
864void Debugger::SaveInputTerminalState() {
865 if (m_input_file_sp) {
866 File &in_file = m_input_file_sp->GetFile();
867 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
868 m_terminal_state.Save(in_file.GetDescriptor(), true);
869 }
870}
871
872void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
873
874ExecutionContext Debugger::GetSelectedExecutionContext() {
875 ExecutionContext exe_ctx;
876 TargetSP target_sp(GetSelectedTarget());
877 exe_ctx.SetTargetSP(target_sp);
878
879 if (target_sp) {
880 ProcessSP process_sp(target_sp->GetProcessSP());
881 exe_ctx.SetProcessSP(process_sp);
882 if (process_sp && !process_sp->IsRunning()) {
883 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
884 if (thread_sp) {
885 exe_ctx.SetThreadSP(thread_sp);
886 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
887 if (exe_ctx.GetFramePtr() == nullptr)
888 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
889 }
890 }
891 }
892 return exe_ctx;
893}
894
895void Debugger::DispatchInputInterrupt() {
896 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
897 IOHandlerSP reader_sp(m_input_reader_stack.Top());
898 if (reader_sp)
899 reader_sp->Interrupt();
900}
901
902void Debugger::DispatchInputEndOfFile() {
903 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
904 IOHandlerSP reader_sp(m_input_reader_stack.Top());
905 if (reader_sp)
906 reader_sp->GotEOF();
907}
908
909void Debugger::ClearIOHandlers() {
910 // The bottom input reader should be the main debugger input reader. We do
911 // not want to close that one here.
912 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
913 while (m_input_reader_stack.GetSize() > 1) {
914 IOHandlerSP reader_sp(m_input_reader_stack.Top());
915 if (reader_sp)
916 PopIOHandler(reader_sp);
917 }
918}
919
920void Debugger::ExecuteIOHandlers() {
921 while (true) {
922 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000925
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000927
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 // Remove all input readers that are done from the top of the stack
929 while (true) {
930 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
931 if (top_reader_sp && top_reader_sp->GetIsDone())
932 PopIOHandler(top_reader_sp);
933 else
934 break;
935 }
936 }
937 ClearIOHandlers();
938}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000939
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
941 return m_input_reader_stack.IsTop(reader_sp);
942}
Greg Clayton44d93782014-01-27 23:43:24 +0000943
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
945 IOHandler::Type second_top_type) {
946 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
947}
948
949void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
950 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
951 m_input_reader_stack.PrintAsync(stream.get(), s, len);
952}
953
954ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
955 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
956}
957
958const char *Debugger::GetIOHandlerCommandPrefix() {
959 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
960}
961
962const char *Debugger::GetIOHandlerHelpPrologue() {
963 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
964}
965
966void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
967 PushIOHandler(reader_sp);
968
969 IOHandlerSP top_reader_sp = reader_sp;
970 while (top_reader_sp) {
971 top_reader_sp->Run();
972
973 if (top_reader_sp.get() == reader_sp.get()) {
974 if (PopIOHandler(reader_sp))
975 break;
976 }
977
978 while (true) {
979 top_reader_sp = m_input_reader_stack.Top();
980 if (top_reader_sp && top_reader_sp->GetIsDone())
981 PopIOHandler(top_reader_sp);
982 else
983 break;
984 }
985 }
986}
987
988void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
989 StreamFileSP &out,
990 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +0000991 // Before an IOHandler runs, it must have in/out/err streams. This function
992 // is called when one ore more of the streams are nullptr. We use the top
993 // input reader's in/out/err streams, or fall back to the debugger file
994 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995
996 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
997 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
998 // If no STDIN has been set, then set it appropriately
999 if (!in) {
1000 if (top_reader_sp)
1001 in = top_reader_sp->GetInputStreamFile();
1002 else
1003 in = GetInputFile();
1004
1005 // If there is nothing, use stdin
1006 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +00001007 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 }
1009 // If no STDOUT has been set, then set it appropriately
1010 if (!out) {
1011 if (top_reader_sp)
1012 out = top_reader_sp->GetOutputStreamFile();
1013 else
1014 out = GetOutputFile();
1015
1016 // If there is nothing, use stdout
1017 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +00001018 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 }
1020 // If no STDERR has been set, then set it appropriately
1021 if (!err) {
1022 if (top_reader_sp)
1023 err = top_reader_sp->GetErrorStreamFile();
1024 else
1025 err = GetErrorFile();
1026
1027 // If there is nothing, use stderr
1028 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +00001029 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 }
1031}
1032
Raphael Isemannc01783a2018-08-29 22:50:54 +00001033void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1034 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 if (!reader_sp)
1036 return;
1037
1038 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1039
1040 // Get the current top input reader...
1041 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1042
1043 // Don't push the same IO handler twice...
1044 if (reader_sp == top_reader_sp)
1045 return;
1046
1047 // Push our new input reader
1048 m_input_reader_stack.Push(reader_sp);
1049 reader_sp->Activate();
1050
Adrian Prantl05097242018-04-30 16:49:04 +00001051 // Interrupt the top input reader to it will exit its Run() function and let
1052 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 if (top_reader_sp) {
1054 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001055 if (cancel_top_handler)
1056 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 }
1058}
1059
1060bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1061 if (!pop_reader_sp)
1062 return false;
1063
1064 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1065
Adrian Prantl05097242018-04-30 16:49:04 +00001066 // The reader on the stop of the stack is done, so let the next read on the
1067 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 if (m_input_reader_stack.IsEmpty())
1069 return false;
1070
1071 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1072
1073 if (pop_reader_sp != reader_sp)
1074 return false;
1075
1076 reader_sp->Deactivate();
1077 reader_sp->Cancel();
1078 m_input_reader_stack.Pop();
1079
1080 reader_sp = m_input_reader_stack.Top();
1081 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001082 reader_sp->Activate();
1083
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 return true;
1085}
1086
1087StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001088 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089}
1090
1091StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001092 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093}
1094
1095size_t Debugger::GetNumDebuggers() {
1096 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1097 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1098 return g_debugger_list_ptr->size();
1099 }
1100 return 0;
1101}
1102
1103lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1104 DebuggerSP debugger_sp;
1105
1106 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1107 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1108 if (index < g_debugger_list_ptr->size())
1109 debugger_sp = g_debugger_list_ptr->at(index);
1110 }
1111
1112 return debugger_sp;
1113}
1114
1115DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1116 DebuggerSP debugger_sp;
1117
1118 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1119 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1120 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1121 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1122 if ((*pos)->GetID() == id) {
1123 debugger_sp = *pos;
1124 break;
1125 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001126 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 }
1128 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001129}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001130
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1132 const SymbolContext *sc,
1133 const SymbolContext *prev_sc,
1134 const ExecutionContext *exe_ctx,
1135 const Address *addr, Stream &s) {
1136 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001137
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 if (format == nullptr) {
1139 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1140 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1141 if (format == nullptr) {
1142 FormatEntity::Parse("${addr}: ", format_entry);
1143 format = &format_entry;
1144 }
1145 }
1146 bool function_changed = false;
1147 bool initial_function = false;
1148 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1149 if (sc && (sc->function || sc->symbol)) {
1150 if (prev_sc->symbol && sc->symbol) {
1151 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1152 prev_sc->symbol->GetType())) {
1153 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 } else if (prev_sc->function && sc->function) {
1156 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1157 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001158 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001160 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 }
Adrian Prantl05097242018-04-30 16:49:04 +00001162 // The first context on a list of instructions will have a prev_sc that has
1163 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 // would return false. But we do get a prev_sc pointer.
1165 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1166 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1167 initial_function = true;
1168 }
1169 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1170 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001171}
1172
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1174 void *baton) {
1175 // For simplicity's sake, I am not going to deal with how to close down any
1176 // open logging streams, I just redirect everything from here on out to the
1177 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001178 m_log_callback_stream_sp =
1179 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001180}
1181
Pavel Labath5e336902017-03-01 10:08:40 +00001182bool Debugger::EnableLog(llvm::StringRef channel,
1183 llvm::ArrayRef<const char *> categories,
1184 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001185 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001186 const bool should_close = true;
1187 const bool unbuffered = true;
1188
1189 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 if (m_log_callback_stream_sp) {
1191 log_stream_sp = m_log_callback_stream_sp;
1192 // For now when using the callback mode you always get thread & timestamp.
1193 log_options |=
1194 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001195 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001196 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1197 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001199 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 if (pos != m_log_streams.end())
1201 log_stream_sp = pos->second.lock();
1202 if (!log_stream_sp) {
Fangrui Songd9b948b2019-08-05 05:43:48 +00001203 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::OF_Text;
Pavel Labath5fae71c2017-02-10 11:49:21 +00001204 if (log_options & LLDB_LOG_OPTION_APPEND)
Fangrui Songd9b948b2019-08-05 05:43:48 +00001205 flags |= llvm::sys::fs::OF_Append;
Pavel Labath5fae71c2017-02-10 11:49:21 +00001206 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001207 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1208 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001209 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001210 return false;
1211 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001212 log_stream_sp =
1213 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001215 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 }
1217 assert(log_stream_sp);
1218
1219 if (log_options == 0)
1220 log_options =
1221 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1222
1223 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1224 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001225}
1226
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00001227ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) {
1228 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1229
1230 if (!m_script_interpreter_sp) {
1231 if (!can_create)
1232 return nullptr;
1233 m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(
1234 GetScriptLanguage(), *this);
1235 }
1236
1237 return m_script_interpreter_sp.get();
1238}
1239
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240SourceManager &Debugger::GetSourceManager() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001241 if (!m_source_manager_up)
Jonas Devliegherea8f3ae72019-08-14 22:19:23 +00001242 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001243 return *m_source_manager_up;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001244}
1245
Greg Clayton44d93782014-01-27 23:43:24 +00001246// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1248 using namespace lldb;
1249 const uint32_t event_type =
1250 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1251 event_sp);
1252
1253 // if (event_type & eBreakpointEventTypeAdded
1254 // || event_type & eBreakpointEventTypeRemoved
1255 // || event_type & eBreakpointEventTypeEnabled
1256 // || event_type & eBreakpointEventTypeDisabled
1257 // || event_type & eBreakpointEventTypeCommandChanged
1258 // || event_type & eBreakpointEventTypeConditionChanged
1259 // || event_type & eBreakpointEventTypeIgnoreChanged
1260 // || event_type & eBreakpointEventTypeLocationsResolved)
1261 // {
1262 // // Don't do anything about these events, since the breakpoint
1263 // commands already echo these actions.
1264 // }
1265 //
1266 if (event_type & eBreakpointEventTypeLocationsAdded) {
1267 uint32_t num_new_locations =
1268 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1269 event_sp);
1270 if (num_new_locations > 0) {
1271 BreakpointSP breakpoint =
1272 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1273 StreamSP output_sp(GetAsyncOutputStream());
1274 if (output_sp) {
1275 output_sp->Printf("%d location%s added to breakpoint %d\n",
1276 num_new_locations, num_new_locations == 1 ? "" : "s",
1277 breakpoint->GetID());
1278 output_sp->Flush();
1279 }
Greg Clayton44d93782014-01-27 23:43:24 +00001280 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 }
1282 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1283 // {
1284 // // These locations just get disabled, not sure it is worth spamming
1285 // folks about this on the command line.
1286 // }
1287 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1288 // {
1289 // // This might be an interesting thing to note, but I'm going to
1290 // leave it quiet for now, it just looked noisy.
1291 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001292}
1293
Pavel Labatha9d58432019-07-31 12:06:50 +00001294void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1295 bool flush_stderr) {
1296 const auto &flush = [&](Stream &stream,
1297 size_t (Process::*get)(char *, size_t, Status &)) {
1298 Status error;
1299 size_t len;
1300 char buffer[1024];
1301 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1302 stream.Write(buffer, len);
1303 stream.Flush();
1304 };
Greg Clayton44d93782014-01-27 23:43:24 +00001305
Pavel Labatha9d58432019-07-31 12:06:50 +00001306 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1307 if (flush_stdout)
1308 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT);
1309 if (flush_stderr)
1310 flush(*GetAsyncErrorStream(), &Process::GetSTDERR);
Greg Clayton44d93782014-01-27 23:43:24 +00001311}
1312
1313// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1315 using namespace lldb;
1316 const uint32_t event_type = event_sp->GetType();
1317 ProcessSP process_sp =
1318 (event_type == Process::eBroadcastBitStructuredData)
1319 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1320 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001321
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 StreamSP output_stream_sp = GetAsyncOutputStream();
1323 StreamSP error_stream_sp = GetAsyncErrorStream();
1324 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001325
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 if (!gui_enabled) {
1327 bool pop_process_io_handler = false;
1328 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001329
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 bool state_is_stopped = false;
1331 const bool got_state_changed =
1332 (event_type & Process::eBroadcastBitStateChanged) != 0;
1333 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1334 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1335 const bool got_structured_data =
1336 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001337
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 if (got_state_changed) {
1339 StateType event_state =
1340 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1341 state_is_stopped = StateIsStoppedState(event_state, false);
1342 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 // Display running state changes first before any STDIO
1345 if (got_state_changed && !state_is_stopped) {
1346 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1347 pop_process_io_handler);
1348 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001349
Pavel Labatha9d58432019-07-31 12:06:50 +00001350 // Now display STDOUT and STDERR
1351 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
1352 got_stderr || got_state_changed);
Greg Claytonb4874f12014-02-28 18:22:24 +00001353
Kate Stoneb9c1b512016-09-06 20:57:50 +00001354 // Give structured data events an opportunity to display.
1355 if (got_structured_data) {
1356 StructuredDataPluginSP plugin_sp =
1357 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1358 if (plugin_sp) {
1359 auto structured_data_sp =
1360 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1361 if (output_stream_sp) {
1362 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001363 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 plugin_sp->GetDescription(structured_data_sp, content_stream);
1365 if (error.Success()) {
1366 if (!content_stream.GetString().empty()) {
1367 // Add newline.
1368 content_stream.PutChar('\n');
1369 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001370
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001372 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001373 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374 } else {
1375 error_stream_sp->Printf("Failed to print structured "
1376 "data with plugin %s: %s",
1377 plugin_sp->GetPluginName().AsCString(),
1378 error.AsCString());
1379 }
Todd Fiala75930012016-08-19 04:21:48 +00001380 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001382 }
Greg Clayton44d93782014-01-27 23:43:24 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 // Now display any stopped state changes after any STDIO
1385 if (got_state_changed && state_is_stopped) {
1386 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1387 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001388 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389
1390 output_stream_sp->Flush();
1391 error_stream_sp->Flush();
1392
1393 if (pop_process_io_handler)
1394 process_sp->PopProcessIOHandler();
1395 }
Greg Clayton44d93782014-01-27 23:43:24 +00001396}
1397
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001399 // At present the only thread event we handle is the Frame Changed event, and
1400 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401 using namespace lldb;
1402 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001403 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404 if (event_type == Thread::eBroadcastBitStackChanged ||
1405 event_type == Thread::eBroadcastBitThreadSelected) {
1406 ThreadSP thread_sp(
1407 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1408 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001409 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 }
1411 }
Greg Clayton44d93782014-01-27 23:43:24 +00001412}
1413
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1415
1416void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1417 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001418}
1419
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1421 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001422}
1423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424void Debugger::DefaultEventHandler() {
1425 ListenerSP listener_sp(GetListener());
1426 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1427 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1428 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1429 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1430 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001431
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 BroadcastEventSpec process_event_spec(
1433 broadcaster_class_process,
1434 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1435 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001436
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1438 Thread::eBroadcastBitStackChanged |
1439 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001440
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1442 target_event_spec);
1443 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1444 process_event_spec);
1445 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1446 thread_event_spec);
1447 listener_sp->StartListeningForEvents(
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001448 m_command_interpreter_up.get(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1450 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1451 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001452
Adrian Prantl05097242018-04-30 16:49:04 +00001453 // Let the thread that spawned us know that we have started up and that we
1454 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001456
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 bool done = false;
1458 while (!done) {
1459 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001460 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 if (event_sp) {
1462 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1463 if (broadcaster) {
1464 uint32_t event_type = event_sp->GetType();
1465 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1466 if (broadcaster_class == broadcaster_class_process) {
1467 HandleProcessEvent(event_sp);
1468 } else if (broadcaster_class == broadcaster_class_target) {
1469 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1470 event_sp.get())) {
1471 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001472 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473 } else if (broadcaster_class == broadcaster_class_thread) {
1474 HandleThreadEvent(event_sp);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001475 } else if (broadcaster == m_command_interpreter_up.get()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 if (event_type &
1477 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1478 done = true;
1479 } else if (event_type &
1480 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1481 const char *data = reinterpret_cast<const char *>(
1482 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1483 if (data && data[0]) {
1484 StreamSP error_sp(GetAsyncErrorStream());
1485 if (error_sp) {
1486 error_sp->PutCString(data);
1487 error_sp->Flush();
1488 }
1489 }
1490 } else if (event_type & CommandInterpreter::
1491 eBroadcastBitAsynchronousOutputData) {
1492 const char *data = reinterpret_cast<const char *>(
1493 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1494 if (data && data[0]) {
1495 StreamSP output_sp(GetAsyncOutputStream());
1496 if (output_sp) {
1497 output_sp->PutCString(data);
1498 output_sp->Flush();
1499 }
1500 }
1501 }
1502 }
Greg Clayton44d93782014-01-27 23:43:24 +00001503 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504
1505 if (m_forward_listener_sp)
1506 m_forward_listener_sp->AddEvent(event_sp);
1507 }
Greg Clayton44d93782014-01-27 23:43:24 +00001508 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 }
Greg Clayton44d93782014-01-27 23:43:24 +00001510}
1511
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1513 ((Debugger *)arg)->DefaultEventHandler();
Konrad Kleine85200642019-05-23 15:17:39 +00001514 return {};
Greg Clayton44d93782014-01-27 23:43:24 +00001515}
1516
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517bool Debugger::StartEventHandlerThread() {
1518 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001519 // We must synchronize with the DefaultEventHandler() thread to ensure it
1520 // is up and running and listening to events before we return from this
1521 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001522 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001523 ConstString full_name("lldb.debugger.event-handler");
1524 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1526 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001527
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001528 auto thread_name =
Jonas Devliegheree063ecc2019-08-02 00:18:44 +00001529 full_name.GetLength() < llvm::get_max_thread_name_length()
1530 ? full_name.AsCString()
1531 : "dbg.evt-handler";
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001532
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533 // Use larger 8MB stack for this thread
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001534 llvm::Expected<HostThread> event_handler_thread =
1535 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1536 g_debugger_event_thread_stack_bytes);
1537
1538 if (event_handler_thread) {
1539 m_event_handler_thread = *event_handler_thread;
1540 } else {
1541 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1542 "failed to launch host thread: {}",
1543 llvm::toString(event_handler_thread.takeError()));
1544 }
Greg Claytonafa91e332014-12-01 22:41:27 +00001545
Adrian Prantl05097242018-04-30 16:49:04 +00001546 // Make sure DefaultEventHandler() is running and listening to events
1547 // before we return from this function. We are only listening for events of
1548 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1549 // event, we just need to wait an infinite amount of time for it (nullptr
1550 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001552 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 }
1554 return m_event_handler_thread.IsJoinable();
1555}
1556
1557void Debugger::StopEventHandlerThread() {
1558 if (m_event_handler_thread.IsJoinable()) {
1559 GetCommandInterpreter().BroadcastEvent(
1560 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1561 m_event_handler_thread.Join(nullptr);
1562 }
1563}
1564
1565lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1566 Debugger *debugger = (Debugger *)arg;
1567 debugger->ExecuteIOHandlers();
1568 debugger->StopEventHandlerThread();
Konrad Kleine85200642019-05-23 15:17:39 +00001569 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570}
1571
1572bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1573
1574bool Debugger::StartIOHandlerThread() {
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001575 if (!m_io_handler_thread.IsJoinable()) {
1576 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1577 "lldb.debugger.io-handler", IOHandlerThread, this,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 8 * 1024 * 1024); // Use larger 8MB stack for this thread
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001579 if (io_handler_thread) {
1580 m_io_handler_thread = *io_handler_thread;
1581 } else {
1582 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1583 "failed to launch host thread: {}",
1584 llvm::toString(io_handler_thread.takeError()));
1585 }
1586 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 return m_io_handler_thread.IsJoinable();
1588}
1589
1590void Debugger::StopIOHandlerThread() {
1591 if (m_io_handler_thread.IsJoinable()) {
1592 if (m_input_file_sp)
1593 m_input_file_sp->GetFile().Close();
1594 m_io_handler_thread.Join(nullptr);
1595 }
1596}
1597
1598void Debugger::JoinIOHandlerThread() {
1599 if (HasIOHandlerThread()) {
1600 thread_result_t result;
1601 m_io_handler_thread.Join(&result);
1602 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1603 }
1604}
1605
1606Target *Debugger::GetDummyTarget() {
1607 return m_target_list.GetDummyTarget(*this).get();
1608}
1609
1610Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1611 Target *target = nullptr;
1612 if (!prefer_dummy) {
1613 target = m_target_list.GetSelectedTarget().get();
1614 if (target)
1615 return target;
1616 }
1617
1618 return GetDummyTarget();
1619}
1620
Zachary Turner97206d52017-05-12 04:51:55 +00001621Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1622 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 FileSpec repl_executable;
1624
1625 if (language == eLanguageTypeUnknown) {
1626 std::set<LanguageType> repl_languages;
1627
1628 Language::GetLanguagesSupportingREPLs(repl_languages);
1629
1630 if (repl_languages.size() == 1) {
1631 language = *repl_languages.begin();
1632 } else if (repl_languages.empty()) {
1633 err.SetErrorStringWithFormat(
1634 "LLDB isn't configured with REPL support for any languages.");
1635 return err;
1636 } else {
1637 err.SetErrorStringWithFormat(
1638 "Multiple possible REPL languages. Please specify a language.");
1639 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001640 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001641 }
Greg Clayton44d93782014-01-27 23:43:24 +00001642
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 Target *const target =
1644 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001645
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001647
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001649 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650 }
1651
1652 if (!repl_sp) {
1653 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1654 Language::GetNameForLanguageType(language));
1655 return err;
1656 }
1657
1658 repl_sp->SetCompilerOptions(repl_options);
1659 repl_sp->RunLoop();
1660
1661 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001662}