blob: 51b9d4fa2eff6293dbc12aab7084e830a6267f98 [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
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000205static constexpr PropertyDefinition g_properties[] = {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000206#define LLDB_PROPERTIES_debugger
Jonas Devlieghered4044aa2019-07-26 20:55:07 +0000207#include "Properties.inc"
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000208};
Greg Clayton67cc0632012-08-22 17:17:09 +0000209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210enum {
Jonas Devlieghere971f9ca2019-07-25 21:36:37 +0000211#define LLDB_PROPERTIES_debugger
Jonas Devlieghered4044aa2019-07-26 20:55:07 +0000212#include "PropertiesEnum.inc"
Greg Clayton67cc0632012-08-22 17:17:09 +0000213};
214
Eugene Zelenkodf370552016-03-02 02:18:18 +0000215LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
Greg Clayton4c054102012-09-01 00:38:36 +0000216
Zachary Turner97206d52017-05-12 04:51:55 +0000217Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
218 VarSetOperationType op,
219 llvm::StringRef property_path,
220 llvm::StringRef value) {
Zachary Turner31d97a52016-11-17 18:08:12 +0000221 bool is_load_script = (property_path == "target.load-script-from-symbol-file");
222 bool is_escape_non_printables = (property_path == "escape-non-printables");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 TargetSP target_sp;
224 LoadScriptFromSymFile load_script_old_value;
225 if (is_load_script && exe_ctx->GetTargetSP()) {
226 target_sp = exe_ctx->GetTargetSP();
227 load_script_old_value =
228 target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
229 }
Zachary Turner97206d52017-05-12 04:51:55 +0000230 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 if (error.Success()) {
232 // FIXME it would be nice to have "on-change" callbacks for properties
Zachary Turner31d97a52016-11-17 18:08:12 +0000233 if (property_path == g_properties[ePropertyPrompt].name) {
Zachary Turner514d8cd2016-09-23 18:06:53 +0000234 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes(
236 new_prompt, GetUseColor());
237 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000238 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 GetCommandInterpreter().UpdatePrompt(new_prompt);
Zachary Turner2f3df612017-04-06 21:28:29 +0000240 auto bytes = llvm::make_unique<EventDataBytes>(new_prompt);
241 auto prompt_change_event_sp = std::make_shared<Event>(
242 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
Zachary Turner31d97a52016-11-17 18:08:12 +0000244 } else if (property_path == g_properties[ePropertyUseColor].name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 // use-color changed. Ping the prompt so it can reset the ansi terminal
246 // codes.
247 SetPrompt(GetPrompt());
248 } else if (is_load_script && target_sp &&
249 load_script_old_value == eLoadScriptFromSymFileWarn) {
250 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
251 eLoadScriptFromSymFileTrue) {
Zachary Turner97206d52017-05-12 04:51:55 +0000252 std::list<Status> errors;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 StreamString feedback_stream;
254 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
255 StreamFileSP stream_sp(GetErrorFile());
256 if (stream_sp) {
257 for (auto error : errors) {
258 stream_sp->Printf("%s\n", error.AsCString());
259 }
260 if (feedback_stream.GetSize())
Zachary Turnerc1564272016-11-16 21:15:24 +0000261 stream_sp->PutCString(feedback_stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 }
263 }
264 }
265 } else if (is_escape_non_printables) {
266 DataVisualization::ForceUpdate();
267 }
268 }
269 return error;
Greg Clayton67cc0632012-08-22 17:17:09 +0000270}
271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272bool Debugger::GetAutoConfirm() const {
273 const uint32_t idx = ePropertyAutoConfirm;
274 return m_collection_sp->GetPropertyAtIndexAsBoolean(
275 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000276}
277
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
279 const uint32_t idx = ePropertyDisassemblyFormat;
280 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000281}
282
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283const FormatEntity::Entry *Debugger::GetFrameFormat() const {
284 const uint32_t idx = ePropertyFrameFormat;
285 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000286}
287
Pavel Labath7f1c1212017-06-12 16:25:24 +0000288const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
289 const uint32_t idx = ePropertyFrameFormatUnique;
290 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
291}
292
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293bool Debugger::GetNotifyVoid() const {
294 const uint32_t idx = ePropertyNotiftVoid;
295 return m_collection_sp->GetPropertyAtIndexAsBoolean(
296 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000297}
298
Zachary Turner514d8cd2016-09-23 18:06:53 +0000299llvm::StringRef Debugger::GetPrompt() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 const uint32_t idx = ePropertyPrompt;
301 return m_collection_sp->GetPropertyAtIndexAsString(
302 nullptr, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000303}
304
Zachary Turner514d8cd2016-09-23 18:06:53 +0000305void Debugger::SetPrompt(llvm::StringRef p) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 const uint32_t idx = ePropertyPrompt;
307 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Zachary Turner514d8cd2016-09-23 18:06:53 +0000308 llvm::StringRef new_prompt = GetPrompt();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309 std::string str =
310 lldb_utility::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
311 if (str.length())
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000312 new_prompt = str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000314}
315
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000316llvm::StringRef Debugger::GetReproducerPath() const {
317 auto &r = repro::Reproducer::Instance();
318 return r.GetReproducerPath().GetCString();
319}
320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321const FormatEntity::Entry *Debugger::GetThreadFormat() const {
322 const uint32_t idx = ePropertyThreadFormat;
323 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000324}
325
Jim Ingham6a9767c2016-11-08 20:36:40 +0000326const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
327 const uint32_t idx = ePropertyThreadStopFormat;
328 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
329}
330
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
332 const uint32_t idx = ePropertyScriptLanguage;
333 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
334 nullptr, idx, g_properties[idx].default_uint_value);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000335}
336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
338 const uint32_t idx = ePropertyScriptLanguage;
339 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
340 script_lang);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000341}
342
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343uint32_t Debugger::GetTerminalWidth() const {
344 const uint32_t idx = ePropertyTerminalWidth;
345 return m_collection_sp->GetPropertyAtIndexAsSInt64(
346 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000347}
348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349bool Debugger::SetTerminalWidth(uint32_t term_width) {
350 const uint32_t idx = ePropertyTerminalWidth;
351 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
Greg Clayton67cc0632012-08-22 17:17:09 +0000352}
353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354bool Debugger::GetUseExternalEditor() const {
355 const uint32_t idx = ePropertyUseExternalEditor;
356 return m_collection_sp->GetPropertyAtIndexAsBoolean(
357 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000358}
Greg Claytone372b982011-11-21 21:44:34 +0000359
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360bool Debugger::SetUseExternalEditor(bool b) {
361 const uint32_t idx = ePropertyUseExternalEditor;
362 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granataebdc1ac2014-11-05 21:20:48 +0000363}
Enrico Granata553fad52013-10-25 23:09:40 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365bool Debugger::GetUseColor() const {
366 const uint32_t idx = ePropertyUseColor;
367 return m_collection_sp->GetPropertyAtIndexAsBoolean(
368 nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata553fad52013-10-25 23:09:40 +0000369}
370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371bool Debugger::SetUseColor(bool b) {
372 const uint32_t idx = ePropertyUseColor;
373 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
374 SetPrompt(GetPrompt());
375 return ret;
Sean Callanan66810412015-10-19 23:11:07 +0000376}
377
Raphael Isemann566afa02018-08-02 00:30:15 +0000378bool Debugger::GetHighlightSource() const {
379 const uint32_t idx = ePropertyHighlightSource;
380 return m_collection_sp->GetPropertyAtIndexAsBoolean(
381 nullptr, idx, g_properties[idx].default_uint_value);
382}
383
Todd Fiala9666ba72016-09-21 20:13:14 +0000384StopShowColumn Debugger::GetStopShowColumn() const {
385 const uint32_t idx = ePropertyStopShowColumn;
386 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
387 nullptr, idx, g_properties[idx].default_uint_value);
388}
389
Raphael Isemann20786322018-08-30 00:09:21 +0000390llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000391 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
Raphael Isemann20786322018-08-30 00:09:21 +0000392 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000393}
394
Raphael Isemann20786322018-08-30 00:09:21 +0000395llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
Todd Fiala9666ba72016-09-21 20:13:14 +0000396 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
Raphael Isemann20786322018-08-30 00:09:21 +0000397 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
Todd Fiala9666ba72016-09-21 20:13:14 +0000398}
399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400uint32_t Debugger::GetStopSourceLineCount(bool before) const {
401 const uint32_t idx =
402 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
403 return m_collection_sp->GetPropertyAtIndexAsSInt64(
404 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000405}
406
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
408 const uint32_t idx = ePropertyStopDisassemblyDisplay;
409 return (Debugger::StopDisassemblyType)
410 m_collection_sp->GetPropertyAtIndexAsEnumeration(
411 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000412}
413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414uint32_t Debugger::GetDisassemblyLineCount() const {
415 const uint32_t idx = ePropertyStopDisassemblyCount;
416 return m_collection_sp->GetPropertyAtIndexAsSInt64(
417 nullptr, idx, g_properties[idx].default_uint_value);
Sean Callanan66810412015-10-19 23:11:07 +0000418}
419
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420bool Debugger::GetAutoOneLineSummaries() const {
421 const uint32_t idx = ePropertyAutoOneLineSummaries;
422 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
Sean Callanan66810412015-10-19 23:11:07 +0000423}
424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425bool Debugger::GetEscapeNonPrintables() const {
426 const uint32_t idx = ePropertyEscapeNonPrintables;
427 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
428}
429
430bool Debugger::GetAutoIndent() const {
431 const uint32_t idx = ePropertyAutoIndent;
432 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
433}
434
435bool Debugger::SetAutoIndent(bool b) {
436 const uint32_t idx = ePropertyAutoIndent;
437 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
438}
439
440bool Debugger::GetPrintDecls() const {
441 const uint32_t idx = ePropertyPrintDecls;
442 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
443}
444
445bool Debugger::SetPrintDecls(bool b) {
446 const uint32_t idx = ePropertyPrintDecls;
447 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
448}
449
450uint32_t Debugger::GetTabSize() const {
451 const uint32_t idx = ePropertyTabSize;
452 return m_collection_sp->GetPropertyAtIndexAsUInt64(
453 nullptr, idx, g_properties[idx].default_uint_value);
454}
455
456bool Debugger::SetTabSize(uint32_t tab_size) {
457 const uint32_t idx = ePropertyTabSize;
458 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
Sean Callanan66810412015-10-19 23:11:07 +0000459}
460
Greg Clayton1b654882010-09-19 02:33:57 +0000461#pragma mark Debugger
462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463// const DebuggerPropertiesSP &
464// Debugger::GetSettings() const
Greg Clayton67cc0632012-08-22 17:17:09 +0000465//{
466// return m_properties_sp;
467//}
468//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
471 assert(g_debugger_list_ptr == nullptr &&
472 "Debugger::Initialize called more than once!");
473 g_debugger_list_mutex_ptr = new std::recursive_mutex();
474 g_debugger_list_ptr = new DebuggerList();
475 g_load_plugin_callback = load_plugin_callback;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000476}
477
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478void Debugger::Terminate() {
479 assert(g_debugger_list_ptr &&
480 "Debugger::Terminate called without a matching Debugger::Initialize!");
Zachary Turnere6e2bb32015-03-31 21:03:22 +0000481
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
483 // Clear our master list of debugger objects
Greg Clayton6c42e062016-05-26 16:51:23 +0000484 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
486 for (const auto &debugger : *g_debugger_list_ptr)
487 debugger->Clear();
488 g_debugger_list_ptr->clear();
Greg Clayton6c42e062016-05-26 16:51:23 +0000489 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000491}
492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
Caroline Tice20bd37f2011-03-10 22:14:10 +0000496
Zachary Turner97206d52017-05-12 04:51:55 +0000497bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 if (g_load_plugin_callback) {
499 llvm::sys::DynamicLibrary dynlib =
500 g_load_plugin_callback(shared_from_this(), spec, error);
501 if (dynlib.isValid()) {
502 m_loaded_plugins.push_back(dynlib);
503 return true;
Enrico Granatae743c782013-04-24 21:29:08 +0000504 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000506 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
507 // if the public API layer isn't available (code is linking against all of
508 // the internal LLDB static libraries), then we can't load plugins
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 error.SetErrorString("Public API layer is not available");
510 }
511 return false;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000512}
513
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000514static FileSystem::EnumerateDirectoryResult
Zachary Turner7d86ee52017-03-08 17:56:08 +0000515LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000516 llvm::StringRef path) {
Zachary Turner97206d52017-05-12 04:51:55 +0000517 Status error;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000518
Jonas Devliegheread8d48f2018-06-13 16:23:21 +0000519 static ConstString g_dylibext(".dylib");
520 static ConstString g_solibext(".so");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521
522 if (!baton)
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000523 return FileSystem::eEnumerateDirectoryResultQuit;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524
525 Debugger *debugger = (Debugger *)baton;
526
Zachary Turner7d86ee52017-03-08 17:56:08 +0000527 namespace fs = llvm::sys::fs;
Adrian Prantl05097242018-04-30 16:49:04 +0000528 // If we have a regular file, a symbolic link or unknown file type, try and
529 // process the file. We must handle unknown as sometimes the directory
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 // enumeration might be enumerating a file system that doesn't have correct
531 // file type information.
Zachary Turner7d86ee52017-03-08 17:56:08 +0000532 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
533 ft == fs::file_type::type_unknown) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000534 FileSpec plugin_file_spec(path);
535 FileSystem::Instance().Resolve(plugin_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536
537 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
538 plugin_file_spec.GetFileNameExtension() != g_solibext) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000539 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000540 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541
Zachary Turner97206d52017-05-12 04:51:55 +0000542 Status plugin_load_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
544
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000545 return FileSystem::eEnumerateDirectoryResultNext;
Zachary Turner7d86ee52017-03-08 17:56:08 +0000546 } else if (ft == fs::file_type::directory_file ||
547 ft == fs::file_type::symlink_file ||
548 ft == fs::file_type::type_unknown) {
Adrian Prantl05097242018-04-30 16:49:04 +0000549 // Try and recurse into anything that a directory or symbolic link. We must
550 // also do this for unknown as sometimes the directory enumeration might be
551 // enumerating a file system that doesn't have correct file type
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 // information.
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000553 return FileSystem::eEnumerateDirectoryResultEnter;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 }
555
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000556 return FileSystem::eEnumerateDirectoryResultNext;
Enrico Granata21dfcd92012-09-28 23:57:51 +0000557}
558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559void Debugger::InstanceInitialize() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 const bool find_directories = true;
561 const bool find_files = true;
562 const bool find_other = true;
563 char dir_path[PATH_MAX];
Pavel Labath60f028f2018-06-19 15:09:07 +0000564 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000565 if (FileSystem::Instance().Exists(dir_spec) &&
566 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000567 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
568 find_files, find_other,
569 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000570 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000572
Pavel Labath60f028f2018-06-19 15:09:07 +0000573 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000574 if (FileSystem::Instance().Exists(dir_spec) &&
575 dir_spec.GetPath(dir_path, sizeof(dir_path))) {
Jonas Devlieghere35e4c842018-11-01 00:33:27 +0000576 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
577 find_files, find_other,
578 LoadPluginCallback, this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
581
582 PluginManager::DebuggerInitialize(*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000583}
584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
586 void *baton) {
587 DebuggerSP debugger_sp(new Debugger(log_callback, baton));
588 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
589 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
590 g_debugger_list_ptr->push_back(debugger_sp);
591 }
592 debugger_sp->InstanceInitialize();
593 return debugger_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000594}
595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596void Debugger::Destroy(DebuggerSP &debugger_sp) {
597 if (!debugger_sp)
598 return;
599
600 debugger_sp->Clear();
601
602 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
603 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
604 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
605 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
606 if ((*pos).get() == debugger_sp.get()) {
607 g_debugger_list_ptr->erase(pos);
Caroline Ticee02657b2011-01-22 01:02:07 +0000608 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000612}
613
Greg Clayton4d122c42011-09-17 08:33:22 +0000614DebuggerSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +0000615Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 DebuggerSP debugger_sp;
617 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
618 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
619 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
620 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
621 if ((*pos)->m_instance_name == instance_name) {
622 debugger_sp = *pos;
623 break;
624 }
Greg Clayton6920b522012-08-22 18:39:03 +0000625 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 }
627 return debugger_sp;
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000628}
Greg Clayton66111032010-06-23 01:19:29 +0000629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
631 TargetSP target_sp;
632 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
633 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
634 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
635 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
636 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
637 if (target_sp)
638 break;
Greg Clayton66111032010-06-23 01:19:29 +0000639 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 }
641 return target_sp;
Greg Clayton66111032010-06-23 01:19:29 +0000642}
643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644TargetSP Debugger::FindTargetWithProcess(Process *process) {
645 TargetSP target_sp;
646 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
647 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
648 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
649 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
650 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
651 if (target_sp)
652 break;
Greg Claytone4e45922011-11-16 05:37:56 +0000653 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 }
655 return target_sp;
Greg Claytone4e45922011-11-16 05:37:56 +0000656}
657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
659 : UserID(g_unique_id++),
Zachary Turner2f3df612017-04-06 21:28:29 +0000660 Properties(std::make_shared<OptionValueProperties>()),
661 m_input_file_sp(std::make_shared<StreamFile>(stdin, false)),
662 m_output_file_sp(std::make_shared<StreamFile>(stdout, false)),
663 m_error_file_sp(std::make_shared<StreamFile>(stderr, false)),
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000664 m_input_recorder(nullptr),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
666 m_terminal_state(), m_target_list(*this), m_platform_list(),
667 m_listener_sp(Listener::MakeListener("lldb.Debugger")),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000668 m_source_manager_up(), m_source_file_cache(),
Jonas Devliegheref20dd1d2019-04-26 20:03:22 +0000669 m_command_interpreter_up(
670 llvm::make_unique<CommandInterpreter>(*this, false)),
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000671 m_script_interpreter_sp(), m_input_reader_stack(), m_instance_name(),
672 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
674 m_forward_listener_sp(), m_clear_once() {
675 char instance_cstr[256];
676 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
677 m_instance_name.SetCString(instance_cstr);
678 if (log_callback)
Zachary Turner2f3df612017-04-06 21:28:29 +0000679 m_log_callback_stream_sp =
680 std::make_shared<StreamCallback>(log_callback, baton);
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000681 m_command_interpreter_up->Initialize();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 // Always add our default platform to the platform list
683 PlatformSP default_platform_sp(Platform::GetHostPlatform());
684 assert(default_platform_sp);
685 m_platform_list.Append(default_platform_sp, true);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000686
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 m_collection_sp->Initialize(g_properties);
688 m_collection_sp->AppendProperty(
689 ConstString("target"),
690 ConstString("Settings specify to debugging targets."), true,
691 Target::GetGlobalProperties()->GetValueProperties());
692 m_collection_sp->AppendProperty(
693 ConstString("platform"), ConstString("Platform settings."), true,
694 Platform::GetGlobalPlatformProperties()->GetValueProperties());
Adrian Prantl235354be2018-03-02 22:42:44 +0000695 m_collection_sp->AppendProperty(
Adrian Prantl3cd29bc2018-03-10 01:11:25 +0000696 ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
697 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000698 if (m_command_interpreter_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 m_collection_sp->AppendProperty(
700 ConstString("interpreter"),
701 ConstString("Settings specify to the debugger's command interpreter."),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000702 true, m_command_interpreter_up->GetValueProperties());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 }
704 OptionValueSInt64 *term_width =
705 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
706 nullptr, ePropertyTerminalWidth);
707 term_width->SetMinimumValue(10);
708 term_width->SetMaximumValue(1024);
709
710 // Turn off use-color if this is a dumb terminal.
711 const char *term = getenv("TERM");
712 if (term && !strcmp(term, "dumb"))
713 SetUseColor(false);
Raphael Isemanneca9ce12018-08-27 15:16:25 +0000714 // Turn off use-color if we don't write to a terminal with color support.
715 if (!m_output_file_sp->GetFile().GetIsTerminalWithColors())
716 SetUseColor(false);
David Bolvansky8aa23612018-09-05 22:06:58 +0000717
718#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
719 // Enabling use of ANSI color codes because LLDB is using them to highlight
720 // text.
721 llvm::sys::Process::UseANSIEscapeCodes(true);
David Bolvansky8aa23612018-09-05 22:06:58 +0000722#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723}
724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725Debugger::~Debugger() { Clear(); }
Jim Ingham8314c522011-09-15 21:36:42 +0000726
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727void Debugger::Clear() {
Adrian Prantl05097242018-04-30 16:49:04 +0000728 // Make sure we call this function only once. With the C++ global destructor
729 // chain having a list of debuggers and with code that can be running on
730 // other threads, we need to ensure this doesn't happen multiple times.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 //
732 // The following functions call Debugger::Clear():
733 // Debugger::~Debugger();
734 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
735 // static void Debugger::Terminate();
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +0000736 llvm::call_once(m_clear_once, [this]() {
Greg Clayton44d93782014-01-27 23:43:24 +0000737 ClearIOHandlers();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 StopIOHandlerThread();
739 StopEventHandlerThread();
740 m_listener_sp->Clear();
741 int num_targets = m_target_list.GetNumTargets();
742 for (int i = 0; i < num_targets; i++) {
743 TargetSP target_sp(m_target_list.GetTargetAtIndex(i));
744 if (target_sp) {
745 ProcessSP process_sp(target_sp->GetProcessSP());
746 if (process_sp)
747 process_sp->Finalize();
748 target_sp->Destroy();
749 }
Greg Clayton577508d2014-06-20 00:23:57 +0000750 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 m_broadcaster_manager_sp->Clear();
752
753 // Close the input file _before_ we close the input read communications
Adrian Prantl05097242018-04-30 16:49:04 +0000754 // class as it does NOT own the input file, our m_input_file does.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 m_terminal_state.Clear();
756 if (m_input_file_sp)
757 m_input_file_sp->GetFile().Close();
758
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000759 m_command_interpreter_up->Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 });
Greg Clayton44d93782014-01-27 23:43:24 +0000761}
762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763bool Debugger::GetCloseInputOnEOF() const {
764 // return m_input_comm.GetCloseOnEOF();
765 return false;
Greg Clayton44d93782014-01-27 23:43:24 +0000766}
767
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768void Debugger::SetCloseInputOnEOF(bool b) {
769 // m_input_comm.SetCloseOnEOF(b);
770}
771
772bool Debugger::GetAsyncExecution() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000773 return !m_command_interpreter_up->GetSynchronous();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774}
775
776void Debugger::SetAsyncExecution(bool async_execution) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000777 m_command_interpreter_up->SetSynchronous(!async_execution);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778}
779
Jonas Devlieghered77c2e02019-03-02 00:20:26 +0000780repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
781
782void Debugger::SetInputFileHandle(FILE *fh, bool tranfer_ownership,
783 repro::DataRecorder *recorder) {
784 m_input_recorder = recorder;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 if (m_input_file_sp)
786 m_input_file_sp->GetFile().SetStream(fh, tranfer_ownership);
787 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000788 m_input_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789
790 File &in_file = m_input_file_sp->GetFile();
791 if (!in_file.IsValid())
792 in_file.SetStream(stdin, true);
793
Adrian Prantl05097242018-04-30 16:49:04 +0000794 // Save away the terminal state if that is relevant, so that we can restore
795 // it in RestoreInputState.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 SaveInputTerminalState();
797}
798
799void Debugger::SetOutputFileHandle(FILE *fh, bool tranfer_ownership) {
800 if (m_output_file_sp)
801 m_output_file_sp->GetFile().SetStream(fh, tranfer_ownership);
802 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000803 m_output_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804
805 File &out_file = m_output_file_sp->GetFile();
806 if (!out_file.IsValid())
807 out_file.SetStream(stdout, false);
808
Jonas Devlieghere2b29b432019-04-26 22:43:16 +0000809 // Do not create the ScriptInterpreter just for setting the output file
810 // handle as the constructor will know how to do the right thing on its own.
811 if (ScriptInterpreter *script_interpreter =
812 GetScriptInterpreter(/*can_create=*/false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 script_interpreter->ResetOutputFileHandle(fh);
814}
815
816void Debugger::SetErrorFileHandle(FILE *fh, bool tranfer_ownership) {
817 if (m_error_file_sp)
818 m_error_file_sp->GetFile().SetStream(fh, tranfer_ownership);
819 else
Zachary Turner2f3df612017-04-06 21:28:29 +0000820 m_error_file_sp = std::make_shared<StreamFile>(fh, tranfer_ownership);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821
822 File &err_file = m_error_file_sp->GetFile();
823 if (!err_file.IsValid())
824 err_file.SetStream(stderr, false);
825}
826
827void Debugger::SaveInputTerminalState() {
828 if (m_input_file_sp) {
829 File &in_file = m_input_file_sp->GetFile();
830 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
831 m_terminal_state.Save(in_file.GetDescriptor(), true);
832 }
833}
834
835void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
836
837ExecutionContext Debugger::GetSelectedExecutionContext() {
838 ExecutionContext exe_ctx;
839 TargetSP target_sp(GetSelectedTarget());
840 exe_ctx.SetTargetSP(target_sp);
841
842 if (target_sp) {
843 ProcessSP process_sp(target_sp->GetProcessSP());
844 exe_ctx.SetProcessSP(process_sp);
845 if (process_sp && !process_sp->IsRunning()) {
846 ThreadSP thread_sp(process_sp->GetThreadList().GetSelectedThread());
847 if (thread_sp) {
848 exe_ctx.SetThreadSP(thread_sp);
849 exe_ctx.SetFrameSP(thread_sp->GetSelectedFrame());
850 if (exe_ctx.GetFramePtr() == nullptr)
851 exe_ctx.SetFrameSP(thread_sp->GetStackFrameAtIndex(0));
852 }
853 }
854 }
855 return exe_ctx;
856}
857
858void Debugger::DispatchInputInterrupt() {
859 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
860 IOHandlerSP reader_sp(m_input_reader_stack.Top());
861 if (reader_sp)
862 reader_sp->Interrupt();
863}
864
865void Debugger::DispatchInputEndOfFile() {
866 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
867 IOHandlerSP reader_sp(m_input_reader_stack.Top());
868 if (reader_sp)
869 reader_sp->GotEOF();
870}
871
872void Debugger::ClearIOHandlers() {
873 // The bottom input reader should be the main debugger input reader. We do
874 // not want to close that one here.
875 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
876 while (m_input_reader_stack.GetSize() > 1) {
877 IOHandlerSP reader_sp(m_input_reader_stack.Top());
878 if (reader_sp)
879 PopIOHandler(reader_sp);
880 }
881}
882
883void Debugger::ExecuteIOHandlers() {
884 while (true) {
885 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886 if (!reader_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 break;
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000888
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889 reader_sp->Run();
Pavel Labath44464872015-05-27 12:40:32 +0000890
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 // Remove all input readers that are done from the top of the stack
892 while (true) {
893 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
894 if (top_reader_sp && top_reader_sp->GetIsDone())
895 PopIOHandler(top_reader_sp);
896 else
897 break;
898 }
899 }
900 ClearIOHandlers();
901}
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000902
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
904 return m_input_reader_stack.IsTop(reader_sp);
905}
Greg Clayton44d93782014-01-27 23:43:24 +0000906
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
908 IOHandler::Type second_top_type) {
909 return m_input_reader_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
910}
911
912void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
913 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
914 m_input_reader_stack.PrintAsync(stream.get(), s, len);
915}
916
917ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
918 return m_input_reader_stack.GetTopIOHandlerControlSequence(ch);
919}
920
921const char *Debugger::GetIOHandlerCommandPrefix() {
922 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
923}
924
925const char *Debugger::GetIOHandlerHelpPrologue() {
926 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
927}
928
929void Debugger::RunIOHandler(const IOHandlerSP &reader_sp) {
930 PushIOHandler(reader_sp);
931
932 IOHandlerSP top_reader_sp = reader_sp;
933 while (top_reader_sp) {
934 top_reader_sp->Run();
935
936 if (top_reader_sp.get() == reader_sp.get()) {
937 if (PopIOHandler(reader_sp))
938 break;
939 }
940
941 while (true) {
942 top_reader_sp = m_input_reader_stack.Top();
943 if (top_reader_sp && top_reader_sp->GetIsDone())
944 PopIOHandler(top_reader_sp);
945 else
946 break;
947 }
948 }
949}
950
951void Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in,
952 StreamFileSP &out,
953 StreamFileSP &err) {
Adrian Prantl05097242018-04-30 16:49:04 +0000954 // Before an IOHandler runs, it must have in/out/err streams. This function
955 // is called when one ore more of the streams are nullptr. We use the top
956 // input reader's in/out/err streams, or fall back to the debugger file
957 // handles, or we fall back onto stdin/stdout/stderr as a last resort.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958
959 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
960 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
961 // If no STDIN has been set, then set it appropriately
962 if (!in) {
963 if (top_reader_sp)
964 in = top_reader_sp->GetInputStreamFile();
965 else
966 in = GetInputFile();
967
968 // If there is nothing, use stdin
969 if (!in)
Zachary Turner2f3df612017-04-06 21:28:29 +0000970 in = std::make_shared<StreamFile>(stdin, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 }
972 // If no STDOUT has been set, then set it appropriately
973 if (!out) {
974 if (top_reader_sp)
975 out = top_reader_sp->GetOutputStreamFile();
976 else
977 out = GetOutputFile();
978
979 // If there is nothing, use stdout
980 if (!out)
Zachary Turner2f3df612017-04-06 21:28:29 +0000981 out = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 }
983 // If no STDERR has been set, then set it appropriately
984 if (!err) {
985 if (top_reader_sp)
986 err = top_reader_sp->GetErrorStreamFile();
987 else
988 err = GetErrorFile();
989
990 // If there is nothing, use stderr
991 if (!err)
Zachary Turner2f3df612017-04-06 21:28:29 +0000992 err = std::make_shared<StreamFile>(stdout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 }
994}
995
Raphael Isemannc01783a2018-08-29 22:50:54 +0000996void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
997 bool cancel_top_handler) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 if (!reader_sp)
999 return;
1000
1001 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1002
1003 // Get the current top input reader...
1004 IOHandlerSP top_reader_sp(m_input_reader_stack.Top());
1005
1006 // Don't push the same IO handler twice...
1007 if (reader_sp == top_reader_sp)
1008 return;
1009
1010 // Push our new input reader
1011 m_input_reader_stack.Push(reader_sp);
1012 reader_sp->Activate();
1013
Adrian Prantl05097242018-04-30 16:49:04 +00001014 // Interrupt the top input reader to it will exit its Run() function and let
1015 // this new input reader take over
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 if (top_reader_sp) {
1017 top_reader_sp->Deactivate();
Raphael Isemannc01783a2018-08-29 22:50:54 +00001018 if (cancel_top_handler)
1019 top_reader_sp->Cancel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 }
1021}
1022
1023bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1024 if (!pop_reader_sp)
1025 return false;
1026
1027 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex());
1028
Adrian Prantl05097242018-04-30 16:49:04 +00001029 // The reader on the stop of the stack is done, so let the next read on the
1030 // stack refresh its prompt and if there is one...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 if (m_input_reader_stack.IsEmpty())
1032 return false;
1033
1034 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1035
1036 if (pop_reader_sp != reader_sp)
1037 return false;
1038
1039 reader_sp->Deactivate();
1040 reader_sp->Cancel();
1041 m_input_reader_stack.Pop();
1042
1043 reader_sp = m_input_reader_stack.Top();
1044 if (reader_sp)
Pavel Labath44464872015-05-27 12:40:32 +00001045 reader_sp->Activate();
1046
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 return true;
1048}
1049
1050StreamSP Debugger::GetAsyncOutputStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001051 return std::make_shared<StreamAsynchronousIO>(*this, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052}
1053
1054StreamSP Debugger::GetAsyncErrorStream() {
Zachary Turner2f3df612017-04-06 21:28:29 +00001055 return std::make_shared<StreamAsynchronousIO>(*this, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056}
1057
1058size_t Debugger::GetNumDebuggers() {
1059 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1060 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1061 return g_debugger_list_ptr->size();
1062 }
1063 return 0;
1064}
1065
1066lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1067 DebuggerSP debugger_sp;
1068
1069 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1070 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1071 if (index < g_debugger_list_ptr->size())
1072 debugger_sp = g_debugger_list_ptr->at(index);
1073 }
1074
1075 return debugger_sp;
1076}
1077
1078DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1079 DebuggerSP debugger_sp;
1080
1081 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1082 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1083 DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1084 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
1085 if ((*pos)->GetID() == id) {
1086 debugger_sp = *pos;
1087 break;
1088 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001089 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 }
1091 return debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001092}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1095 const SymbolContext *sc,
1096 const SymbolContext *prev_sc,
1097 const ExecutionContext *exe_ctx,
1098 const Address *addr, Stream &s) {
1099 FormatEntity::Entry format_entry;
Greg Clayton554f68d2015-02-04 22:00:53 +00001100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 if (format == nullptr) {
1102 if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1103 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1104 if (format == nullptr) {
1105 FormatEntity::Parse("${addr}: ", format_entry);
1106 format = &format_entry;
1107 }
1108 }
1109 bool function_changed = false;
1110 bool initial_function = false;
1111 if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1112 if (sc && (sc->function || sc->symbol)) {
1113 if (prev_sc->symbol && sc->symbol) {
1114 if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1115 prev_sc->symbol->GetType())) {
1116 function_changed = true;
Greg Clayton554f68d2015-02-04 22:00:53 +00001117 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 } else if (prev_sc->function && sc->function) {
1119 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1120 function_changed = true;
Jason Molendaaff1b352014-10-10 23:07:36 +00001121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 }
Jason Molendaaff1b352014-10-10 23:07:36 +00001123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 }
Adrian Prantl05097242018-04-30 16:49:04 +00001125 // The first context on a list of instructions will have a prev_sc that has
1126 // no Function or Symbol -- if SymbolContext had an IsValid() method, it
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 // would return false. But we do get a prev_sc pointer.
1128 if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1129 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1130 initial_function = true;
1131 }
1132 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1133 function_changed, initial_function);
Jason Molendaaff1b352014-10-10 23:07:36 +00001134}
1135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1137 void *baton) {
1138 // For simplicity's sake, I am not going to deal with how to close down any
1139 // open logging streams, I just redirect everything from here on out to the
1140 // callback.
Zachary Turner2f3df612017-04-06 21:28:29 +00001141 m_log_callback_stream_sp =
1142 std::make_shared<StreamCallback>(log_callback, baton);
Jim Ingham228063c2012-02-21 02:23:08 +00001143}
1144
Pavel Labath5e336902017-03-01 10:08:40 +00001145bool Debugger::EnableLog(llvm::StringRef channel,
1146 llvm::ArrayRef<const char *> categories,
1147 llvm::StringRef log_file, uint32_t log_options,
Pavel Labath775588c2017-03-15 09:06:58 +00001148 llvm::raw_ostream &error_stream) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001149 const bool should_close = true;
1150 const bool unbuffered = true;
1151
1152 std::shared_ptr<llvm::raw_ostream> log_stream_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 if (m_log_callback_stream_sp) {
1154 log_stream_sp = m_log_callback_stream_sp;
1155 // For now when using the callback mode you always get thread & timestamp.
1156 log_options |=
1157 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
Pavel Labath5e336902017-03-01 10:08:40 +00001158 } else if (log_file.empty()) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001159 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1160 GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161 } else {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001162 auto pos = m_log_streams.find(log_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 if (pos != m_log_streams.end())
1164 log_stream_sp = pos->second.lock();
1165 if (!log_stream_sp) {
Pavel Labath5fae71c2017-02-10 11:49:21 +00001166 llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1167 if (log_options & LLDB_LOG_OPTION_APPEND)
1168 flags |= llvm::sys::fs::F_Append;
1169 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001170 if (std::error_code ec = llvm::sys::fs::openFileForWrite(
1171 log_file, FD, llvm::sys::fs::CD_CreateAlways, flags)) {
Pavel Labath775588c2017-03-15 09:06:58 +00001172 error_stream << "Unable to open log file: " << ec.message();
Pavel Labath5fae71c2017-02-10 11:49:21 +00001173 return false;
1174 }
Zachary Turner2f3df612017-04-06 21:28:29 +00001175 log_stream_sp =
1176 std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 m_log_streams[log_file] = log_stream_sp;
Jim Ingham228063c2012-02-21 02:23:08 +00001178 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001179 }
1180 assert(log_stream_sp);
1181
1182 if (log_options == 0)
1183 log_options =
1184 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1185
1186 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1187 error_stream);
Jim Ingham228063c2012-02-21 02:23:08 +00001188}
1189
Jonas Devlieghere2b29b432019-04-26 22:43:16 +00001190ScriptInterpreter *Debugger::GetScriptInterpreter(bool can_create) {
1191 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1192
1193 if (!m_script_interpreter_sp) {
1194 if (!can_create)
1195 return nullptr;
1196 m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(
1197 GetScriptLanguage(), *this);
1198 }
1199
1200 return m_script_interpreter_sp.get();
1201}
1202
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203SourceManager &Debugger::GetSourceManager() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001204 if (!m_source_manager_up)
1205 m_source_manager_up = llvm::make_unique<SourceManager>(shared_from_this());
1206 return *m_source_manager_up;
Greg Clayton9585fbf2013-03-19 00:20:55 +00001207}
1208
Greg Clayton44d93782014-01-27 23:43:24 +00001209// This function handles events that were broadcast by the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1211 using namespace lldb;
1212 const uint32_t event_type =
1213 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1214 event_sp);
1215
1216 // if (event_type & eBreakpointEventTypeAdded
1217 // || event_type & eBreakpointEventTypeRemoved
1218 // || event_type & eBreakpointEventTypeEnabled
1219 // || event_type & eBreakpointEventTypeDisabled
1220 // || event_type & eBreakpointEventTypeCommandChanged
1221 // || event_type & eBreakpointEventTypeConditionChanged
1222 // || event_type & eBreakpointEventTypeIgnoreChanged
1223 // || event_type & eBreakpointEventTypeLocationsResolved)
1224 // {
1225 // // Don't do anything about these events, since the breakpoint
1226 // commands already echo these actions.
1227 // }
1228 //
1229 if (event_type & eBreakpointEventTypeLocationsAdded) {
1230 uint32_t num_new_locations =
1231 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1232 event_sp);
1233 if (num_new_locations > 0) {
1234 BreakpointSP breakpoint =
1235 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1236 StreamSP output_sp(GetAsyncOutputStream());
1237 if (output_sp) {
1238 output_sp->Printf("%d location%s added to breakpoint %d\n",
1239 num_new_locations, num_new_locations == 1 ? "" : "s",
1240 breakpoint->GetID());
1241 output_sp->Flush();
1242 }
Greg Clayton44d93782014-01-27 23:43:24 +00001243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 }
1245 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1246 // {
1247 // // These locations just get disabled, not sure it is worth spamming
1248 // folks about this on the command line.
1249 // }
1250 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1251 // {
1252 // // This might be an interesting thing to note, but I'm going to
1253 // leave it quiet for now, it just looked noisy.
1254 // }
Greg Clayton44d93782014-01-27 23:43:24 +00001255}
1256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1258 size_t total_bytes = 0;
1259 if (stream == nullptr)
1260 stream = GetOutputFile().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001261
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 if (stream) {
1263 // The process has stuff waiting for stdout; get it and write it out to the
1264 // appropriate place.
1265 if (process == nullptr) {
1266 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1267 if (target_sp)
1268 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001271 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 size_t len;
1273 char stdio_buffer[1024];
1274 while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1275 error)) > 0) {
1276 stream->Write(stdio_buffer, len);
1277 total_bytes += len;
1278 }
1279 }
1280 stream->Flush();
1281 }
1282 return total_bytes;
Greg Clayton44d93782014-01-27 23:43:24 +00001283}
1284
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1286 size_t total_bytes = 0;
1287 if (stream == nullptr)
1288 stream = GetOutputFile().get();
1289
1290 if (stream) {
1291 // The process has stuff waiting for stderr; get it and write it out to the
1292 // appropriate place.
1293 if (process == nullptr) {
1294 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1295 if (target_sp)
1296 process = target_sp->GetProcessSP().get();
Greg Clayton44d93782014-01-27 23:43:24 +00001297 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 if (process) {
Zachary Turner97206d52017-05-12 04:51:55 +00001299 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 size_t len;
1301 char stdio_buffer[1024];
1302 while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1303 error)) > 0) {
1304 stream->Write(stdio_buffer, len);
1305 total_bytes += len;
1306 }
1307 }
1308 stream->Flush();
1309 }
1310 return total_bytes;
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
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 // Now display and STDOUT
1351 if (got_stdout || got_state_changed) {
1352 GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1353 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001354
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355 // Now display and STDERR
1356 if (got_stderr || got_state_changed) {
1357 GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1358 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001359
Kate Stoneb9c1b512016-09-06 20:57:50 +00001360 // Give structured data events an opportunity to display.
1361 if (got_structured_data) {
1362 StructuredDataPluginSP plugin_sp =
1363 EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1364 if (plugin_sp) {
1365 auto structured_data_sp =
1366 EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1367 if (output_stream_sp) {
1368 StreamString content_stream;
Zachary Turner97206d52017-05-12 04:51:55 +00001369 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 plugin_sp->GetDescription(structured_data_sp, content_stream);
1371 if (error.Success()) {
1372 if (!content_stream.GetString().empty()) {
1373 // Add newline.
1374 content_stream.PutChar('\n');
1375 content_stream.Flush();
Todd Fiala75930012016-08-19 04:21:48 +00001376
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377 // Print it.
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001378 output_stream_sp->PutCString(content_stream.GetString());
Todd Fiala75930012016-08-19 04:21:48 +00001379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 } else {
1381 error_stream_sp->Printf("Failed to print structured "
1382 "data with plugin %s: %s",
1383 plugin_sp->GetPluginName().AsCString(),
1384 error.AsCString());
1385 }
Todd Fiala75930012016-08-19 04:21:48 +00001386 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 }
Greg Claytonb4874f12014-02-28 18:22:24 +00001388 }
Greg Clayton44d93782014-01-27 23:43:24 +00001389
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 // Now display any stopped state changes after any STDIO
1391 if (got_state_changed && state_is_stopped) {
1392 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1393 pop_process_io_handler);
Greg Clayton44d93782014-01-27 23:43:24 +00001394 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395
1396 output_stream_sp->Flush();
1397 error_stream_sp->Flush();
1398
1399 if (pop_process_io_handler)
1400 process_sp->PopProcessIOHandler();
1401 }
Greg Clayton44d93782014-01-27 23:43:24 +00001402}
1403
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404void Debugger::HandleThreadEvent(const EventSP &event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001405 // At present the only thread event we handle is the Frame Changed event, and
1406 // all we do for that is just reprint the thread status for that thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407 using namespace lldb;
1408 const uint32_t event_type = event_sp->GetType();
Jim Ingham6a9767c2016-11-08 20:36:40 +00001409 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 if (event_type == Thread::eBroadcastBitStackChanged ||
1411 event_type == Thread::eBroadcastBitThreadSelected) {
1412 ThreadSP thread_sp(
1413 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1414 if (thread_sp) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001415 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 }
1417 }
Greg Clayton44d93782014-01-27 23:43:24 +00001418}
1419
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1421
1422void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1423 m_forward_listener_sp = listener_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001424}
1425
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1427 m_forward_listener_sp.reset();
Greg Clayton44d93782014-01-27 23:43:24 +00001428}
1429
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430void Debugger::DefaultEventHandler() {
1431 ListenerSP listener_sp(GetListener());
1432 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1433 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1434 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1435 BroadcastEventSpec target_event_spec(broadcaster_class_target,
1436 Target::eBroadcastBitBreakpointChanged);
Greg Clayton44d93782014-01-27 23:43:24 +00001437
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 BroadcastEventSpec process_event_spec(
1439 broadcaster_class_process,
1440 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1441 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
Greg Clayton44d93782014-01-27 23:43:24 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1444 Thread::eBroadcastBitStackChanged |
1445 Thread::eBroadcastBitThreadSelected);
Greg Clayton44d93782014-01-27 23:43:24 +00001446
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1448 target_event_spec);
1449 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1450 process_event_spec);
1451 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1452 thread_event_spec);
1453 listener_sp->StartListeningForEvents(
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001454 m_command_interpreter_up.get(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1456 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1457 CommandInterpreter::eBroadcastBitAsynchronousErrorData);
Greg Claytonafa91e332014-12-01 22:41:27 +00001458
Adrian Prantl05097242018-04-30 16:49:04 +00001459 // Let the thread that spawned us know that we have started up and that we
1460 // are now listening to all required events so no events get missed
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001462
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 bool done = false;
1464 while (!done) {
1465 EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001466 if (listener_sp->GetEvent(event_sp, llvm::None)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 if (event_sp) {
1468 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1469 if (broadcaster) {
1470 uint32_t event_type = event_sp->GetType();
1471 ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1472 if (broadcaster_class == broadcaster_class_process) {
1473 HandleProcessEvent(event_sp);
1474 } else if (broadcaster_class == broadcaster_class_target) {
1475 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1476 event_sp.get())) {
1477 HandleBreakpointEvent(event_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00001478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 } else if (broadcaster_class == broadcaster_class_thread) {
1480 HandleThreadEvent(event_sp);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001481 } else if (broadcaster == m_command_interpreter_up.get()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001482 if (event_type &
1483 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1484 done = true;
1485 } else if (event_type &
1486 CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1487 const char *data = reinterpret_cast<const char *>(
1488 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1489 if (data && data[0]) {
1490 StreamSP error_sp(GetAsyncErrorStream());
1491 if (error_sp) {
1492 error_sp->PutCString(data);
1493 error_sp->Flush();
1494 }
1495 }
1496 } else if (event_type & CommandInterpreter::
1497 eBroadcastBitAsynchronousOutputData) {
1498 const char *data = reinterpret_cast<const char *>(
1499 EventDataBytes::GetBytesFromEvent(event_sp.get()));
1500 if (data && data[0]) {
1501 StreamSP output_sp(GetAsyncOutputStream());
1502 if (output_sp) {
1503 output_sp->PutCString(data);
1504 output_sp->Flush();
1505 }
1506 }
1507 }
1508 }
Greg Clayton44d93782014-01-27 23:43:24 +00001509 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510
1511 if (m_forward_listener_sp)
1512 m_forward_listener_sp->AddEvent(event_sp);
1513 }
Greg Clayton44d93782014-01-27 23:43:24 +00001514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 }
Greg Clayton44d93782014-01-27 23:43:24 +00001516}
1517
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1519 ((Debugger *)arg)->DefaultEventHandler();
Konrad Kleine85200642019-05-23 15:17:39 +00001520 return {};
Greg Clayton44d93782014-01-27 23:43:24 +00001521}
1522
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523bool Debugger::StartEventHandlerThread() {
1524 if (!m_event_handler_thread.IsJoinable()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001525 // We must synchronize with the DefaultEventHandler() thread to ensure it
1526 // is up and running and listening to events before we return from this
1527 // function. We do this by listening to events for the
Kate Stoneb9c1b512016-09-06 20:57:50 +00001528 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001529 ConstString full_name("lldb.debugger.event-handler");
1530 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1532 eBroadcastBitEventThreadIsListening);
Greg Claytonafa91e332014-12-01 22:41:27 +00001533
Tatyana Krasnukha1a728f62018-07-13 11:21:06 +00001534 auto thread_name =
1535 full_name.GetLength() < llvm::get_max_thread_name_length() ?
1536 full_name.AsCString() : "dbg.evt-handler";
1537
Kate Stoneb9c1b512016-09-06 20:57:50 +00001538 // Use larger 8MB stack for this thread
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001539 llvm::Expected<HostThread> event_handler_thread =
1540 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1541 g_debugger_event_thread_stack_bytes);
1542
1543 if (event_handler_thread) {
1544 m_event_handler_thread = *event_handler_thread;
1545 } else {
1546 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1547 "failed to launch host thread: {}",
1548 llvm::toString(event_handler_thread.takeError()));
1549 }
Greg Claytonafa91e332014-12-01 22:41:27 +00001550
Adrian Prantl05097242018-04-30 16:49:04 +00001551 // Make sure DefaultEventHandler() is running and listening to events
1552 // before we return from this function. We are only listening for events of
1553 // type eBroadcastBitEventThreadIsListening so we don't need to check the
1554 // event, we just need to wait an infinite amount of time for it (nullptr
1555 // timeout as the first parameter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00001557 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558 }
1559 return m_event_handler_thread.IsJoinable();
1560}
1561
1562void Debugger::StopEventHandlerThread() {
1563 if (m_event_handler_thread.IsJoinable()) {
1564 GetCommandInterpreter().BroadcastEvent(
1565 CommandInterpreter::eBroadcastBitQuitCommandReceived);
1566 m_event_handler_thread.Join(nullptr);
1567 }
1568}
1569
1570lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1571 Debugger *debugger = (Debugger *)arg;
1572 debugger->ExecuteIOHandlers();
1573 debugger->StopEventHandlerThread();
Konrad Kleine85200642019-05-23 15:17:39 +00001574 return {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00001575}
1576
1577bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1578
1579bool Debugger::StartIOHandlerThread() {
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001580 if (!m_io_handler_thread.IsJoinable()) {
1581 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1582 "lldb.debugger.io-handler", IOHandlerThread, this,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 8 * 1024 * 1024); // Use larger 8MB stack for this thread
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00001584 if (io_handler_thread) {
1585 m_io_handler_thread = *io_handler_thread;
1586 } else {
1587 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1588 "failed to launch host thread: {}",
1589 llvm::toString(io_handler_thread.takeError()));
1590 }
1591 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592 return m_io_handler_thread.IsJoinable();
1593}
1594
1595void Debugger::StopIOHandlerThread() {
1596 if (m_io_handler_thread.IsJoinable()) {
1597 if (m_input_file_sp)
1598 m_input_file_sp->GetFile().Close();
1599 m_io_handler_thread.Join(nullptr);
1600 }
1601}
1602
1603void Debugger::JoinIOHandlerThread() {
1604 if (HasIOHandlerThread()) {
1605 thread_result_t result;
1606 m_io_handler_thread.Join(&result);
1607 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1608 }
1609}
1610
1611Target *Debugger::GetDummyTarget() {
1612 return m_target_list.GetDummyTarget(*this).get();
1613}
1614
1615Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1616 Target *target = nullptr;
1617 if (!prefer_dummy) {
1618 target = m_target_list.GetSelectedTarget().get();
1619 if (target)
1620 return target;
1621 }
1622
1623 return GetDummyTarget();
1624}
1625
Zachary Turner97206d52017-05-12 04:51:55 +00001626Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1627 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001628 FileSpec repl_executable;
1629
1630 if (language == eLanguageTypeUnknown) {
1631 std::set<LanguageType> repl_languages;
1632
1633 Language::GetLanguagesSupportingREPLs(repl_languages);
1634
1635 if (repl_languages.size() == 1) {
1636 language = *repl_languages.begin();
1637 } else if (repl_languages.empty()) {
1638 err.SetErrorStringWithFormat(
1639 "LLDB isn't configured with REPL support for any languages.");
1640 return err;
1641 } else {
1642 err.SetErrorStringWithFormat(
1643 "Multiple possible REPL languages. Please specify a language.");
1644 return err;
Greg Clayton807b6b32014-10-15 18:03:59 +00001645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 }
Greg Clayton44d93782014-01-27 23:43:24 +00001647
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 Target *const target =
1649 nullptr; // passing in an empty target means the REPL must create one
Greg Clayton44d93782014-01-27 23:43:24 +00001650
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
Greg Clayton44d93782014-01-27 23:43:24 +00001652
Kate Stoneb9c1b512016-09-06 20:57:50 +00001653 if (!err.Success()) {
Sean Callanan3e7e9152015-10-20 00:23:46 +00001654 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 }
1656
1657 if (!repl_sp) {
1658 err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1659 Language::GetNameForLanguageType(language));
1660 return err;
1661 }
1662
1663 repl_sp->SetCompilerOptions(repl_options);
1664 repl_sp->RunLoop();
1665
1666 return err;
Sean Callanan3e7e9152015-10-20 00:23:46 +00001667}