blob: 5efe78635d23ea5deeaea547dbec506c692fdb6d [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Clayton4a33d312011-06-23 17:59:56 +00009#include "lldb/Core/Debugger.h"
10
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000011#include "lldb/Breakpoint/Breakpoint.h"
Greg Clayton554f68d2015-02-04 22:00:53 +000012#include "lldb/Core/FormatEntity.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000013#include "lldb/Core/Mangled.h"
14#include "lldb/Core/ModuleList.h"
Greg Claytone8cd0c92012-10-19 18:02:49 +000015#include "lldb/Core/PluginManager.h"
Jim Ingham5b52f0c2011-06-02 23:58:26 +000016#include "lldb/Core/StreamAsynchronousIO.h"
Greg Clayton44d93782014-01-27 23:43:24 +000017#include "lldb/Core/StreamFile.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000018#include "lldb/DataFormatters/DataVisualization.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000019#include "lldb/Expression/REPL.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000020#include "lldb/Host/File.h"
Jonas Devlieghere35e4c842018-11-01 00:33:27 +000021#include "lldb/Host/FileSystem.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000022#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000023#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000024#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000026#include "lldb/Interpreter/OptionValue.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000027#include "lldb/Interpreter/OptionValueProperties.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000028#include "lldb/Interpreter/OptionValueSInt64.h"
29#include "lldb/Interpreter/OptionValueString.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000030#include "lldb/Interpreter/Property.h"
31#include "lldb/Interpreter/ScriptInterpreter.h"
Greg Clayton1f746072012-08-29 21:13:06 +000032#include "lldb/Symbol/Function.h"
33#include "lldb/Symbol/Symbol.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000034#include "lldb/Symbol/SymbolContext.h"
Sean Callanan3e7e9152015-10-20 00:23:46 +000035#include "lldb/Target/Language.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Target/Process.h"
Todd Fiala75930012016-08-19 04:21:48 +000037#include "lldb/Target/StructuredDataPlugin.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000038#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#include "lldb/Target/TargetList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/Thread.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000041#include "lldb/Target/ThreadList.h"
Greg Clayton5a314712011-10-14 07:41:33 +000042#include "lldb/Utility/AnsiTerminal.h"
Pavel Labath181b8232018-12-14 15:59:49 +000043#include "lldb/Utility/Event.h"
44#include "lldb/Utility/Listener.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000045#include "lldb/Utility/Log.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000046#include "lldb/Utility/Reproducer.h"
Pavel Labathd821c992018-08-07 11:07:21 +000047#include "lldb/Utility/State.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000048#include "lldb/Utility/Stream.h"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000049#include "lldb/Utility/StreamCallback.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000050#include "lldb/Utility/StreamString.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000051
Nico Weberb1cb0b792018-04-10 13:33:45 +000052#if defined(_WIN32)
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000053#include "lldb/Host/windows/PosixApi.h"
David Bolvansky8aa23612018-09-05 22:06:58 +000054#include "lldb/Host/windows/windows.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000055#endif
56
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000057#include "llvm/ADT/None.h"
58#include "llvm/ADT/STLExtras.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000059#include "llvm/ADT/StringRef.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000060#include "llvm/ADT/iterator.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000061#include "llvm/Support/DynamicLibrary.h"
62#include "llvm/Support/FileSystem.h"
David Bolvansky8aa23612018-09-05 22:06:58 +000063#include "llvm/Support/Process.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000064#include "llvm/Support/Threading.h"
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000065#include "llvm/Support/raw_ostream.h"
Zachary Turner2f3df612017-04-06 21:28:29 +000066
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000067#include <list>
68#include <memory>
Zachary Turner2f3df612017-04-06 21:28:29 +000069#include <mutex>
Jonas Devlieghere672d2c12018-11-11 23:16:43 +000070#include <set>
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#include <string>
75#include <system_error>
Zachary Turner2f3df612017-04-06 21:28:29 +000076
77namespace lldb_private {
78class Address;
79}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080
81using namespace lldb;
82using namespace lldb_private;
83
Caroline Ticeebc1bb22010-06-30 16:22:25 +000084static lldb::user_id_t g_unique_id = 1;
Zachary Turner7c2896a2014-10-24 22:06:29 +000085static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000086
Greg Clayton1b654882010-09-19 02:33:57 +000087#pragma mark Static Functions
88
Greg Clayton1b654882010-09-19 02:33:57 +000089typedef std::vector<DebuggerSP> DebuggerList;
Kate Stoneb9c1b512016-09-06 20:57:50 +000090static std::recursive_mutex *g_debugger_list_mutex_ptr =
91 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
92static DebuggerList *g_debugger_list_ptr =
93 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
Greg Claytone372b982011-11-21 21:44:34 +000094
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000095static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 {Debugger::eStopDisassemblyTypeNever, "never",
97 "Never show disassembly when displaying a stop context."},
98 {Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo",
99 "Show disassembly when there is no debug information."},
100 {Debugger::eStopDisassemblyTypeNoSource, "no-source",
101 "Show disassembly when there is no source information, or the source file "
102 "is missing when displaying a stop context."},
103 {Debugger::eStopDisassemblyTypeAlways, "always",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000104 "Always show disassembly when displaying a stop context."} };
Greg Claytone372b982011-11-21 21:44:34 +0000105
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000106static constexpr OptionEnumValueElement g_language_enumerators[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 {eScriptLanguageNone, "none", "Disable scripting languages."},
108 {eScriptLanguagePython, "python",
109 "Select python as the default scripting language."},
110 {eScriptLanguageDefault, "default",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000111 "Select the lldb default as the default scripting language."} };
Greg Claytone372b982011-11-21 21:44:34 +0000112
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113#define MODULE_WITH_FUNC \
114 "{ " \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000115 "${module.file.basename}{`${function.name-with-args}" \
116 "{${frame.no-debug}${function.pc-offset}}}}"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000117
118#define MODULE_WITH_FUNC_NO_ARGS \
119 "{ " \
120 "${module.file.basename}{`${function.name-without-args}" \
121 "{${frame.no-debug}${function.pc-offset}}}}"
122
Adrian Prantl4954f6a2018-09-05 23:52:08 +0000123#define FILE_AND_LINE \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000124 "{ at ${ansi.fg.cyan}${line.file.basename}${ansi.normal}" \
125 ":${ansi.fg.yellow}${line.number}${ansi.normal}" \
126 "{:${ansi.fg.yellow}${line.column}${ansi.normal}}}"
127
Jason Molenda6ab659a2015-07-29 00:42:47 +0000128#define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
Greg Clayton67cc0632012-08-22 17:17:09 +0000129
Vedant Kumar4b36f792018-10-05 23:23:15 +0000130#define IS_ARTIFICIAL "{${frame.is-artificial} [artificial]}"
131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132#define DEFAULT_THREAD_FORMAT \
133 "thread #${thread.index}: tid = ${thread.id%tid}" \
134 "{, ${frame.pc}}" MODULE_WITH_FUNC FILE_AND_LINE \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000135 "{, name = ${ansi.fg.green}'${thread.name}'${ansi.normal}}" \
136 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
137 "{, activity = " \
138 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 "{, ${thread.info.trace_messages} messages}" \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000140 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 "{\\nReturn value: ${thread.return-value}}" \
142 "{\\nCompleted expression: ${thread.completed-expression}}" \
143 "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000144
Jim Ingham6a9767c2016-11-08 20:36:40 +0000145#define DEFAULT_THREAD_STOP_FORMAT \
146 "thread #${thread.index}{, name = '${thread.name}'}" \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000147 "{, queue = ${ansi.fg.green}'${thread.queue}'${ansi.normal}}" \
148 "{, activity = " \
149 "${ansi.fg.green}'${thread.info.activity.name}'${ansi.normal}}" \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000150 "{, ${thread.info.trace_messages} messages}" \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000151 "{, stop reason = ${ansi.fg.red}${thread.stop-reason}${ansi.normal}}" \
Jim Ingham6a9767c2016-11-08 20:36:40 +0000152 "{\\nReturn value: ${thread.return-value}}" \
153 "{\\nCompleted expression: ${thread.completed-expression}}" \
154 "\\n"
155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156#define DEFAULT_FRAME_FORMAT \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000157 "frame #${frame.index}: " \
158 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC FILE_AND_LINE \
Vedant Kumar4b36f792018-10-05 23:23:15 +0000159 IS_OPTIMIZED IS_ARTIFICIAL "\\n"
Greg Clayton67cc0632012-08-22 17:17:09 +0000160
Pavel Labath7f1c1212017-06-12 16:25:24 +0000161#define DEFAULT_FRAME_FORMAT_NO_ARGS \
Jonas Devliegheref9626f22019-06-17 19:53:11 +0000162 "frame #${frame.index}: " \
163 "${ansi.fg.yellow}${frame.pc}${ansi.normal}" MODULE_WITH_FUNC_NO_ARGS \
164 FILE_AND_LINE IS_OPTIMIZED IS_ARTIFICIAL "\\n"
Pavel Labath7f1c1212017-06-12 16:25:24 +0000165
Jason Molendac980fa92015-02-13 23:24:21 +0000166// Three parts to this disassembly format specification:
167// 1. If this is a new function/symbol (no previous symbol/function), print
168// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169// 2. If this is a symbol context change (different from previous
170// symbol/function), print
Jason Molendac980fa92015-02-13 23:24:21 +0000171// dylib`funcname:\n
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172// 3. print
173// address <+offset>:
174#define DEFAULT_DISASSEMBLY_FORMAT \
175 "{${function.initial-function}{${module.file.basename}`}{${function.name-" \
Jonas Devliegheree43be152018-10-01 13:20:15 +0000176 "without-args}}:\\n}{${function.changed}\\n{${module.file.basename}`}{${" \
177 "function.name-without-args}}:\\n}{${current-pc-arrow} " \
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178 "}${addr-file-or-load}{ " \
179 "<${function.concrete-only-addr-offset-no-padding}>}: "
Jason Molendac980fa92015-02-13 23:24:21 +0000180
Adrian Prantl05097242018-04-30 16:49:04 +0000181// gdb's disassembly format can be emulated with ${current-pc-arrow}${addr-
182// file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-
183// offset-no-padding}>}:
Jason Molendac980fa92015-02-13 23:24:21 +0000184
185// lldb's original format for disassembly would look like this format string -
Adrian Prantl05097242018-04-30 16:49:04 +0000186// {${function.initial-function}{${module.file.basename}`}{${function.name-
187// without-
188// args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-
189// without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}:
Jason Molendac980fa92015-02-13 23:24:21 +0000190
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000191static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
Todd Fiala9666ba72016-09-21 20:13:14 +0000192 {eStopShowColumnAnsiOrCaret, "ansi-or-caret",
193 "Highlight the stop column with ANSI terminal codes when color/ANSI mode "
194 "is enabled; otherwise, fall back to using a text-only caret (^) as if "
195 "\"caret-only\" mode was selected."},
196 {eStopShowColumnAnsi, "ansi", "Highlight the stop column with ANSI "
197 "terminal codes when running LLDB with "
198 "color/ANSI enabled."},
199 {eStopShowColumnCaret, "caret",
200 "Highlight the stop column with a caret character (^) underneath the stop "
201 "column. This method introduces a new line in source listings that "
202 "display thread stop locations."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000203 {eStopShowColumnNone, "none", "Do not highlight the stop column."}};
Todd Fiala9666ba72016-09-21 20:13:14 +0000204
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000205#define LLDB_PROPERTIES_debugger
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000206#include "CoreProperties.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000209#define LLDB_PROPERTIES_debugger
Jordan Rupprecht6a253d32019-07-29 17:22:10 +0000210#include "CorePropertiesEnum.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000211};
212
Eugene Zelenkodf370552016-03-02 02:18:18 +0000213LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000214
Zachary Turner97206d52017-05-12 04:51:55 +0000215Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
216 VarSetOperationType op,
217 llvm::StringRef property_path,
218 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000219 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
220 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 TargetSP target_sp;
222 LoadScriptFromSymFile load_script_old_value;
223 if (is_load_script && exe_ctx->GetTargetSP()) {
224 target_sp = exe_ctx->GetTargetSP();
225 load_script_old_value =
226 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
227 }
Zachary Turner97206d52017-05-12 04:51:55 +0000228 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 if (error.Success()) {
230 // FIXME it would be nice to have "on-change" callbacks for properties
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000231 if (property_path == g_debugger_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000232 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
234 new_prompt, GetUseColor());
235 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000236 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000238 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
239 auto prompt_change_event_sp = std::make_shared<Event>(
240 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000242 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 // use-color changed. Ping the prompt so it can reset the ansi terminal
244 // codes.
245 SetPrompt(GetPrompt());
246 } else if (is_load_script && target_sp &&
247 load_script_old_value == eLoadScriptFromSymFileWarn) {
248 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
249 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000250 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 StreamString feedback_stream;
252 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
253 StreamFileSP stream_sp(GetErrorFile());
254 if (stream_sp) {
255 for (auto error : errors) {
256 stream_sp->Printf("%s\n", error.AsCString());
257 }
258 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000259 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 }
261 }
262 }
263 } else if (is_escape_non_printables) {
264 DataVisualization::ForceUpdate();
265 }
266 }
267 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000268}
269
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270bool Debugger::GetAutoConfirm() const {
271 const uint32_t idx = ePropertyAutoConfirm;
272 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000273 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000274}
275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
277 const uint32_t idx = ePropertyDisassemblyFormat;
278 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000279}
280
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281const FormatEntity::Entry *Debugger::GetFrameFormat() const {
282 const uint32_t idx = ePropertyFrameFormat;
283 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000284}
285
Pavel Labath7f1c1212017-06-12 16:25:24 +0000286const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
287 const uint32_t idx = ePropertyFrameFormatUnique;
288 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
289}
290
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291bool Debugger::GetNotifyVoid() const {
292 const uint32_t idx = ePropertyNotiftVoid;
293 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000294 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000295}
296
Zachary Turner514d8cd2016-09-23 18:06:53 +0000297llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 const uint32_t idx = ePropertyPrompt;
299 return m_collection_sp->GetPropertyAtIndexAsString(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000300 nullptr, idx, g_debugger_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000301}
302
Zachary Turner514d8cd2016-09-23 18:06:53 +0000303void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 const uint32_t idx = ePropertyPrompt;
305 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000306 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 std::string str =
308 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
309 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000310 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000312}
313
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000314llvm::StringRef Debugger::GetReproducerPath() const {
315 auto &r = repro::Reproducer::Instance();
316 return r.GetReproducerPath().GetCString();
317}
318
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319const FormatEntity::Entry *Debugger::GetThreadFormat() const {
320 const uint32_t idx = ePropertyThreadFormat;
321 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000322}
323
Jim Ingham6a9767c2016-11-08 20:36:40 +0000324const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
325 const uint32_t idx = ePropertyThreadStopFormat;
326 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
327}
328
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
330 const uint32_t idx = ePropertyScriptLanguage;
331 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000332 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000333}
334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
336 const uint32_t idx = ePropertyScriptLanguage;
337 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
338 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000339}
340
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341uint32_t Debugger::GetTerminalWidth() const {
342 const uint32_t idx = ePropertyTerminalWidth;
343 return m_collection_sp->GetPropertyAtIndexAsSInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000344 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000345}
346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347bool Debugger::SetTerminalWidth(uint32_t term_width) {
348 const uint32_t idx = ePropertyTerminalWidth;
349 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000350}
351
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352bool Debugger::GetUseExternalEditor() const {
353 const uint32_t idx = ePropertyUseExternalEditor;
354 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000355 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000356}
Greg Claytone372b982011-11-21 21:44:34 +0000357
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358bool Debugger::SetUseExternalEditor(bool b) {
359 const uint32_t idx = ePropertyUseExternalEditor;
360 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000361}
Enrico Granata553fad52013-10-25 23:09:40 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363bool Debugger::GetUseColor() const {
364 const uint32_t idx = ePropertyUseColor;
365 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000366 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369bool Debugger::SetUseColor(bool b) {
370 const uint32_t idx = ePropertyUseColor;
371 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
372 SetPrompt(GetPrompt());
373 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000374}
375
Raphael Isemann566afa02018-08-02 00:30:15 +0000376bool Debugger::GetHighlightSource() const {
377 const uint32_t idx = ePropertyHighlightSource;
378 return m_collection_sp->GetPropertyAtIndexAsBoolean(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000379 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Raphael Isemann566afa02018-08-02 00:30:15 +0000380}
381
Todd Fiala9666ba72016-09-21 20:13:14 +0000382StopShowColumn Debugger::GetStopShowColumn() const {
383 const uint32_t idx = ePropertyStopShowColumn;
384 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000385 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Todd Fiala9666ba72016-09-21 20:13:14 +0000386}
387
Raphael Isemann20786322018-08-30 00:09:21 +0000388llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000389 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000390 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000391}
392
Raphael Isemann20786322018-08-30 00:09:21 +0000393llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000394 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000395 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000396}
397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398uint32_t Debugger::GetStopSourceLineCount(bool before) const {
399 const uint32_t idx =
400 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
401 return m_collection_sp->GetPropertyAtIndexAsSInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000402 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000403}
404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
406 const uint32_t idx = ePropertyStopDisassemblyDisplay;
407 return (Debugger::StopDisassemblyType)
408 m_collection_sp->GetPropertyAtIndexAsEnumeration(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000409 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000410}
411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412uint32_t Debugger::GetDisassemblyLineCount() const {
413 const uint32_t idx = ePropertyStopDisassemblyCount;
414 return m_collection_sp->GetPropertyAtIndexAsSInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000415 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000416}
417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418bool Debugger::GetAutoOneLineSummaries() const {
419 const uint32_t idx = ePropertyAutoOneLineSummaries;
420 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000421}
422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423bool Debugger::GetEscapeNonPrintables() const {
424 const uint32_t idx = ePropertyEscapeNonPrintables;
425 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
426}
427
428bool Debugger::GetAutoIndent() const {
429 const uint32_t idx = ePropertyAutoIndent;
430 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
431}
432
433bool Debugger::SetAutoIndent(bool b) {
434 const uint32_t idx = ePropertyAutoIndent;
435 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
436}
437
438bool Debugger::GetPrintDecls() const {
439 const uint32_t idx = ePropertyPrintDecls;
440 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
441}
442
443bool Debugger::SetPrintDecls(bool b) {
444 const uint32_t idx = ePropertyPrintDecls;
445 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
446}
447
448uint32_t Debugger::GetTabSize() const {
449 const uint32_t idx = ePropertyTabSize;
450 return m_collection_sp->GetPropertyAtIndexAsUInt64(
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000451 nullptr, idx, g_debugger_properties[idx].default_uint_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452}
453
454bool Debugger::SetTabSize(uint32_t tab_size) {
455 const uint32_t idx = ePropertyTabSize;
456 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000457}
458
Greg Clayton1b654882010-09-19 02:33:57 +0000459#pragma mark Debugger
460
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461// const DebuggerPropertiesSP &
462// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000463//{
464// return m_properties_sp;
465//}
466//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
469 assert(g_debugger_list_ptr == nullptr &&
470 "Debugger::Initialize called more than once!");
471 g_debugger_list_mutex_ptr = new std::recursive_mutex();
472 g_debugger_list_ptr = new DebuggerList();
473 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000474}
475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476void Debugger::Terminate() {
477 assert(g_debugger_list_ptr &&
478 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000479
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
481 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000482 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
484 for (const auto &debugger : *g_debugger_list_ptr)
485 debugger->Clear();
486 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000487 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489}
490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000494
Zachary Turner97206d52017-05-12 04:51:55 +0000495bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 if (g_load_plugin_callback) {
497 llvm::sys::DynamicLibrary dynlib =
498 g_load_plugin_callback(shared_from_this(), spec, error);
499 if (dynlib.isValid()) {
500 m_loaded_plugins.push_back(dynlib);
501 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000502 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000504 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
505 // if the public API layer isn't available (code is linking against all of
506 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 error.SetErrorString("Public API layer is not available");
508 }
509 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000510}
511
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000512static FileSystem::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000513LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000514 llvm::StringRef path) {
Zachary Turner97206d52017-05-12 04:51:55 +0000515 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000516
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000517 static ConstString g_dylibext(".dylib");
518 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519
520 if (!baton)
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000521 return FileSystem::eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522
523 Debugger *debugger = (Debugger *)baton;
524
Zachary Turner7d86ee52017-03-08 17:56:08 +0000525 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000526 // If we have a regular file, a symbolic link or unknown file type, try and
527 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 // enumeration might be enumerating a file system that doesn't have correct
529 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000530 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
531 ft == fs::file_type::type_unknown) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000532 FileSpec plugin_file_spec(path);
533 FileSystem::Instance().Resolve(plugin_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534
535 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
536 plugin_file_spec.GetFileNameExtension() != g_solibext) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000537 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000538 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539
Zachary Turner97206d52017-05-12 04:51:55 +0000540 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
542
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000543 return FileSystem::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000544 } else if (ft == fs::file_type::directory_file ||
545 ft == fs::file_type::symlink_file ||
546 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000547 // Try and recurse into anything that a directory or symbolic link. We must
548 // also do this for unknown as sometimes the directory enumeration might be
549 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 // information.
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000551 return FileSystem::eEnumerateDirectoryResultEnter;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 }
553
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000554 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000555}
556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 const bool find_directories = true;
559 const bool find_files = true;
560 const bool find_other = true;
561 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000562 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000563 if (FileSystem::Instance().Exists(dir_spec) &&
564 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000565 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
566 find_files, find_other,
567 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000568 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000570
Pavel Labath60f028f2018-06-19 15:09:07 +0000571 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000572 if (FileSystem::Instance().Exists(dir_spec) &&
573 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000574 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
575 find_files, find_other,
576 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000577 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 }
579
580 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000581}
582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
584 void *baton) {
585 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
586 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
587 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
588 g_debugger_list_ptr->push_back(debugger_sp);
589 }
590 debugger_sp->InstanceInitialize();
591 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000592}
593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594void Debugger::Destroy(DebuggerSP &debugger_sp) {
595 if (!debugger_sp)
596 return;
597
598 debugger_sp->Clear();
599
600 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
601 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
602 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
603 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
604 if ((*pos).get() == debugger_sp.get()) {
605 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000606 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000608 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000610}
611
Greg Clayton4d122c42011-09-17 08:33:22 +0000612DebuggerSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +0000613Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 DebuggerSP debugger_sp;
615 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
616 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
617 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
618 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
619 if ((*pos)->m_instance_name == instance_name) {
620 debugger_sp = *pos;
621 break;
622 }
Greg Clayton6920b522012-08-22 18:39:03 +0000623 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 }
625 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000626}
Greg Clayton66111032010-06-23 01:19:29 +0000627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
629 TargetSP target_sp;
630 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
631 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
632 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
633 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
634 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
635 if (target_sp)
636 break;
Greg Clayton66111032010-06-23 01:19:29 +0000637 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000638 }
639 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000640}
641
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642TargetSP Debugger::FindTargetWithProcess(Process *process) {
643 TargetSP target_sp;
644 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
645 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
646 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
647 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
648 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
649 if (target_sp)
650 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000651 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 }
653 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000654}
655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
657 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000658 Properties(std::make_shared<OptionValueProperties>()),
659 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
660 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
661 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000662 m_input_recorder(nullptr),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
664 m_terminal_state(), m_target_list(*this), m_platform_list(),
665 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000666 m_source_manager_up(), m_source_file_cache(),
Jonas Devliegheref20dd1d2019-04-26 20:03:22 +0000667 m_command_interpreter_up(
668 llvm::make_unique<CommandInterpreter>(*this, false)),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000669 m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(),
670 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
672 m_forward_listener_sp(), m_clear_once() {
673 char instance_cstr[256];
674 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
675 m_instance_name.SetCString(instance_cstr);
676 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000677 m_log_callback_stream_sp =
678 std::make_shared<StreamCallback>(log_callback, baton);
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000679 m_command_interpreter_up->Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 // Always add our default platform to the platform list
681 PlatformSP default_platform_sp(Platform::GetHostPlatform());
682 assert(default_platform_sp);
683 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000684
Jonas Devliegherea8ea5952019-07-29 16:41:30 +0000685 m_collection_sp->Initialize(g_debugger_properties);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000686 m_collection_sp->AppendProperty(
687 ConstString("target"),
688 ConstString("Settings specify to debugging targets."), true,
689 Target::GetGlobalProperties()->GetValueProperties());
690 m_collection_sp->AppendProperty(
691 ConstString("platform"), ConstString("Platform settings."), true,
692 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000693 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000694 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
695 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000696 if (m_command_interpreter_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 m_collection_sp->AppendProperty(
698 ConstString("interpreter"),
699 ConstString("Settings specify to the debugger's command interpreter."),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000700 true, m_command_interpreter_up->GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 }
702 OptionValueSInt64 *term_width =
703 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
704 nullptr, ePropertyTerminalWidth);
705 term_width->SetMinimumValue(10);
706 term_width->SetMaximumValue(1024);
707
708 // Turn off use-color if this is a dumb terminal.
709 const char *term = getenv("TERM");
710 if (term && !strcmp(term, "dumb"))
711 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000712 // Turn off use-color if we don't write to a terminal with color support.
713 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
714 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000715
716#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
717 // Enabling use of ANSI color codes because LLDB is using them to highlight
718 // text.
719 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000720#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721}
722
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725void Debugger::Clear() {
Adrian Prantl05097242018-04-30 16:49:04 +0000726 // Make sure we call this function only once. With the C++ global destructor
727 // chain having a list of debuggers and with code that can be running on
728 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 //
730 // The following functions call Debugger::Clear():
731 // Debugger::~Debugger();
732 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
733 // static void Debugger::Terminate();
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000734 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000735 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 StopIOHandlerThread();
737 StopEventHandlerThread();
738 m_listener_sp->Clear();
739 int num_targets = m_target_list.GetNumTargets();
740 for (int i = 0; i < num_targets; i++) {
741 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
742 if (target_sp) {
743 ProcessSP process_sp(target_sp->GetProcessSP());
744 if (process_sp)
745 process_sp->Finalize();
746 target_sp->Destroy();
747 }
Greg Clayton577508d2014-06-20 00:23:57 +0000748 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 m_broadcaster_manager_sp->Clear();
750
751 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000752 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 m_terminal_state.Clear();
754 if (m_input_file_sp)
755 m_input_file_sp->GetFile().Close();
756
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000757 m_command_interpreter_up->Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 });
Greg Clayton44d93782014-01-27 23:43:24 +0000759}
760
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761bool Debugger::GetCloseInputOnEOF() const {
762 // return m_input_comm.GetCloseOnEOF();
763 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000764}
765
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766void Debugger::SetCloseInputOnEOF(bool b) {
767 // m_input_comm.SetCloseOnEOF(b);
768}
769
770bool Debugger::GetAsyncExecution() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000771 return !m_command_interpreter_up->GetSynchronous();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772}
773
774void Debugger::SetAsyncExecution(bool async_execution) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000775 m_command_interpreter_up->SetSynchronous(!async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776}
777
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000778repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
779
780void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership,
781 repro::DataRecorder *recorder) {
782 m_input_recorder = recorder;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 if (m_input_file_sp)
784 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
785 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000786 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787
788 File &in_file = m_input_file_sp->GetFile();
789 if (!in_file.IsValid())
790 in_file.SetStream(stdin, true);
791
Adrian Prantl05097242018-04-30 16:49:04 +0000792 // Save away the terminal state if that is relevant, so that we can restore
793 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 SaveInputTerminalState();
795}
796
797void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
798 if (m_output_file_sp)
799 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
800 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000801 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802
803 File &out_file = m_output_file_sp->GetFile();
804 if (!out_file.IsValid())
805 out_file.SetStream(stdout, false);
806
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000807 // Do not create the ScriptInterpreter just for setting the output file
808 // handle as the constructor will know how to do the right thing on its own.
809 if (ScriptInterpreter *script_interpreter =
810 GetScriptInterpreter(/*can_create=*/false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 script_interpreter->ResetOutputFileHandle(fh);
812}
813
814void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
815 if (m_error_file_sp)
816 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
817 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000818 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819
820 File &err_file = m_error_file_sp->GetFile();
821 if (!err_file.IsValid())
822 err_file.SetStream(stderr, false);
823}
824
825void Debugger::SaveInputTerminalState() {
826 if (m_input_file_sp) {
827 File &in_file = m_input_file_sp->GetFile();
828 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
829 m_terminal_state.Save(in_file.GetDescriptor(), true);
830 }
831}
832
833void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
834
835ExecutionContext Debugger::GetSelectedExecutionContext() {
836 ExecutionContext exe_ctx;
837 TargetSP target_sp(GetSelectedTarget());
838 exe_ctx.SetTargetSP(target_sp);
839
840 if (target_sp) {
841 ProcessSP process_sp(target_sp->GetProcessSP());
842 exe_ctx.SetProcessSP(process_sp);
843 if (process_sp && !process_sp->IsRunning()) {
844 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
845 if (thread_sp) {
846 exe_ctx.SetThreadSP(thread_sp);
847 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
848 if (exe_ctx.GetFramePtr() == nullptr)
849 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
850 }
851 }
852 }
853 return exe_ctx;
854}
855
856void Debugger::DispatchInputInterrupt() {
857 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
858 IOHandlerSP reader_sp(m_input_reader_stack.Top());
859 if (reader_sp)
860 reader_sp->Interrupt();
861}
862
863void Debugger::DispatchInputEndOfFile() {
864 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
865 IOHandlerSP reader_sp(m_input_reader_stack.Top());
866 if (reader_sp)
867 reader_sp->GotEOF();
868}
869
870void Debugger::ClearIOHandlers() {
871 // The bottom input reader should be the main debugger input reader. We do
872 // not want to close that one here.
873 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
874 while (m_input_reader_stack.GetSize() > 1) {
875 IOHandlerSP reader_sp(m_input_reader_stack.Top());
876 if (reader_sp)
877 PopIOHandler(reader_sp);
878 }
879}
880
881void Debugger::ExecuteIOHandlers() {
882 while (true) {
883 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000886
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000888
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889 // Remove all input readers that are done from the top of the stack
890 while (true) {
891 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
892 if (top_reader_sp && top_reader_sp->GetIsDone())
893 PopIOHandler(top_reader_sp);
894 else
895 break;
896 }
897 }
898 ClearIOHandlers();
899}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000900
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
902 return m_input_reader_stack.IsTop(reader_sp);
903}
Greg Clayton44d93782014-01-27 23:43:24 +0000904
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
906 IOHandler::Type second_top_type) {
907 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
908}
909
910void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
911 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
912 m_input_reader_stack.PrintAsync(stream.get(), s, len);
913}
914
915ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
916 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
917}
918
919const char *Debugger::GetIOHandlerCommandPrefix() {
920 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
921}
922
923const char *Debugger::GetIOHandlerHelpPrologue() {
924 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
925}
926
927void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
928 PushIOHandler(reader_sp);
929
930 IOHandlerSP top_reader_sp = reader_sp;
931 while (top_reader_sp) {
932 top_reader_sp->Run();
933
934 if (top_reader_sp.get() == reader_sp.get()) {
935 if (PopIOHandler(reader_sp))
936 break;
937 }
938
939 while (true) {
940 top_reader_sp = m_input_reader_stack.Top();
941 if (top_reader_sp && top_reader_sp->GetIsDone())
942 PopIOHandler(top_reader_sp);
943 else
944 break;
945 }
946 }
947}
948
949void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
950 StreamFileSP &out,
951 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +0000952 // Before an IOHandler runs, it must have in/out/err streams. This function
953 // is called when one ore more of the streams are nullptr. We use the top
954 // input reader's in/out/err streams, or fall back to the debugger file
955 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956
957 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
958 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
959 // If no STDIN has been set, then set it appropriately
960 if (!in) {
961 if (top_reader_sp)
962 in = top_reader_sp->GetInputStreamFile();
963 else
964 in = GetInputFile();
965
966 // If there is nothing, use stdin
967 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +0000968 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 }
970 // If no STDOUT has been set, then set it appropriately
971 if (!out) {
972 if (top_reader_sp)
973 out = top_reader_sp->GetOutputStreamFile();
974 else
975 out = GetOutputFile();
976
977 // If there is nothing, use stdout
978 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +0000979 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 }
981 // If no STDERR has been set, then set it appropriately
982 if (!err) {
983 if (top_reader_sp)
984 err = top_reader_sp->GetErrorStreamFile();
985 else
986 err = GetErrorFile();
987
988 // If there is nothing, use stderr
989 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +0000990 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 }
992}
993
Raphael Isemannc01783a2018-08-29 22:50:54 +0000994void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
995 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 if (!reader_sp)
997 return;
998
999 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1000
1001 // Get the current top input reader...
1002 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1003
1004 // Don't push the same IO handler twice...
1005 if (reader_sp == top_reader_sp)
1006 return;
1007
1008 // Push our new input reader
1009 m_input_reader_stack.Push(reader_sp);
1010 reader_sp->Activate();
1011
Adrian Prantl05097242018-04-30 16:49:04 +00001012 // Interrupt the top input reader to it will exit its Run() function and let
1013 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 if (top_reader_sp) {
1015 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001016 if (cancel_top_handler)
1017 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 }
1019}
1020
1021bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1022 if (!pop_reader_sp)
1023 return false;
1024
1025 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1026
Adrian Prantl05097242018-04-30 16:49:04 +00001027 // The reader on the stop of the stack is done, so let the next read on the
1028 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 if (m_input_reader_stack.IsEmpty())
1030 return false;
1031
1032 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1033
1034 if (pop_reader_sp != reader_sp)
1035 return false;
1036
1037 reader_sp->Deactivate();
1038 reader_sp->Cancel();
1039 m_input_reader_stack.Pop();
1040
1041 reader_sp = m_input_reader_stack.Top();
1042 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001043 reader_sp->Activate();
1044
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 return true;
1046}
1047
1048StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001049 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050}
1051
1052StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001053 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054}
1055
1056size_t Debugger::GetNumDebuggers() {
1057 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1058 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1059 return g_debugger_list_ptr->size();
1060 }
1061 return 0;
1062}
1063
1064lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1065 DebuggerSP debugger_sp;
1066
1067 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1068 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1069 if (index < g_debugger_list_ptr->size())
1070 debugger_sp = g_debugger_list_ptr->at(index);
1071 }
1072
1073 return debugger_sp;
1074}
1075
1076DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1077 DebuggerSP debugger_sp;
1078
1079 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1080 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1081 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1082 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1083 if ((*pos)->GetID() == id) {
1084 debugger_sp = *pos;
1085 break;
1086 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001087 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 }
1089 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001090}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001091
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1093 const SymbolContext *sc,
1094 const SymbolContext *prev_sc,
1095 const ExecutionContext *exe_ctx,
1096 const Address *addr, Stream &s) {
1097 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001098
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 if (format == nullptr) {
1100 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1101 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1102 if (format == nullptr) {
1103 FormatEntity::Parse("${addr}: ", format_entry);
1104 format = &format_entry;
1105 }
1106 }
1107 bool function_changed = false;
1108 bool initial_function = false;
1109 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1110 if (sc && (sc->function || sc->symbol)) {
1111 if (prev_sc->symbol && sc->symbol) {
1112 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1113 prev_sc->symbol->GetType())) {
1114 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001115 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 } else if (prev_sc->function && sc->function) {
1117 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1118 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001119 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 }
Adrian Prantl05097242018-04-30 16:49:04 +00001123 // The first context on a list of instructions will have a prev_sc that has
1124 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 // would return false. But we do get a prev_sc pointer.
1126 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1127 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1128 initial_function = true;
1129 }
1130 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1131 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001132}
1133
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1135 void *baton) {
1136 // For simplicity's sake, I am not going to deal with how to close down any
1137 // open logging streams, I just redirect everything from here on out to the
1138 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001139 m_log_callback_stream_sp =
1140 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001141}
1142
Pavel Labath5e336902017-03-01 10:08:40 +00001143bool Debugger::EnableLog(llvm::StringRef channel,
1144 llvm::ArrayRef<const char *> categories,
1145 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001146 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001147 const bool should_close = true;
1148 const bool unbuffered = true;
1149
1150 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 if (m_log_callback_stream_sp) {
1152 log_stream_sp = m_log_callback_stream_sp;
1153 // For now when using the callback mode you always get thread & timestamp.
1154 log_options |=
1155 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001156 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001157 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1158 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001160 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 if (pos != m_log_streams.end())
1162 log_stream_sp = pos->second.lock();
1163 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001164 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1165 if (log_options & LLDB_LOG_OPTION_APPEND)
1166 flags |= llvm::sys::fs::F_Append;
1167 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001168 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1169 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001170 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001171 return false;
1172 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001173 log_stream_sp =
1174 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001176 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 }
1178 assert(log_stream_sp);
1179
1180 if (log_options == 0)
1181 log_options =
1182 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1183
1184 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1185 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001186}
1187
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00001188ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) {
1189 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1190
1191 if (!m_script_interpreter_sp) {
1192 if (!can_create)
1193 return nullptr;
1194 m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(
1195 GetScriptLanguage(), *this);
1196 }
1197
1198 return m_script_interpreter_sp.get();
1199}
1200
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201SourceManager &Debugger::GetSourceManager() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001202 if (!m_source_manager_up)
1203 m_source_manager_up = llvm::make_unique<SourceManager>(shared_from_this());
1204 return *m_source_manager_up;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001205}
1206
Greg Clayton44d93782014-01-27 23:43:24 +00001207// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1209 using namespace lldb;
1210 const uint32_t event_type =
1211 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1212 event_sp);
1213
1214 // if (event_type & eBreakpointEventTypeAdded
1215 // || event_type & eBreakpointEventTypeRemoved
1216 // || event_type & eBreakpointEventTypeEnabled
1217 // || event_type & eBreakpointEventTypeDisabled
1218 // || event_type & eBreakpointEventTypeCommandChanged
1219 // || event_type & eBreakpointEventTypeConditionChanged
1220 // || event_type & eBreakpointEventTypeIgnoreChanged
1221 // || event_type & eBreakpointEventTypeLocationsResolved)
1222 // {
1223 // // Don't do anything about these events, since the breakpoint
1224 // commands already echo these actions.
1225 // }
1226 //
1227 if (event_type & eBreakpointEventTypeLocationsAdded) {
1228 uint32_t num_new_locations =
1229 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1230 event_sp);
1231 if (num_new_locations > 0) {
1232 BreakpointSP breakpoint =
1233 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1234 StreamSP output_sp(GetAsyncOutputStream());
1235 if (output_sp) {
1236 output_sp->Printf("%d location%s added to breakpoint %d\n",
1237 num_new_locations, num_new_locations == 1 ? "" : "s",
1238 breakpoint->GetID());
1239 output_sp->Flush();
1240 }
Greg Clayton44d93782014-01-27 23:43:24 +00001241 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 }
1243 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1244 // {
1245 // // These locations just get disabled, not sure it is worth spamming
1246 // folks about this on the command line.
1247 // }
1248 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1249 // {
1250 // // This might be an interesting thing to note, but I'm going to
1251 // leave it quiet for now, it just looked noisy.
1252 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001253}
1254
Pavel Labatha9d58432019-07-31 12:06:50 +00001255void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1256 bool flush_stderr) {
1257 const auto &flush = [&](Stream &stream,
1258 size_t (Process::*get)(char *, size_t, Status &)) {
1259 Status error;
1260 size_t len;
1261 char buffer[1024];
1262 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1263 stream.Write(buffer, len);
1264 stream.Flush();
1265 };
Greg Clayton44d93782014-01-27 23:43:24 +00001266
Pavel Labatha9d58432019-07-31 12:06:50 +00001267 std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1268 if (flush_stdout)
1269 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT);
1270 if (flush_stderr)
1271 flush(*GetAsyncErrorStream(), &Process::GetSTDERR);
Greg Clayton44d93782014-01-27 23:43:24 +00001272}
1273
1274// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1276 using namespace lldb;
1277 const uint32_t event_type = event_sp->GetType();
1278 ProcessSP process_sp =
1279 (event_type == Process::eBroadcastBitStructuredData)
1280 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1281 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
Greg Claytondc6224e2014-10-21 01:00:42 +00001282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 StreamSP output_stream_sp = GetAsyncOutputStream();
1284 StreamSP error_stream_sp = GetAsyncErrorStream();
1285 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00001286
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (!gui_enabled) {
1288 bool pop_process_io_handler = false;
1289 assert(process_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001290
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 bool state_is_stopped = false;
1292 const bool got_state_changed =
1293 (event_type & Process::eBroadcastBitStateChanged) != 0;
1294 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1295 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1296 const bool got_structured_data =
1297 (event_type & Process::eBroadcastBitStructuredData) != 0;
Todd Fiala75930012016-08-19 04:21:48 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 if (got_state_changed) {
1300 StateType event_state =
1301 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1302 state_is_stopped = StateIsStoppedState(event_state, false);
1303 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001304
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305 // Display running state changes first before any STDIO
1306 if (got_state_changed && !state_is_stopped) {
1307 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1308 pop_process_io_handler);
1309 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001310
Pavel Labatha9d58432019-07-31 12:06:50 +00001311 // Now display STDOUT and STDERR
1312 FlushProcessOutput(*process_sp, got_stdout || got_state_changed,
1313 got_stderr || got_state_changed);
Greg Claytonb4874f12014-02-28 18:22:24 +00001314
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 // Give structured data events an opportunity to display.
1316 if (got_structured_data) {
1317 StructuredDataPluginSP plugin_sp =
1318 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1319 if (plugin_sp) {
1320 auto structured_data_sp =
1321 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1322 if (output_stream_sp) {
1323 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001324 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325 plugin_sp->GetDescription(structured_data_sp, content_stream);
1326 if (error.Success()) {
1327 if (!content_stream.GetString().empty()) {
1328 // Add newline.
1329 content_stream.PutChar('\n');
1330 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001331
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001333 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001334 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335 } else {
1336 error_stream_sp->Printf("Failed to print structured "
1337 "data with plugin %s: %s",
1338 plugin_sp->GetPluginName().AsCString(),
1339 error.AsCString());
1340 }
Todd Fiala75930012016-08-19 04:21:48 +00001341 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001343 }
Greg Clayton44d93782014-01-27 23:43:24 +00001344
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345 // Now display any stopped state changes after any STDIO
1346 if (got_state_changed && state_is_stopped) {
1347 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1348 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001349 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350
1351 output_stream_sp->Flush();
1352 error_stream_sp->Flush();
1353
1354 if (pop_process_io_handler)
1355 process_sp->PopProcessIOHandler();
1356 }
Greg Clayton44d93782014-01-27 23:43:24 +00001357}
1358
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001360 // At present the only thread event we handle is the Frame Changed event, and
1361 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 using namespace lldb;
1363 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001364 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 if (event_type == Thread::eBroadcastBitStackChanged ||
1366 event_type == Thread::eBroadcastBitThreadSelected) {
1367 ThreadSP thread_sp(
1368 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1369 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001370 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 }
1372 }
Greg Clayton44d93782014-01-27 23:43:24 +00001373}
1374
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1376
1377void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1378 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001379}
1380
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1382 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001383}
1384
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385void Debugger::DefaultEventHandler() {
1386 ListenerSP listener_sp(GetListener());
1387 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1388 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1389 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1390 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1391 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001392
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 BroadcastEventSpec process_event_spec(
1394 broadcaster_class_process,
1395 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1396 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001397
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1399 Thread::eBroadcastBitStackChanged |
1400 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1403 target_event_spec);
1404 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1405 process_event_spec);
1406 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1407 thread_event_spec);
1408 listener_sp->StartListeningForEvents(
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001409 m_command_interpreter_up.get(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1411 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1412 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001413
Adrian Prantl05097242018-04-30 16:49:04 +00001414 // Let the thread that spawned us know that we have started up and that we
1415 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001417
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 bool done = false;
1419 while (!done) {
1420 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001421 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 if (event_sp) {
1423 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1424 if (broadcaster) {
1425 uint32_t event_type = event_sp->GetType();
1426 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1427 if (broadcaster_class == broadcaster_class_process) {
1428 HandleProcessEvent(event_sp);
1429 } else if (broadcaster_class == broadcaster_class_target) {
1430 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1431 event_sp.get())) {
1432 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001433 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 } else if (broadcaster_class == broadcaster_class_thread) {
1435 HandleThreadEvent(event_sp);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001436 } else if (broadcaster == m_command_interpreter_up.get()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 if (event_type &
1438 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1439 done = true;
1440 } else if (event_type &
1441 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1442 const char *data = reinterpret_cast<const char *>(
1443 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1444 if (data && data[0]) {
1445 StreamSP error_sp(GetAsyncErrorStream());
1446 if (error_sp) {
1447 error_sp->PutCString(data);
1448 error_sp->Flush();
1449 }
1450 }
1451 } else if (event_type & CommandInterpreter::
1452 eBroadcastBitAsynchronousOutputData) {
1453 const char *data = reinterpret_cast<const char *>(
1454 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1455 if (data && data[0]) {
1456 StreamSP output_sp(GetAsyncOutputStream());
1457 if (output_sp) {
1458 output_sp->PutCString(data);
1459 output_sp->Flush();
1460 }
1461 }
1462 }
1463 }
Greg Clayton44d93782014-01-27 23:43:24 +00001464 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465
1466 if (m_forward_listener_sp)
1467 m_forward_listener_sp->AddEvent(event_sp);
1468 }
Greg Clayton44d93782014-01-27 23:43:24 +00001469 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 }
Greg Clayton44d93782014-01-27 23:43:24 +00001471}
1472
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1474 ((Debugger *)arg)->DefaultEventHandler();
Konrad Kleine85200642019-05-23 15:17:39 +00001475 return {};
Greg Clayton44d93782014-01-27 23:43:24 +00001476}
1477
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478bool Debugger::StartEventHandlerThread() {
1479 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001480 // We must synchronize with the DefaultEventHandler() thread to ensure it
1481 // is up and running and listening to events before we return from this
1482 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001484 ConstString full_name("lldb.debugger.event-handler");
1485 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1487 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001488
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001489 auto thread_name =
1490 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1491 full_name.AsCString() : "dbg.evt-handler";
1492
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493 // Use larger 8MB stack for this thread
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001494 llvm::Expected<HostThread> event_handler_thread =
1495 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1496 g_debugger_event_thread_stack_bytes);
1497
1498 if (event_handler_thread) {
1499 m_event_handler_thread = *event_handler_thread;
1500 } else {
1501 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1502 "failed to launch host thread: {}",
1503 llvm::toString(event_handler_thread.takeError()));
1504 }
Greg Claytonafa91e332014-12-01 22:41:27 +00001505
Adrian Prantl05097242018-04-30 16:49:04 +00001506 // Make sure DefaultEventHandler() is running and listening to events
1507 // before we return from this function. We are only listening for events of
1508 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1509 // event, we just need to wait an infinite amount of time for it (nullptr
1510 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001512 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513 }
1514 return m_event_handler_thread.IsJoinable();
1515}
1516
1517void Debugger::StopEventHandlerThread() {
1518 if (m_event_handler_thread.IsJoinable()) {
1519 GetCommandInterpreter().BroadcastEvent(
1520 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1521 m_event_handler_thread.Join(nullptr);
1522 }
1523}
1524
1525lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1526 Debugger *debugger = (Debugger *)arg;
1527 debugger->ExecuteIOHandlers();
1528 debugger->StopEventHandlerThread();
Konrad Kleine85200642019-05-23 15:17:39 +00001529 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530}
1531
1532bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1533
1534bool Debugger::StartIOHandlerThread() {
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001535 if (!m_io_handler_thread.IsJoinable()) {
1536 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1537 "lldb.debugger.io-handler", IOHandlerThread, this,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001538 8 * 1024 * 1024); // Use larger 8MB stack for this thread
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001539 if (io_handler_thread) {
1540 m_io_handler_thread = *io_handler_thread;
1541 } else {
1542 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1543 "failed to launch host thread: {}",
1544 llvm::toString(io_handler_thread.takeError()));
1545 }
1546 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 return m_io_handler_thread.IsJoinable();
1548}
1549
1550void Debugger::StopIOHandlerThread() {
1551 if (m_io_handler_thread.IsJoinable()) {
1552 if (m_input_file_sp)
1553 m_input_file_sp->GetFile().Close();
1554 m_io_handler_thread.Join(nullptr);
1555 }
1556}
1557
1558void Debugger::JoinIOHandlerThread() {
1559 if (HasIOHandlerThread()) {
1560 thread_result_t result;
1561 m_io_handler_thread.Join(&result);
1562 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1563 }
1564}
1565
1566Target *Debugger::GetDummyTarget() {
1567 return m_target_list.GetDummyTarget(*this).get();
1568}
1569
1570Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1571 Target *target = nullptr;
1572 if (!prefer_dummy) {
1573 target = m_target_list.GetSelectedTarget().get();
1574 if (target)
1575 return target;
1576 }
1577
1578 return GetDummyTarget();
1579}
1580
Zachary Turner97206d52017-05-12 04:51:55 +00001581Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1582 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 FileSpec repl_executable;
1584
1585 if (language == eLanguageTypeUnknown) {
1586 std::set<LanguageType> repl_languages;
1587
1588 Language::GetLanguagesSupportingREPLs(repl_languages);
1589
1590 if (repl_languages.size() == 1) {
1591 language = *repl_languages.begin();
1592 } else if (repl_languages.empty()) {
1593 err.SetErrorStringWithFormat(
1594 "LLDB isn't configured with REPL support for any languages.");
1595 return err;
1596 } else {
1597 err.SetErrorStringWithFormat(
1598 "Multiple possible REPL languages. Please specify a language.");
1599 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001600 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601 }
Greg Clayton44d93782014-01-27 23:43:24 +00001602
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 Target *const target =
1604 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001605
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001607
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001609 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610 }
1611
1612 if (!repl_sp) {
1613 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1614 Language::GetNameForLanguageType(language));
1615 return err;
1616 }
1617
1618 repl_sp->SetCompilerOptions(repl_options);
1619 repl_sp->RunLoop();
1620
1621 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001622}