blob: 69fae11dfbd523b19ca03eb006a52c046f286ba5 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Clayton4a33d312011-06-23 17:59:56 +000012#include "lldb/Core/Debugger.h"
13
14#include <map>
15
Enrico Granata4becb372011-06-29 22:27:15 +000016#include "clang/AST/DeclCXX.h"
17#include "clang/AST/Type.h"
Jason Molenda705b1802014-06-13 02:37:02 +000018#include "llvm/ADT/StringRef.h"
Enrico Granata4becb372011-06-29 22:27:15 +000019
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/lldb-private.h"
21#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton1f746072012-08-29 21:13:06 +000022#include "lldb/Core/Module.h"
Greg Claytone8cd0c92012-10-19 18:02:49 +000023#include "lldb/Core/PluginManager.h"
Greg Clayton7349bd92011-05-09 20:18:18 +000024#include "lldb/Core/RegisterValue.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Core/State.h"
Jim Ingham5b52f0c2011-06-02 23:58:26 +000026#include "lldb/Core/StreamAsynchronousIO.h"
Jim Ingham228063c2012-02-21 02:23:08 +000027#include "lldb/Core/StreamCallback.h"
Greg Clayton44d93782014-01-27 23:43:24 +000028#include "lldb/Core/StreamFile.h"
Greg Clayton1b654882010-09-19 02:33:57 +000029#include "lldb/Core/StreamString.h"
Jason Molenda705b1802014-06-13 02:37:02 +000030#include "lldb/Core/StructuredData.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Core/Timer.h"
Enrico Granata4becb372011-06-29 22:27:15 +000032#include "lldb/Core/ValueObject.h"
Greg Clayton6d3dbf52012-01-13 08:39:16 +000033#include "lldb/Core/ValueObjectVariable.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000034#include "lldb/DataFormatters/DataVisualization.h"
35#include "lldb/DataFormatters/FormatManager.h"
Enrico Granata894f7352014-03-25 22:03:52 +000036#include "lldb/DataFormatters/TypeSummary.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000037#include "lldb/Host/HostInfo.h"
Greg Claytona3406612011-02-07 23:24:47 +000038#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000039#include "lldb/Host/ThreadLauncher.h"
Greg Clayton66111032010-06-23 01:19:29 +000040#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000041#include "lldb/Interpreter/OptionValueSInt64.h"
42#include "lldb/Interpreter/OptionValueString.h"
Greg Clayton1f746072012-08-29 21:13:06 +000043#include "lldb/Symbol/ClangASTContext.h"
44#include "lldb/Symbol/CompileUnit.h"
45#include "lldb/Symbol/Function.h"
46#include "lldb/Symbol/Symbol.h"
Greg Clayton6d3dbf52012-01-13 08:39:16 +000047#include "lldb/Symbol/VariableList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Target/TargetList.h"
49#include "lldb/Target/Process.h"
Greg Clayton1b654882010-09-19 02:33:57 +000050#include "lldb/Target/RegisterContext.h"
Greg Clayton5fb8f792013-12-02 19:35:49 +000051#include "lldb/Target/SectionLoadList.h"
Greg Clayton1b654882010-09-19 02:33:57 +000052#include "lldb/Target/StopInfo.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000053#include "lldb/Target/Target.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054#include "lldb/Target/Thread.h"
Greg Clayton5a314712011-10-14 07:41:33 +000055#include "lldb/Utility/AnsiTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056
Zachary Turner58a559c2014-08-27 20:15:09 +000057#include "llvm/Support/DynamicLibrary.h"
58
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059using namespace lldb;
60using namespace lldb_private;
61
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062
Greg Clayton1b654882010-09-19 02:33:57 +000063static uint32_t g_shared_debugger_refcount = 0;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000064static lldb::user_id_t g_unique_id = 1;
65
Greg Clayton1b654882010-09-19 02:33:57 +000066#pragma mark Static Functions
67
68static Mutex &
69GetDebuggerListMutex ()
70{
71 static Mutex g_mutex(Mutex::eMutexTypeRecursive);
72 return g_mutex;
73}
74
75typedef std::vector<DebuggerSP> DebuggerList;
76
77static DebuggerList &
78GetDebuggerList()
79{
80 // hide the static debugger list inside a singleton accessor to avoid
Bruce Mitchener6a7f3332014-06-27 02:42:12 +000081 // global init constructors
Greg Clayton1b654882010-09-19 02:33:57 +000082 static DebuggerList g_list;
83 return g_list;
84}
Greg Claytone372b982011-11-21 21:44:34 +000085
86OptionEnumValueElement
Greg Clayton67cc0632012-08-22 17:17:09 +000087g_show_disassembly_enum_values[] =
Greg Claytone372b982011-11-21 21:44:34 +000088{
Greg Clayton67cc0632012-08-22 17:17:09 +000089 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."},
90 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
91 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."},
Greg Claytone372b982011-11-21 21:44:34 +000092 { 0, NULL, NULL }
93};
94
Greg Clayton67cc0632012-08-22 17:17:09 +000095OptionEnumValueElement
96g_language_enumerators[] =
97{
98 { eScriptLanguageNone, "none", "Disable scripting languages."},
99 { eScriptLanguagePython, "python", "Select python as the default scripting language."},
100 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."},
Greg Claytona12993c2012-09-13 23:03:20 +0000101 { 0, NULL, NULL }
Greg Clayton67cc0632012-08-22 17:17:09 +0000102};
Greg Claytone372b982011-11-21 21:44:34 +0000103
Greg Clayton67cc0632012-08-22 17:17:09 +0000104#define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
105#define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
106
Michael Sartain0769b2b2013-07-30 16:44:36 +0000107#define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
Greg Clayton67cc0632012-08-22 17:17:09 +0000108 "{, ${frame.pc}}"\
109 MODULE_WITH_FUNC\
110 FILE_AND_LINE\
Michael Sartain0769b2b2013-07-30 16:44:36 +0000111 "{, name = '${thread.name}'}"\
112 "{, queue = '${thread.queue}'}"\
Jason Molenda705b1802014-06-13 02:37:02 +0000113 "{, activity = '${thread.info.activity.name}'}" \
114 "{, ${thread.info.trace_messages} messages}" \
Greg Clayton67cc0632012-08-22 17:17:09 +0000115 "{, stop reason = ${thread.stop-reason}}"\
116 "{\\nReturn value: ${thread.return-value}}"\
Jim Ingham30fadaf2014-07-08 01:07:32 +0000117 "{\\nCompleted expression: ${thread.completed-expression}}"\
Greg Clayton67cc0632012-08-22 17:17:09 +0000118 "\\n"
119
120#define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
121 MODULE_WITH_FUNC\
122 FILE_AND_LINE\
123 "\\n"
124
125
126
Greg Clayton754a9362012-08-23 00:22:02 +0000127static PropertyDefinition
128g_properties[] =
Greg Clayton67cc0632012-08-22 17:17:09 +0000129{
130{ "auto-confirm", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
131{ "frame-format", OptionValue::eTypeString , true, 0 , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
132{ "notify-void", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
Greg Clayton4c054102012-09-01 00:38:36 +0000133{ "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000134{ "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
135{ "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
136{ "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
137{ "stop-line-count-after", OptionValue::eTypeSInt64 , true, 3 , NULL, NULL, "The number of sources lines to display that come after the current source line when displaying a stopped context." },
138{ "stop-line-count-before", OptionValue::eTypeSInt64 , true, 3 , NULL, NULL, "The number of sources lines to display that come before the current source line when displaying a stopped context." },
139{ "term-width", OptionValue::eTypeSInt64 , true, 80 , NULL, NULL, "The maximum number of columns to use for displaying text." },
140{ "thread-format", OptionValue::eTypeString , true, 0 , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
141{ "use-external-editor", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Whether to use an external editor or not." },
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000142{ "use-color", OptionValue::eTypeBoolean, true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
Enrico Granata90a8db32013-10-31 21:01:07 +0000143{ "auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
Greg Claytone8cd0c92012-10-19 18:02:49 +0000144
145 { NULL, OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
Greg Clayton67cc0632012-08-22 17:17:09 +0000146};
147
148enum
149{
150 ePropertyAutoConfirm = 0,
151 ePropertyFrameFormat,
152 ePropertyNotiftVoid,
153 ePropertyPrompt,
154 ePropertyScriptLanguage,
155 ePropertyStopDisassemblyCount,
156 ePropertyStopDisassemblyDisplay,
157 ePropertyStopLineCountAfter,
158 ePropertyStopLineCountBefore,
159 ePropertyTerminalWidth,
160 ePropertyThreadFormat,
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000161 ePropertyUseExternalEditor,
162 ePropertyUseColor,
Enrico Granata90a8db32013-10-31 21:01:07 +0000163 ePropertyAutoOneLineSummaries
Greg Clayton67cc0632012-08-22 17:17:09 +0000164};
165
Greg Clayton5fb8f792013-12-02 19:35:49 +0000166Debugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
Greg Clayton4c054102012-09-01 00:38:36 +0000167
168Error
169Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
170 VarSetOperationType op,
171 const char *property_path,
172 const char *value)
173{
Enrico Granata84a53df2013-05-20 22:29:23 +0000174 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
175 TargetSP target_sp;
Enrico Granata397ddd52013-05-21 20:13:34 +0000176 LoadScriptFromSymFile load_script_old_value;
Enrico Granata84a53df2013-05-20 22:29:23 +0000177 if (is_load_script && exe_ctx->GetTargetSP())
178 {
179 target_sp = exe_ctx->GetTargetSP();
180 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
181 }
Greg Clayton4c054102012-09-01 00:38:36 +0000182 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
183 if (error.Success())
184 {
Enrico Granata84a53df2013-05-20 22:29:23 +0000185 // FIXME it would be nice to have "on-change" callbacks for properties
Greg Clayton4c054102012-09-01 00:38:36 +0000186 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
187 {
188 const char *new_prompt = GetPrompt();
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000189 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
190 if (str.length())
191 new_prompt = str.c_str();
Greg Clayton44d93782014-01-27 23:43:24 +0000192 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton4c054102012-09-01 00:38:36 +0000193 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
194 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
195 }
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000196 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
197 {
198 // use-color changed. Ping the prompt so it can reset the ansi terminal codes.
199 SetPrompt (GetPrompt());
200 }
Enrico Granata397ddd52013-05-21 20:13:34 +0000201 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
Enrico Granata84a53df2013-05-20 22:29:23 +0000202 {
Enrico Granata397ddd52013-05-21 20:13:34 +0000203 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
Enrico Granata84a53df2013-05-20 22:29:23 +0000204 {
205 std::list<Error> errors;
Enrico Granata97303392013-05-21 00:00:30 +0000206 StreamString feedback_stream;
207 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
Enrico Granata84a53df2013-05-20 22:29:23 +0000208 {
Greg Clayton44d93782014-01-27 23:43:24 +0000209 StreamFileSP stream_sp (GetErrorFile());
210 if (stream_sp)
Enrico Granata84a53df2013-05-20 22:29:23 +0000211 {
Greg Clayton44d93782014-01-27 23:43:24 +0000212 for (auto error : errors)
213 {
214 stream_sp->Printf("%s\n",error.AsCString());
215 }
216 if (feedback_stream.GetSize())
217 stream_sp->Printf("%s",feedback_stream.GetData());
Enrico Granata84a53df2013-05-20 22:29:23 +0000218 }
219 }
220 }
221 }
Greg Clayton4c054102012-09-01 00:38:36 +0000222 }
223 return error;
224}
225
Greg Clayton67cc0632012-08-22 17:17:09 +0000226bool
227Debugger::GetAutoConfirm () const
228{
229 const uint32_t idx = ePropertyAutoConfirm;
Greg Clayton754a9362012-08-23 00:22:02 +0000230 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000231}
232
233const char *
234Debugger::GetFrameFormat() const
235{
236 const uint32_t idx = ePropertyFrameFormat;
Greg Clayton754a9362012-08-23 00:22:02 +0000237 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000238}
239
240bool
241Debugger::GetNotifyVoid () const
242{
243 const uint32_t idx = ePropertyNotiftVoid;
Greg Clayton754a9362012-08-23 00:22:02 +0000244 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000245}
246
247const char *
248Debugger::GetPrompt() const
249{
250 const uint32_t idx = ePropertyPrompt;
Greg Clayton754a9362012-08-23 00:22:02 +0000251 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000252}
253
254void
255Debugger::SetPrompt(const char *p)
256{
257 const uint32_t idx = ePropertyPrompt;
258 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
259 const char *new_prompt = GetPrompt();
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000260 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
261 if (str.length())
262 new_prompt = str.c_str();
Greg Clayton44d93782014-01-27 23:43:24 +0000263 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000264}
265
266const char *
267Debugger::GetThreadFormat() const
268{
269 const uint32_t idx = ePropertyThreadFormat;
Greg Clayton754a9362012-08-23 00:22:02 +0000270 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000271}
272
273lldb::ScriptLanguage
274Debugger::GetScriptLanguage() const
275{
276 const uint32_t idx = ePropertyScriptLanguage;
Greg Clayton754a9362012-08-23 00:22:02 +0000277 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000278}
279
280bool
281Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
282{
283 const uint32_t idx = ePropertyScriptLanguage;
284 return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
285}
286
287uint32_t
288Debugger::GetTerminalWidth () const
289{
290 const uint32_t idx = ePropertyTerminalWidth;
Greg Clayton754a9362012-08-23 00:22:02 +0000291 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000292}
293
294bool
295Debugger::SetTerminalWidth (uint32_t term_width)
296{
297 const uint32_t idx = ePropertyTerminalWidth;
298 return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
299}
300
301bool
302Debugger::GetUseExternalEditor () const
303{
304 const uint32_t idx = ePropertyUseExternalEditor;
Greg Clayton754a9362012-08-23 00:22:02 +0000305 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000306}
307
308bool
309Debugger::SetUseExternalEditor (bool b)
310{
311 const uint32_t idx = ePropertyUseExternalEditor;
312 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
313}
314
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000315bool
316Debugger::GetUseColor () const
317{
318 const uint32_t idx = ePropertyUseColor;
319 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
320}
321
322bool
323Debugger::SetUseColor (bool b)
324{
325 const uint32_t idx = ePropertyUseColor;
326 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
327 SetPrompt (GetPrompt());
328 return ret;
329}
330
Greg Clayton67cc0632012-08-22 17:17:09 +0000331uint32_t
332Debugger::GetStopSourceLineCount (bool before) const
333{
334 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
Greg Clayton754a9362012-08-23 00:22:02 +0000335 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000336}
337
338Debugger::StopDisassemblyType
339Debugger::GetStopDisassemblyDisplay () const
340{
341 const uint32_t idx = ePropertyStopDisassemblyDisplay;
Greg Clayton754a9362012-08-23 00:22:02 +0000342 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000343}
344
345uint32_t
346Debugger::GetDisassemblyLineCount () const
347{
348 const uint32_t idx = ePropertyStopDisassemblyCount;
Greg Clayton754a9362012-08-23 00:22:02 +0000349 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000350}
Greg Claytone372b982011-11-21 21:44:34 +0000351
Enrico Granata553fad52013-10-25 23:09:40 +0000352bool
Enrico Granata90a8db32013-10-31 21:01:07 +0000353Debugger::GetAutoOneLineSummaries () const
Enrico Granata553fad52013-10-25 23:09:40 +0000354{
Enrico Granata90a8db32013-10-31 21:01:07 +0000355 const uint32_t idx = ePropertyAutoOneLineSummaries;
Enrico Granata553fad52013-10-25 23:09:40 +0000356 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
357
358}
359
Greg Clayton1b654882010-09-19 02:33:57 +0000360#pragma mark Debugger
361
Greg Clayton67cc0632012-08-22 17:17:09 +0000362//const DebuggerPropertiesSP &
363//Debugger::GetSettings() const
364//{
365// return m_properties_sp;
366//}
367//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000368
Caroline Tice2f88aad2011-01-14 00:29:16 +0000369int
370Debugger::TestDebuggerRefCount ()
371{
372 return g_shared_debugger_refcount;
373}
374
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000375void
Greg Clayton5fb8f792013-12-02 19:35:49 +0000376Debugger::Initialize (LoadPluginCallbackType load_plugin_callback)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377{
Greg Clayton5fb8f792013-12-02 19:35:49 +0000378 g_load_plugin_callback = load_plugin_callback;
Greg Claytonc15f55e2012-03-30 20:53:46 +0000379 if (g_shared_debugger_refcount++ == 0)
Greg Claytondbe54502010-11-19 03:46:01 +0000380 lldb_private::Initialize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000381}
382
383void
384Debugger::Terminate ()
385{
Greg Clayton66111032010-06-23 01:19:29 +0000386 if (g_shared_debugger_refcount > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387 {
Greg Clayton66111032010-06-23 01:19:29 +0000388 g_shared_debugger_refcount--;
389 if (g_shared_debugger_refcount == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390 {
Greg Claytondbe54502010-11-19 03:46:01 +0000391 lldb_private::WillTerminate();
392 lldb_private::Terminate();
Caroline Tice6760a512011-01-17 21:55:19 +0000393
394 // Clear our master list of debugger objects
395 Mutex::Locker locker (GetDebuggerListMutex ());
396 GetDebuggerList().clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000398 }
399}
400
Caroline Tice20bd37f2011-03-10 22:14:10 +0000401void
402Debugger::SettingsInitialize ()
403{
Greg Clayton6920b522012-08-22 18:39:03 +0000404 Target::SettingsInitialize ();
Caroline Tice20bd37f2011-03-10 22:14:10 +0000405}
406
407void
408Debugger::SettingsTerminate ()
409{
Greg Clayton6920b522012-08-22 18:39:03 +0000410 Target::SettingsTerminate ();
Caroline Tice20bd37f2011-03-10 22:14:10 +0000411}
412
Enrico Granata21dfcd92012-09-28 23:57:51 +0000413bool
Enrico Granatae743c782013-04-24 21:29:08 +0000414Debugger::LoadPlugin (const FileSpec& spec, Error& error)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000415{
Greg Clayton5fb8f792013-12-02 19:35:49 +0000416 if (g_load_plugin_callback)
Enrico Granatae743c782013-04-24 21:29:08 +0000417 {
Zachary Turner58a559c2014-08-27 20:15:09 +0000418 llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
419 if (dynlib.isValid())
Greg Clayton5fb8f792013-12-02 19:35:49 +0000420 {
Zachary Turner58a559c2014-08-27 20:15:09 +0000421 m_loaded_plugins.push_back(dynlib);
Greg Clayton5fb8f792013-12-02 19:35:49 +0000422 return true;
423 }
Enrico Granatae743c782013-04-24 21:29:08 +0000424 }
Greg Clayton5fb8f792013-12-02 19:35:49 +0000425 else
Enrico Granatae743c782013-04-24 21:29:08 +0000426 {
Greg Clayton5fb8f792013-12-02 19:35:49 +0000427 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
428 // and if the public API layer isn't available (code is linking against
429 // all of the internal LLDB static libraries), then we can't load plugins
430 error.SetErrorString("Public API layer is not available");
Enrico Granatae743c782013-04-24 21:29:08 +0000431 }
Enrico Granata21dfcd92012-09-28 23:57:51 +0000432 return false;
433}
434
435static FileSpec::EnumerateDirectoryResult
436LoadPluginCallback
437(
438 void *baton,
439 FileSpec::FileType file_type,
440 const FileSpec &file_spec
441 )
442{
443 Error error;
444
445 static ConstString g_dylibext("dylib");
Michael Sartain3cf443d2013-07-17 00:26:30 +0000446 static ConstString g_solibext("so");
Enrico Granata21dfcd92012-09-28 23:57:51 +0000447
448 if (!baton)
449 return FileSpec::eEnumerateDirectoryResultQuit;
450
451 Debugger *debugger = (Debugger*)baton;
452
453 // If we have a regular file, a symbolic link or unknown file type, try
454 // and process the file. We must handle unknown as sometimes the directory
455 // enumeration might be enumerating a file system that doesn't have correct
456 // file type information.
457 if (file_type == FileSpec::eFileTypeRegular ||
458 file_type == FileSpec::eFileTypeSymbolicLink ||
459 file_type == FileSpec::eFileTypeUnknown )
460 {
461 FileSpec plugin_file_spec (file_spec);
462 plugin_file_spec.ResolvePath ();
463
Michael Sartain3cf443d2013-07-17 00:26:30 +0000464 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
465 plugin_file_spec.GetFileNameExtension() != g_solibext)
466 {
Enrico Granata21dfcd92012-09-28 23:57:51 +0000467 return FileSpec::eEnumerateDirectoryResultNext;
Michael Sartain3cf443d2013-07-17 00:26:30 +0000468 }
Enrico Granata21dfcd92012-09-28 23:57:51 +0000469
Enrico Granatae743c782013-04-24 21:29:08 +0000470 Error plugin_load_error;
471 debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000472
473 return FileSpec::eEnumerateDirectoryResultNext;
474 }
475
476 else if (file_type == FileSpec::eFileTypeUnknown ||
477 file_type == FileSpec::eFileTypeDirectory ||
478 file_type == FileSpec::eFileTypeSymbolicLink )
479 {
480 // Try and recurse into anything that a directory or symbolic link.
481 // We must also do this for unknown as sometimes the directory enumeration
Bruce Mitchener6a7f3332014-06-27 02:42:12 +0000482 // might be enumerating a file system that doesn't have correct file type
Enrico Granata21dfcd92012-09-28 23:57:51 +0000483 // information.
484 return FileSpec::eEnumerateDirectoryResultEnter;
485 }
486
487 return FileSpec::eEnumerateDirectoryResultNext;
488}
489
490void
491Debugger::InstanceInitialize ()
492{
493 FileSpec dir_spec;
494 const bool find_directories = true;
495 const bool find_files = true;
496 const bool find_other = true;
497 char dir_path[PATH_MAX];
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000498 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000499 {
500 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
501 {
502 FileSpec::EnumerateDirectory (dir_path,
503 find_directories,
504 find_files,
505 find_other,
506 LoadPluginCallback,
507 this);
508 }
509 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000510
511 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000512 {
513 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
514 {
515 FileSpec::EnumerateDirectory (dir_path,
516 find_directories,
517 find_files,
518 find_other,
519 LoadPluginCallback,
520 this);
521 }
522 }
Greg Claytone8cd0c92012-10-19 18:02:49 +0000523
524 PluginManager::DebuggerInitialize (*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000525}
526
Greg Clayton66111032010-06-23 01:19:29 +0000527DebuggerSP
Jim Ingham228063c2012-02-21 02:23:08 +0000528Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
Greg Clayton66111032010-06-23 01:19:29 +0000529{
Jim Ingham228063c2012-02-21 02:23:08 +0000530 DebuggerSP debugger_sp (new Debugger(log_callback, baton));
Greg Claytonc15f55e2012-03-30 20:53:46 +0000531 if (g_shared_debugger_refcount > 0)
Greg Clayton66111032010-06-23 01:19:29 +0000532 {
533 Mutex::Locker locker (GetDebuggerListMutex ());
534 GetDebuggerList().push_back(debugger_sp);
535 }
Enrico Granata21dfcd92012-09-28 23:57:51 +0000536 debugger_sp->InstanceInitialize ();
Greg Clayton66111032010-06-23 01:19:29 +0000537 return debugger_sp;
538}
539
Caroline Ticee02657b2011-01-22 01:02:07 +0000540void
Greg Clayton4d122c42011-09-17 08:33:22 +0000541Debugger::Destroy (DebuggerSP &debugger_sp)
Caroline Ticee02657b2011-01-22 01:02:07 +0000542{
543 if (debugger_sp.get() == NULL)
544 return;
545
Jim Ingham8314c522011-09-15 21:36:42 +0000546 debugger_sp->Clear();
547
Greg Claytonc15f55e2012-03-30 20:53:46 +0000548 if (g_shared_debugger_refcount > 0)
Caroline Ticee02657b2011-01-22 01:02:07 +0000549 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000550 Mutex::Locker locker (GetDebuggerListMutex ());
551 DebuggerList &debugger_list = GetDebuggerList ();
552 DebuggerList::iterator pos, end = debugger_list.end();
553 for (pos = debugger_list.begin (); pos != end; ++pos)
Caroline Ticee02657b2011-01-22 01:02:07 +0000554 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000555 if ((*pos).get() == debugger_sp.get())
556 {
557 debugger_list.erase (pos);
558 return;
559 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000560 }
561 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000562}
563
Greg Clayton4d122c42011-09-17 08:33:22 +0000564DebuggerSP
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000565Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
566{
Greg Clayton4d122c42011-09-17 08:33:22 +0000567 DebuggerSP debugger_sp;
Greg Clayton6920b522012-08-22 18:39:03 +0000568 if (g_shared_debugger_refcount > 0)
569 {
570 Mutex::Locker locker (GetDebuggerListMutex ());
571 DebuggerList &debugger_list = GetDebuggerList();
572 DebuggerList::iterator pos, end = debugger_list.end();
573
574 for (pos = debugger_list.begin(); pos != end; ++pos)
575 {
576 if ((*pos).get()->m_instance_name == instance_name)
577 {
578 debugger_sp = *pos;
579 break;
580 }
581 }
582 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000583 return debugger_sp;
584}
Greg Clayton66111032010-06-23 01:19:29 +0000585
586TargetSP
587Debugger::FindTargetWithProcessID (lldb::pid_t pid)
588{
Greg Clayton4d122c42011-09-17 08:33:22 +0000589 TargetSP target_sp;
Greg Claytonc15f55e2012-03-30 20:53:46 +0000590 if (g_shared_debugger_refcount > 0)
Greg Clayton66111032010-06-23 01:19:29 +0000591 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000592 Mutex::Locker locker (GetDebuggerListMutex ());
593 DebuggerList &debugger_list = GetDebuggerList();
594 DebuggerList::iterator pos, end = debugger_list.end();
595 for (pos = debugger_list.begin(); pos != end; ++pos)
596 {
597 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
598 if (target_sp)
599 break;
600 }
Greg Clayton66111032010-06-23 01:19:29 +0000601 }
602 return target_sp;
603}
604
Greg Claytone4e45922011-11-16 05:37:56 +0000605TargetSP
606Debugger::FindTargetWithProcess (Process *process)
607{
608 TargetSP target_sp;
Greg Claytonc15f55e2012-03-30 20:53:46 +0000609 if (g_shared_debugger_refcount > 0)
Greg Claytone4e45922011-11-16 05:37:56 +0000610 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000611 Mutex::Locker locker (GetDebuggerListMutex ());
612 DebuggerList &debugger_list = GetDebuggerList();
613 DebuggerList::iterator pos, end = debugger_list.end();
614 for (pos = debugger_list.begin(); pos != end; ++pos)
615 {
616 target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
617 if (target_sp)
618 break;
619 }
Greg Claytone4e45922011-11-16 05:37:56 +0000620 }
621 return target_sp;
622}
623
Jason Molendae6481c72014-09-12 01:50:46 +0000624Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) :
625 UserID(g_unique_id++),
626 Properties(OptionValuePropertiesSP(new OptionValueProperties())),
627 m_input_file_sp(new StreamFile(stdin, false)),
628 m_output_file_sp(new StreamFile(stdout, false)),
629 m_error_file_sp(new StreamFile(stderr, false)),
630 m_terminal_state(),
631 m_target_list(*this),
632 m_platform_list(),
633 m_listener("lldb.Debugger"),
634 m_source_manager_ap(),
635 m_source_file_cache(),
636 m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)),
637 m_input_reader_stack(),
638 m_instance_name(),
639 m_loaded_plugins()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640{
Greg Clayton67cc0632012-08-22 17:17:09 +0000641 char instance_cstr[256];
642 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
643 m_instance_name.SetCString(instance_cstr);
Jim Ingham228063c2012-02-21 02:23:08 +0000644 if (log_callback)
645 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
Greg Clayton66111032010-06-23 01:19:29 +0000646 m_command_interpreter_ap->Initialize ();
Greg Claytonded470d2011-03-19 01:12:21 +0000647 // Always add our default platform to the platform list
Greg Clayton615eb7e2014-09-19 20:11:50 +0000648 PlatformSP default_platform_sp (Platform::GetHostPlatform());
Greg Claytonded470d2011-03-19 01:12:21 +0000649 assert (default_platform_sp.get());
650 m_platform_list.Append (default_platform_sp, true);
Greg Clayton67cc0632012-08-22 17:17:09 +0000651
Greg Clayton754a9362012-08-23 00:22:02 +0000652 m_collection_sp->Initialize (g_properties);
Greg Clayton67cc0632012-08-22 17:17:09 +0000653 m_collection_sp->AppendProperty (ConstString("target"),
654 ConstString("Settings specify to debugging targets."),
655 true,
656 Target::GetGlobalProperties()->GetValueProperties());
Greg Clayton754a9362012-08-23 00:22:02 +0000657 if (m_command_interpreter_ap.get())
658 {
659 m_collection_sp->AppendProperty (ConstString("interpreter"),
660 ConstString("Settings specify to the debugger's command interpreter."),
661 true,
662 m_command_interpreter_ap->GetValueProperties());
663 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000664 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
665 term_width->SetMinimumValue(10);
666 term_width->SetMaximumValue(1024);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000667
668 // Turn off use-color if this is a dumb terminal.
669 const char *term = getenv ("TERM");
670 if (term && !strcmp (term, "dumb"))
671 SetUseColor (false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000672}
673
674Debugger::~Debugger ()
675{
Jim Ingham8314c522011-09-15 21:36:42 +0000676 Clear();
677}
678
679void
680Debugger::Clear()
681{
Greg Clayton44d93782014-01-27 23:43:24 +0000682 ClearIOHandlers();
683 StopIOHandlerThread();
684 StopEventHandlerThread();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000685 m_listener.Clear();
Greg Clayton66111032010-06-23 01:19:29 +0000686 int num_targets = m_target_list.GetNumTargets();
687 for (int i = 0; i < num_targets; i++)
688 {
Greg Claytonccbc08e2012-01-14 17:04:19 +0000689 TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
690 if (target_sp)
Jim Ingham8314c522011-09-15 21:36:42 +0000691 {
Greg Claytonccbc08e2012-01-14 17:04:19 +0000692 ProcessSP process_sp (target_sp->GetProcessSP());
693 if (process_sp)
Jim Ingham1fd07052013-02-27 19:13:05 +0000694 process_sp->Finalize();
Greg Claytonccbc08e2012-01-14 17:04:19 +0000695 target_sp->Destroy();
Jim Ingham8314c522011-09-15 21:36:42 +0000696 }
Greg Clayton66111032010-06-23 01:19:29 +0000697 }
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000698 BroadcasterManager::Clear ();
Greg Clayton0d69a3a2012-05-16 00:11:54 +0000699
700 // Close the input file _before_ we close the input read communications class
701 // as it does NOT own the input file, our m_input_file does.
Jim Inghamc5917d92012-11-30 20:23:19 +0000702 m_terminal_state.Clear();
Greg Clayton44d93782014-01-27 23:43:24 +0000703 if (m_input_file_sp)
704 m_input_file_sp->GetFile().Close ();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000705
706 m_command_interpreter_ap->Clear();
Jim Ingham8314c522011-09-15 21:36:42 +0000707}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708
709bool
Greg Claytonfc3f0272011-05-29 04:06:55 +0000710Debugger::GetCloseInputOnEOF () const
711{
Greg Clayton44d93782014-01-27 23:43:24 +0000712// return m_input_comm.GetCloseOnEOF();
713 return false;
Greg Claytonfc3f0272011-05-29 04:06:55 +0000714}
715
716void
717Debugger::SetCloseInputOnEOF (bool b)
718{
Greg Clayton44d93782014-01-27 23:43:24 +0000719// m_input_comm.SetCloseOnEOF(b);
Greg Claytonfc3f0272011-05-29 04:06:55 +0000720}
721
722bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723Debugger::GetAsyncExecution ()
724{
Greg Clayton66111032010-06-23 01:19:29 +0000725 return !m_command_interpreter_ap->GetSynchronous();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726}
727
728void
729Debugger::SetAsyncExecution (bool async_execution)
730{
Greg Clayton66111032010-06-23 01:19:29 +0000731 m_command_interpreter_ap->SetSynchronous (!async_execution);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732}
733
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734
735void
736Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
737{
Greg Clayton44d93782014-01-27 23:43:24 +0000738 if (m_input_file_sp)
739 m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
740 else
741 m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
742
743 File &in_file = m_input_file_sp->GetFile();
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000744 if (in_file.IsValid() == false)
745 in_file.SetStream (stdin, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746
Jim Inghamc5917d92012-11-30 20:23:19 +0000747 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
748 SaveInputTerminalState ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749}
750
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751void
752Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
753{
Greg Clayton44d93782014-01-27 23:43:24 +0000754 if (m_output_file_sp)
755 m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
756 else
757 m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
758
759 File &out_file = m_output_file_sp->GetFile();
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000760 if (out_file.IsValid() == false)
761 out_file.SetStream (stdout, false);
Caroline Tice2f88aad2011-01-14 00:29:16 +0000762
Enrico Granatab5887262012-10-29 21:18:03 +0000763 // do not create the ScriptInterpreter just for setting the output file handle
764 // as the constructor will know how to do the right thing on its own
765 const bool can_create = false;
766 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
767 if (script_interpreter)
768 script_interpreter->ResetOutputFileHandle (fh);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769}
770
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771void
772Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
773{
Greg Clayton44d93782014-01-27 23:43:24 +0000774 if (m_error_file_sp)
775 m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
776 else
777 m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
778
779 File &err_file = m_error_file_sp->GetFile();
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000780 if (err_file.IsValid() == false)
781 err_file.SetStream (stderr, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000782}
783
Jim Inghamc5917d92012-11-30 20:23:19 +0000784void
785Debugger::SaveInputTerminalState ()
786{
Greg Clayton44d93782014-01-27 23:43:24 +0000787 if (m_input_file_sp)
788 {
789 File &in_file = m_input_file_sp->GetFile();
790 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
791 m_terminal_state.Save(in_file.GetDescriptor(), true);
792 }
Jim Inghamc5917d92012-11-30 20:23:19 +0000793}
794
795void
796Debugger::RestoreInputTerminalState ()
797{
798 m_terminal_state.Restore();
799}
800
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801ExecutionContext
Jim Ingham2976d002010-08-26 21:32:51 +0000802Debugger::GetSelectedExecutionContext ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803{
804 ExecutionContext exe_ctx;
Greg Claytonc14ee322011-09-22 04:58:26 +0000805 TargetSP target_sp(GetSelectedTarget());
806 exe_ctx.SetTargetSP (target_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807
808 if (target_sp)
809 {
Greg Claytonc14ee322011-09-22 04:58:26 +0000810 ProcessSP process_sp (target_sp->GetProcessSP());
811 exe_ctx.SetProcessSP (process_sp);
812 if (process_sp && process_sp->IsRunning() == false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813 {
Greg Claytonc14ee322011-09-22 04:58:26 +0000814 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
815 if (thread_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 {
Greg Claytonc14ee322011-09-22 04:58:26 +0000817 exe_ctx.SetThreadSP (thread_sp);
818 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
819 if (exe_ctx.GetFramePtr() == NULL)
820 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000821 }
822 }
823 }
824 return exe_ctx;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825}
826
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827void
Caroline Ticeefed6132010-11-19 20:47:54 +0000828Debugger::DispatchInputInterrupt ()
829{
Greg Clayton44d93782014-01-27 23:43:24 +0000830 Mutex::Locker locker (m_input_reader_stack.GetMutex());
831 IOHandlerSP reader_sp (m_input_reader_stack.Top());
Caroline Ticeb44880c2011-02-10 01:15:13 +0000832 if (reader_sp)
Greg Clayton44d93782014-01-27 23:43:24 +0000833 reader_sp->Interrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +0000834}
835
836void
837Debugger::DispatchInputEndOfFile ()
838{
Greg Clayton44d93782014-01-27 23:43:24 +0000839 Mutex::Locker locker (m_input_reader_stack.GetMutex());
840 IOHandlerSP reader_sp (m_input_reader_stack.Top());
Caroline Ticeb44880c2011-02-10 01:15:13 +0000841 if (reader_sp)
Greg Clayton44d93782014-01-27 23:43:24 +0000842 reader_sp->GotEOF();
Caroline Ticeefed6132010-11-19 20:47:54 +0000843}
844
845void
Greg Clayton44d93782014-01-27 23:43:24 +0000846Debugger::ClearIOHandlers ()
Caroline Tice3d6086f2010-12-20 18:35:50 +0000847{
Caroline Ticeb44880c2011-02-10 01:15:13 +0000848 // The bottom input reader should be the main debugger input reader. We do not want to close that one here.
Greg Clayton44d93782014-01-27 23:43:24 +0000849 Mutex::Locker locker (m_input_reader_stack.GetMutex());
Caroline Ticed5a0a01b2011-06-02 19:18:55 +0000850 while (m_input_reader_stack.GetSize() > 1)
Caroline Tice3d6086f2010-12-20 18:35:50 +0000851 {
Greg Clayton44d93782014-01-27 23:43:24 +0000852 IOHandlerSP reader_sp (m_input_reader_stack.Top());
Caroline Tice3d6086f2010-12-20 18:35:50 +0000853 if (reader_sp)
854 {
Greg Clayton44d93782014-01-27 23:43:24 +0000855 m_input_reader_stack.Pop();
856 reader_sp->SetIsDone(true);
Greg Claytone68f5d62014-02-24 22:50:57 +0000857 reader_sp->Cancel();
Caroline Tice3d6086f2010-12-20 18:35:50 +0000858 }
859 }
860}
861
862void
Greg Clayton44d93782014-01-27 23:43:24 +0000863Debugger::ExecuteIOHanders()
Caroline Tice969ed3d2011-05-02 20:41:46 +0000864{
Caroline Tice9088b062011-05-09 23:06:58 +0000865
Greg Clayton44d93782014-01-27 23:43:24 +0000866 while (1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867 {
Greg Clayton44d93782014-01-27 23:43:24 +0000868 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 if (!reader_sp)
870 break;
871
Greg Clayton44d93782014-01-27 23:43:24 +0000872 reader_sp->Activate();
873 reader_sp->Run();
874 reader_sp->Deactivate();
875
876 // Remove all input readers that are done from the top of the stack
877 while (1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878 {
Greg Clayton44d93782014-01-27 23:43:24 +0000879 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
880 if (top_reader_sp && top_reader_sp->GetIsDone())
881 m_input_reader_stack.Pop();
882 else
883 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 }
885 }
Greg Clayton44d93782014-01-27 23:43:24 +0000886 ClearIOHandlers();
887}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888
Greg Clayton44d93782014-01-27 23:43:24 +0000889bool
890Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
891{
892 return m_input_reader_stack.IsTop (reader_sp);
893}
894
895
896ConstString
897Debugger::GetTopIOHandlerControlSequence(char ch)
898{
899 return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900}
901
902void
Greg Clayton44d93782014-01-27 23:43:24 +0000903Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
904{
905 Mutex::Locker locker (m_input_reader_stack.GetMutex());
906 PushIOHandler (reader_sp);
Greg Clayton577508d2014-06-20 00:23:57 +0000907
908 IOHandlerSP top_reader_sp = reader_sp;
909 while (top_reader_sp)
910 {
911 top_reader_sp->Activate();
912 top_reader_sp->Run();
913 top_reader_sp->Deactivate();
914
915 if (top_reader_sp.get() == reader_sp.get())
916 {
917 if (PopIOHandler (reader_sp))
918 break;
919 }
920
921 while (1)
922 {
923 top_reader_sp = m_input_reader_stack.Top();
924 if (top_reader_sp && top_reader_sp->GetIsDone())
925 m_input_reader_stack.Pop();
926 else
927 break;
928 }
929 }
Greg Clayton44d93782014-01-27 23:43:24 +0000930}
931
932void
933Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
934{
935 // Before an IOHandler runs, it must have in/out/err streams.
936 // This function is called when one ore more of the streams
937 // are NULL. We use the top input reader's in/out/err streams,
938 // or fall back to the debugger file handles, or we fall back
939 // onto stdin/stdout/stderr as a last resort.
940
941 Mutex::Locker locker (m_input_reader_stack.GetMutex());
942 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
943 // If no STDIN has been set, then set it appropriately
944 if (!in)
945 {
946 if (top_reader_sp)
947 in = top_reader_sp->GetInputStreamFile();
948 else
949 in = GetInputFile();
950
951 // If there is nothing, use stdin
952 if (!in)
953 in = StreamFileSP(new StreamFile(stdin, false));
954 }
955 // If no STDOUT has been set, then set it appropriately
956 if (!out)
957 {
958 if (top_reader_sp)
959 out = top_reader_sp->GetOutputStreamFile();
960 else
961 out = GetOutputFile();
962
963 // If there is nothing, use stdout
964 if (!out)
965 out = StreamFileSP(new StreamFile(stdout, false));
966 }
967 // If no STDERR has been set, then set it appropriately
968 if (!err)
969 {
970 if (top_reader_sp)
971 err = top_reader_sp->GetErrorStreamFile();
972 else
973 err = GetErrorFile();
974
975 // If there is nothing, use stderr
976 if (!err)
977 err = StreamFileSP(new StreamFile(stdout, false));
978
979 }
980}
981
982void
983Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984{
985 if (!reader_sp)
986 return;
Caroline Ticeb44880c2011-02-10 01:15:13 +0000987
Greg Clayton44d93782014-01-27 23:43:24 +0000988 // Got the current top input reader...
989 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
Caroline Ticeb44880c2011-02-10 01:15:13 +0000990
Greg Claytonb4874f12014-02-28 18:22:24 +0000991 // Don't push the same IO handler twice...
992 if (reader_sp.get() != top_reader_sp.get())
993 {
994 // Push our new input reader
995 m_input_reader_stack.Push (reader_sp);
Greg Clayton44d93782014-01-27 23:43:24 +0000996
Greg Claytonb4874f12014-02-28 18:22:24 +0000997 // Interrupt the top input reader to it will exit its Run() function
998 // and let this new input reader take over
999 if (top_reader_sp)
1000 top_reader_sp->Deactivate();
1001 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002}
1003
1004bool
Greg Clayton44d93782014-01-27 23:43:24 +00001005Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006{
1007 bool result = false;
Greg Clayton44d93782014-01-27 23:43:24 +00001008
1009 Mutex::Locker locker (m_input_reader_stack.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010
1011 // The reader on the stop of the stack is done, so let the next
Bruce Mitchener6a7f3332014-06-27 02:42:12 +00001012 // read on the stack refresh its prompt and if there is one...
Caroline Ticed5a0a01b2011-06-02 19:18:55 +00001013 if (!m_input_reader_stack.IsEmpty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014 {
Greg Clayton44d93782014-01-27 23:43:24 +00001015 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016
1017 if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
1018 {
Greg Clayton44d93782014-01-27 23:43:24 +00001019 reader_sp->Deactivate();
Greg Claytonb4874f12014-02-28 18:22:24 +00001020 reader_sp->Cancel();
Caroline Ticed5a0a01b2011-06-02 19:18:55 +00001021 m_input_reader_stack.Pop ();
Greg Clayton44d93782014-01-27 23:43:24 +00001022
1023 reader_sp = m_input_reader_stack.Top();
1024 if (reader_sp)
1025 reader_sp->Activate();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001026
Greg Clayton44d93782014-01-27 23:43:24 +00001027 result = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028 }
1029 }
1030 return result;
1031}
1032
1033bool
Greg Clayton44d93782014-01-27 23:43:24 +00001034Debugger::HideTopIOHandler()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035{
Greg Clayton44d93782014-01-27 23:43:24 +00001036 Mutex::Locker locker;
1037
1038 if (locker.TryLock(m_input_reader_stack.GetMutex()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039 {
Greg Clayton44d93782014-01-27 23:43:24 +00001040 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1041 if (reader_sp)
1042 reader_sp->Hide();
1043 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 }
Greg Clayton44d93782014-01-27 23:43:24 +00001045 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046}
1047
1048void
Greg Clayton44d93782014-01-27 23:43:24 +00001049Debugger::RefreshTopIOHandler()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050{
Greg Clayton44d93782014-01-27 23:43:24 +00001051 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1052 if (reader_sp)
1053 reader_sp->Refresh();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054}
Greg Clayton66111032010-06-23 01:19:29 +00001055
Greg Clayton44d93782014-01-27 23:43:24 +00001056
Jim Ingham5b52f0c2011-06-02 23:58:26 +00001057StreamSP
1058Debugger::GetAsyncOutputStream ()
1059{
1060 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1061 CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1062}
1063
1064StreamSP
1065Debugger::GetAsyncErrorStream ()
1066{
1067 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1068 CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1069}
1070
Greg Claytonc7bece562013-01-25 18:06:21 +00001071size_t
Enrico Granata061858c2012-02-15 02:34:21 +00001072Debugger::GetNumDebuggers()
1073{
Greg Claytonc15f55e2012-03-30 20:53:46 +00001074 if (g_shared_debugger_refcount > 0)
1075 {
1076 Mutex::Locker locker (GetDebuggerListMutex ());
1077 return GetDebuggerList().size();
1078 }
1079 return 0;
Enrico Granata061858c2012-02-15 02:34:21 +00001080}
1081
1082lldb::DebuggerSP
Greg Claytonc7bece562013-01-25 18:06:21 +00001083Debugger::GetDebuggerAtIndex (size_t index)
Enrico Granata061858c2012-02-15 02:34:21 +00001084{
1085 DebuggerSP debugger_sp;
1086
Greg Claytonc15f55e2012-03-30 20:53:46 +00001087 if (g_shared_debugger_refcount > 0)
1088 {
1089 Mutex::Locker locker (GetDebuggerListMutex ());
1090 DebuggerList &debugger_list = GetDebuggerList();
Enrico Granata061858c2012-02-15 02:34:21 +00001091
Greg Claytonc15f55e2012-03-30 20:53:46 +00001092 if (index < debugger_list.size())
1093 debugger_sp = debugger_list[index];
1094 }
1095
Enrico Granata061858c2012-02-15 02:34:21 +00001096 return debugger_sp;
1097}
1098
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001099DebuggerSP
1100Debugger::FindDebuggerWithID (lldb::user_id_t id)
1101{
Greg Clayton4d122c42011-09-17 08:33:22 +00001102 DebuggerSP debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001103
Greg Claytonc15f55e2012-03-30 20:53:46 +00001104 if (g_shared_debugger_refcount > 0)
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001105 {
Greg Claytonc15f55e2012-03-30 20:53:46 +00001106 Mutex::Locker locker (GetDebuggerListMutex ());
1107 DebuggerList &debugger_list = GetDebuggerList();
1108 DebuggerList::iterator pos, end = debugger_list.end();
1109 for (pos = debugger_list.begin(); pos != end; ++pos)
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001110 {
Greg Claytonc15f55e2012-03-30 20:53:46 +00001111 if ((*pos).get()->GetID() == id)
1112 {
1113 debugger_sp = *pos;
1114 break;
1115 }
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001116 }
1117 }
1118 return debugger_sp;
1119}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001120
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001121#if 0
Greg Clayton1b654882010-09-19 02:33:57 +00001122static void
Jason Molendab57e4a12013-11-04 09:33:30 +00001123TestPromptFormats (StackFrame *frame)
Greg Clayton1b654882010-09-19 02:33:57 +00001124{
1125 if (frame == NULL)
1126 return;
1127
1128 StreamString s;
1129 const char *prompt_format =
1130 "{addr = '${addr}'\n}"
1131 "{process.id = '${process.id}'\n}"
1132 "{process.name = '${process.name}'\n}"
1133 "{process.file.basename = '${process.file.basename}'\n}"
1134 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1135 "{thread.id = '${thread.id}'\n}"
1136 "{thread.index = '${thread.index}'\n}"
1137 "{thread.name = '${thread.name}'\n}"
1138 "{thread.queue = '${thread.queue}'\n}"
1139 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1140 "{target.arch = '${target.arch}'\n}"
1141 "{module.file.basename = '${module.file.basename}'\n}"
1142 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1143 "{file.basename = '${file.basename}'\n}"
1144 "{file.fullpath = '${file.fullpath}'\n}"
1145 "{frame.index = '${frame.index}'\n}"
1146 "{frame.pc = '${frame.pc}'\n}"
1147 "{frame.sp = '${frame.sp}'\n}"
1148 "{frame.fp = '${frame.fp}'\n}"
1149 "{frame.flags = '${frame.flags}'\n}"
1150 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1151 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1152 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1153 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1154 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1155 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1156 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1157 "{function.id = '${function.id}'\n}"
1158 "{function.name = '${function.name}'\n}"
Greg Claytonccbc08e2012-01-14 17:04:19 +00001159 "{function.name-with-args = '${function.name-with-args}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001160 "{function.addr-offset = '${function.addr-offset}'\n}"
1161 "{function.line-offset = '${function.line-offset}'\n}"
1162 "{function.pc-offset = '${function.pc-offset}'\n}"
1163 "{line.file.basename = '${line.file.basename}'\n}"
1164 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1165 "{line.number = '${line.number}'\n}"
1166 "{line.start-addr = '${line.start-addr}'\n}"
1167 "{line.end-addr = '${line.end-addr}'\n}"
1168;
1169
1170 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1171 ExecutionContext exe_ctx;
Greg Clayton0603aa92010-10-04 01:05:56 +00001172 frame->CalculateExecutionContext(exe_ctx);
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001173 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
Greg Clayton1b654882010-09-19 02:33:57 +00001174 {
1175 printf("%s\n", s.GetData());
1176 }
1177 else
1178 {
Greg Clayton1b654882010-09-19 02:33:57 +00001179 printf ("what we got: %s\n", s.GetData());
1180 }
1181}
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001182#endif
Greg Clayton1b654882010-09-19 02:33:57 +00001183
Enrico Granata9fc19442011-07-06 02:13:41 +00001184static bool
Enrico Granatadc940732011-08-23 00:32:52 +00001185ScanFormatDescriptor (const char* var_name_begin,
1186 const char* var_name_end,
1187 const char** var_name_final,
1188 const char** percent_position,
Greg Clayton4d122c42011-09-17 08:33:22 +00001189 Format* custom_format,
Enrico Granatadc940732011-08-23 00:32:52 +00001190 ValueObject::ValueObjectRepresentationStyle* val_obj_display)
Enrico Granata9fc19442011-07-06 02:13:41 +00001191{
Greg Clayton5160ce52013-03-27 23:08:40 +00001192 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Enrico Granata9fc19442011-07-06 02:13:41 +00001193 *percent_position = ::strchr(var_name_begin,'%');
Greg Clayton34132752011-07-06 04:07:21 +00001194 if (!*percent_position || *percent_position > var_name_end)
Enrico Granatae992a082011-07-22 17:03:19 +00001195 {
1196 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001197 log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
Enrico Granata9fc19442011-07-06 02:13:41 +00001198 *var_name_final = var_name_end;
Enrico Granatae992a082011-07-22 17:03:19 +00001199 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001200 else
1201 {
1202 *var_name_final = *percent_position;
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001203 std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
Enrico Granatae992a082011-07-22 17:03:19 +00001204 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001205 log->Printf("[ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001206 if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
Enrico Granata9fc19442011-07-06 02:13:41 +00001207 true,
1208 *custom_format) )
1209 {
Enrico Granatae992a082011-07-22 17:03:19 +00001210 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001211 log->Printf("[ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001212
1213 switch (format_name.front())
1214 {
1215 case '@': // if this is an @ sign, print ObjC description
1216 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1217 break;
1218 case 'V': // if this is a V, print the value using the default format
1219 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1220 break;
1221 case 'L': // if this is an L, print the location of the value
1222 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1223 break;
1224 case 'S': // if this is an S, print the summary after all
1225 *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1226 break;
1227 case '#': // if this is a '#', print the number of children
1228 *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1229 break;
1230 case 'T': // if this is a 'T', print the type
1231 *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1232 break;
Enrico Granata2c75f112013-06-21 00:04:51 +00001233 case 'N': // if this is a 'N', print the name
1234 *val_obj_display = ValueObject::eValueObjectRepresentationStyleName;
1235 break;
1236 case '>': // if this is a '>', print the name
1237 *val_obj_display = ValueObject::eValueObjectRepresentationStyleExpressionPath;
1238 break;
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001239 default:
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001240 if (log)
1241 log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001242 break;
1243 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001244 }
1245 // a good custom format tells us to print the value using it
1246 else
Enrico Granatae992a082011-07-22 17:03:19 +00001247 {
1248 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001249 log->Printf("[ScanFormatDescriptor] will display value for this VO");
Enrico Granata86cc9822012-03-19 22:58:49 +00001250 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
Enrico Granatae992a082011-07-22 17:03:19 +00001251 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001252 }
Enrico Granatae992a082011-07-22 17:03:19 +00001253 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001254 log->Printf("[ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
Enrico Granatae992a082011-07-22 17:03:19 +00001255 *custom_format,
1256 *val_obj_display);
Enrico Granata9fc19442011-07-06 02:13:41 +00001257 return true;
1258}
1259
1260static bool
Enrico Granatadc940732011-08-23 00:32:52 +00001261ScanBracketedRange (const char* var_name_begin,
1262 const char* var_name_end,
1263 const char* var_name_final,
1264 const char** open_bracket_position,
1265 const char** separator_position,
1266 const char** close_bracket_position,
1267 const char** var_name_final_if_array_range,
1268 int64_t* index_lower,
1269 int64_t* index_higher)
Enrico Granata9fc19442011-07-06 02:13:41 +00001270{
Greg Clayton5160ce52013-03-27 23:08:40 +00001271 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Enrico Granata9fc19442011-07-06 02:13:41 +00001272 *open_bracket_position = ::strchr(var_name_begin,'[');
Greg Clayton34132752011-07-06 04:07:21 +00001273 if (*open_bracket_position && *open_bracket_position < var_name_final)
Enrico Granata9fc19442011-07-06 02:13:41 +00001274 {
1275 *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1276 *close_bracket_position = ::strchr(*open_bracket_position,']');
1277 // as usual, we assume that [] will come before %
1278 //printf("trying to expand a []\n");
1279 *var_name_final_if_array_range = *open_bracket_position;
Greg Clayton34132752011-07-06 04:07:21 +00001280 if (*close_bracket_position - *open_bracket_position == 1)
Enrico Granata9fc19442011-07-06 02:13:41 +00001281 {
Enrico Granatae992a082011-07-22 17:03:19 +00001282 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001283 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
Enrico Granata9fc19442011-07-06 02:13:41 +00001284 *index_lower = 0;
1285 }
1286 else if (*separator_position == NULL || *separator_position > var_name_end)
1287 {
1288 char *end = NULL;
1289 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1290 *index_higher = *index_lower;
Enrico Granatae992a082011-07-22 17:03:19 +00001291 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001292 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
Enrico Granata9fc19442011-07-06 02:13:41 +00001293 }
Greg Clayton34132752011-07-06 04:07:21 +00001294 else if (*close_bracket_position && *close_bracket_position < var_name_end)
Enrico Granata9fc19442011-07-06 02:13:41 +00001295 {
1296 char *end = NULL;
1297 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1298 *index_higher = ::strtoul (*separator_position+1, &end, 0);
Enrico Granatae992a082011-07-22 17:03:19 +00001299 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001300 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
Enrico Granata9fc19442011-07-06 02:13:41 +00001301 }
1302 else
Enrico Granatae992a082011-07-22 17:03:19 +00001303 {
1304 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001305 log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
Enrico Granata9fc19442011-07-06 02:13:41 +00001306 return false;
Enrico Granatae992a082011-07-22 17:03:19 +00001307 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001308 if (*index_lower > *index_higher && *index_higher > 0)
1309 {
Enrico Granatae992a082011-07-22 17:03:19 +00001310 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001311 log->Printf("[ScanBracketedRange] swapping indices");
Greg Claytonc7bece562013-01-25 18:06:21 +00001312 int64_t temp = *index_lower;
Enrico Granata9fc19442011-07-06 02:13:41 +00001313 *index_lower = *index_higher;
1314 *index_higher = temp;
1315 }
1316 }
Enrico Granatae992a082011-07-22 17:03:19 +00001317 else if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001318 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
Enrico Granata9fc19442011-07-06 02:13:41 +00001319 return true;
1320}
1321
Michael Sartain0769b2b2013-07-30 16:44:36 +00001322template <typename T>
1323static bool RunScriptFormatKeyword(Stream &s, ScriptInterpreter *script_interpreter, T t, const std::string& script_name)
1324{
1325 if (script_interpreter)
1326 {
1327 Error script_error;
1328 std::string script_output;
1329
1330 if (script_interpreter->RunScriptFormatKeyword(script_name.c_str(), t, script_output, script_error) && script_error.Success())
1331 {
1332 s.Printf("%s", script_output.c_str());
1333 return true;
1334 }
1335 else
1336 {
1337 s.Printf("<error: %s>",script_error.AsCString());
1338 }
1339 }
1340 return false;
1341}
1342
Enrico Granata9fc19442011-07-06 02:13:41 +00001343static ValueObjectSP
Enrico Granatadc940732011-08-23 00:32:52 +00001344ExpandIndexedExpression (ValueObject* valobj,
Greg Claytonc7bece562013-01-25 18:06:21 +00001345 size_t index,
Jason Molendab57e4a12013-11-04 09:33:30 +00001346 StackFrame* frame,
Enrico Granatadc940732011-08-23 00:32:52 +00001347 bool deref_pointer)
Enrico Granata9fc19442011-07-06 02:13:41 +00001348{
Greg Clayton5160ce52013-03-27 23:08:40 +00001349 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001350 const char* ptr_deref_format = "[%d]";
Enrico Granata599171a2013-02-01 23:59:44 +00001351 std::string ptr_deref_buffer(10,0);
1352 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
Enrico Granatae992a082011-07-22 17:03:19 +00001353 if (log)
Enrico Granata599171a2013-02-01 23:59:44 +00001354 log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001355 const char* first_unparsed;
1356 ValueObject::GetValueForExpressionPathOptions options;
1357 ValueObject::ExpressionPathEndResultType final_value_type;
1358 ValueObject::ExpressionPathScanEndReason reason_to_stop;
Enrico Granata86cc9822012-03-19 22:58:49 +00001359 ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
Enrico Granata599171a2013-02-01 23:59:44 +00001360 ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001361 &first_unparsed,
1362 &reason_to_stop,
1363 &final_value_type,
1364 options,
1365 &what_next);
1366 if (!item)
1367 {
Enrico Granatae992a082011-07-22 17:03:19 +00001368 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001369 log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001370 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001371 first_unparsed, reason_to_stop, final_value_type);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001372 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001373 else
1374 {
Enrico Granatae992a082011-07-22 17:03:19 +00001375 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001376 log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001377 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001378 first_unparsed, reason_to_stop, final_value_type);
Enrico Granata9fc19442011-07-06 02:13:41 +00001379 }
1380 return item;
1381}
1382
Michael Sartain0769b2b2013-07-30 16:44:36 +00001383static inline bool
1384IsToken(const char *var_name_begin, const char *var)
1385{
1386 return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1387}
1388
1389static bool
1390IsTokenWithFormat(const char *var_name_begin, const char *var, std::string &format, const char *default_format,
1391 const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1392{
1393 int var_len = strlen(var);
1394 if (::strncmp (var_name_begin, var, var_len) == 0)
1395 {
1396 var_name_begin += var_len;
1397 if (*var_name_begin == '}')
1398 {
1399 format = default_format;
1400 return true;
1401 }
1402 else if (*var_name_begin == '%')
1403 {
1404 // Allow format specifiers: x|X|u with optional width specifiers.
1405 // ${thread.id%x} ; hex
1406 // ${thread.id%X} ; uppercase hex
1407 // ${thread.id%u} ; unsigned decimal
1408 // ${thread.id%8.8X} ; width.precision + specifier
1409 // ${thread.id%tid} ; unsigned on FreeBSD/Linux, otherwise default_format (0x%4.4x for thread.id)
1410 int dot_count = 0;
1411 const char *specifier = NULL;
1412 int width_precision_length = 0;
1413 const char *width_precision = ++var_name_begin;
1414 while (isdigit(*var_name_begin) || *var_name_begin == '.')
1415 {
1416 dot_count += (*var_name_begin == '.');
1417 if (dot_count > 1)
1418 break;
1419 var_name_begin++;
1420 width_precision_length++;
1421 }
1422
1423 if (IsToken (var_name_begin, "tid}"))
1424 {
1425 Target *target = Target::GetTargetFromContexts (exe_ctx_ptr, sc_ptr);
1426 if (target)
1427 {
1428 ArchSpec arch (target->GetArchitecture ());
1429 llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1430 if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1431 specifier = PRIu64;
1432 }
1433 if (!specifier)
1434 {
1435 format = default_format;
1436 return true;
1437 }
1438 }
1439 else if (IsToken (var_name_begin, "x}"))
1440 specifier = PRIx64;
1441 else if (IsToken (var_name_begin, "X}"))
1442 specifier = PRIX64;
1443 else if (IsToken (var_name_begin, "u}"))
1444 specifier = PRIu64;
1445
1446 if (specifier)
1447 {
1448 format = "%";
1449 if (width_precision_length)
1450 format += std::string(width_precision, width_precision_length);
1451 format += specifier;
1452 return true;
1453 }
1454 }
1455 }
1456 return false;
1457}
1458
Jason Molenda705b1802014-06-13 02:37:02 +00001459// Find information for the "thread.info.*" specifiers in a format string
1460static bool
1461FormatThreadExtendedInfoRecurse
1462(
1463 const char *var_name_begin,
1464 StructuredData::ObjectSP thread_info_dictionary,
1465 const SymbolContext *sc,
1466 const ExecutionContext *exe_ctx,
1467 Stream &s
1468)
1469{
1470 bool var_success = false;
1471 std::string token_format;
1472
1473 llvm::StringRef var_name(var_name_begin);
1474 size_t percent_idx = var_name.find('%');
1475 size_t close_curly_idx = var_name.find('}');
1476 llvm::StringRef path = var_name;
1477 llvm::StringRef formatter = var_name;
1478
1479 // 'path' will be the dot separated list of objects to transverse up until we hit
1480 // a close curly brace, a percent sign, or an end of string.
1481 if (percent_idx != llvm::StringRef::npos || close_curly_idx != llvm::StringRef::npos)
1482 {
1483 if (percent_idx != llvm::StringRef::npos && close_curly_idx != llvm::StringRef::npos)
1484 {
1485 if (percent_idx < close_curly_idx)
1486 {
1487 path = var_name.slice(0, percent_idx);
1488 formatter = var_name.substr (percent_idx);
1489 }
1490 else
1491 {
1492 path = var_name.slice(0, close_curly_idx);
1493 formatter = var_name.substr (close_curly_idx);
1494 }
1495 }
1496 else if (percent_idx != llvm::StringRef::npos)
1497 {
1498 path = var_name.slice(0, percent_idx);
1499 formatter = var_name.substr (percent_idx);
1500 }
1501 else if (close_curly_idx != llvm::StringRef::npos)
1502 {
1503 path = var_name.slice(0, close_curly_idx);
1504 formatter = var_name.substr (close_curly_idx);
1505 }
1506 }
1507
1508 StructuredData::ObjectSP value = thread_info_dictionary->GetObjectForDotSeparatedPath (path);
1509
1510 if (value.get())
1511 {
1512 if (value->GetType() == StructuredData::Type::eTypeInteger)
1513 {
1514 if (IsTokenWithFormat (formatter.str().c_str(), "", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1515 {
1516 s.Printf(token_format.c_str(), value->GetAsInteger()->GetValue());
1517 var_success = true;
1518 }
1519 }
1520 else if (value->GetType() == StructuredData::Type::eTypeFloat)
1521 {
1522 s.Printf ("%f", value->GetAsFloat()->GetValue());
1523 var_success = true;
1524 }
1525 else if (value->GetType() == StructuredData::Type::eTypeString)
1526 {
1527 s.Printf("%s", value->GetAsString()->GetValue().c_str());
1528 var_success = true;
1529 }
1530 else if (value->GetType() == StructuredData::Type::eTypeArray)
1531 {
1532 if (value->GetAsArray()->GetSize() > 0)
1533 {
1534 s.Printf ("%zu", value->GetAsArray()->GetSize());
1535 var_success = true;
1536 }
1537 }
1538 else if (value->GetType() == StructuredData::Type::eTypeDictionary)
1539 {
1540 s.Printf ("%zu", value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1541 var_success = true;
1542 }
1543 }
1544
1545 return var_success;
1546}
1547
1548
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001549static bool
1550FormatPromptRecurse
Greg Clayton1b654882010-09-19 02:33:57 +00001551(
1552 const char *format,
1553 const SymbolContext *sc,
1554 const ExecutionContext *exe_ctx,
1555 const Address *addr,
1556 Stream &s,
Enrico Granata4becb372011-06-29 22:27:15 +00001557 const char **end,
Enrico Granatac482a192011-08-17 22:13:59 +00001558 ValueObject* valobj
Greg Clayton1b654882010-09-19 02:33:57 +00001559)
1560{
Enrico Granatac482a192011-08-17 22:13:59 +00001561 ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
Greg Clayton1b654882010-09-19 02:33:57 +00001562 bool success = true;
1563 const char *p;
Greg Clayton5160ce52013-03-27 23:08:40 +00001564 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001565
Greg Clayton1b654882010-09-19 02:33:57 +00001566 for (p = format; *p != '\0'; ++p)
1567 {
Enrico Granatac482a192011-08-17 22:13:59 +00001568 if (realvalobj)
Enrico Granata4becb372011-06-29 22:27:15 +00001569 {
Enrico Granatac482a192011-08-17 22:13:59 +00001570 valobj = realvalobj;
1571 realvalobj = NULL;
Enrico Granata4becb372011-06-29 22:27:15 +00001572 }
Greg Clayton1b654882010-09-19 02:33:57 +00001573 size_t non_special_chars = ::strcspn (p, "${}\\");
1574 if (non_special_chars > 0)
1575 {
1576 if (success)
1577 s.Write (p, non_special_chars);
1578 p += non_special_chars;
1579 }
1580
1581 if (*p == '\0')
1582 {
1583 break;
1584 }
1585 else if (*p == '{')
1586 {
1587 // Start a new scope that must have everything it needs if it is to
1588 // to make it into the final output stream "s". If you want to make
1589 // a format that only prints out the function or symbol name if there
1590 // is one in the symbol context you can use:
1591 // "{function =${function.name}}"
1592 // The first '{' starts a new scope that end with the matching '}' at
1593 // the end of the string. The contents "function =${function.name}"
1594 // will then be evaluated and only be output if there is a function
1595 // or symbol with a valid name.
1596 StreamString sub_strm;
1597
1598 ++p; // Skip the '{'
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001599
1600 if (FormatPromptRecurse (p, sc, exe_ctx, addr, sub_strm, &p, valobj))
Greg Clayton1b654882010-09-19 02:33:57 +00001601 {
1602 // The stream had all it needed
1603 s.Write(sub_strm.GetData(), sub_strm.GetSize());
1604 }
1605 if (*p != '}')
1606 {
1607 success = false;
1608 break;
1609 }
1610 }
1611 else if (*p == '}')
1612 {
1613 // End of a enclosing scope
1614 break;
1615 }
1616 else if (*p == '$')
1617 {
1618 // We have a prompt variable to print
1619 ++p;
1620 if (*p == '{')
1621 {
1622 ++p;
1623 const char *var_name_begin = p;
1624 const char *var_name_end = ::strchr (p, '}');
1625
1626 if (var_name_end && var_name_begin < var_name_end)
1627 {
1628 // if we have already failed to parse, skip this variable
1629 if (success)
1630 {
1631 const char *cstr = NULL;
Michael Sartain0769b2b2013-07-30 16:44:36 +00001632 std::string token_format;
Greg Clayton1b654882010-09-19 02:33:57 +00001633 Address format_addr;
1634 bool calculate_format_addr_function_offset = false;
1635 // Set reg_kind and reg_num to invalid values
1636 RegisterKind reg_kind = kNumRegisterKinds;
1637 uint32_t reg_num = LLDB_INVALID_REGNUM;
1638 FileSpec format_file_spec;
Greg Claytone0d378b2011-03-24 21:19:54 +00001639 const RegisterInfo *reg_info = NULL;
Greg Clayton1b654882010-09-19 02:33:57 +00001640 RegisterContext *reg_ctx = NULL;
Enrico Granata9fc19442011-07-06 02:13:41 +00001641 bool do_deref_pointer = false;
Enrico Granata86cc9822012-03-19 22:58:49 +00001642 ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1643 ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001644
Greg Clayton1b654882010-09-19 02:33:57 +00001645 // Each variable must set success to true below...
1646 bool var_success = false;
1647 switch (var_name_begin[0])
1648 {
Enrico Granata4becb372011-06-29 22:27:15 +00001649 case '*':
Enrico Granata4becb372011-06-29 22:27:15 +00001650 case 'v':
Enrico Granata6f3533f2011-07-29 19:53:35 +00001651 case 's':
Enrico Granata4becb372011-06-29 22:27:15 +00001652 {
Enrico Granatac482a192011-08-17 22:13:59 +00001653 if (!valobj)
Enrico Granata6f3533f2011-07-29 19:53:35 +00001654 break;
1655
Enrico Granatac3e320a2011-08-02 17:27:39 +00001656 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001657 log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
Enrico Granatac3e320a2011-08-02 17:27:39 +00001658
Enrico Granata6f3533f2011-07-29 19:53:35 +00001659 // check for *var and *svar
1660 if (*var_name_begin == '*')
1661 {
1662 do_deref_pointer = true;
1663 var_name_begin++;
Enrico Granata68ae4112013-06-18 18:23:07 +00001664 if (log)
1665 log->Printf("[Debugger::FormatPrompt] found a deref, new string is: %s",var_name_begin);
Enrico Granata6f3533f2011-07-29 19:53:35 +00001666 }
Enrico Granatac3e320a2011-08-02 17:27:39 +00001667
Enrico Granata6f3533f2011-07-29 19:53:35 +00001668 if (*var_name_begin == 's')
1669 {
Enrico Granatac5bc4122012-03-27 02:35:13 +00001670 if (!valobj->IsSynthetic())
1671 valobj = valobj->GetSyntheticValue().get();
Enrico Granata86cc9822012-03-19 22:58:49 +00001672 if (!valobj)
1673 break;
Enrico Granata6f3533f2011-07-29 19:53:35 +00001674 var_name_begin++;
Enrico Granata68ae4112013-06-18 18:23:07 +00001675 if (log)
1676 log->Printf("[Debugger::FormatPrompt] found a synthetic, new string is: %s",var_name_begin);
Enrico Granata6f3533f2011-07-29 19:53:35 +00001677 }
1678
1679 // should be a 'v' by now
1680 if (*var_name_begin != 'v')
1681 break;
1682
Enrico Granatac3e320a2011-08-02 17:27:39 +00001683 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001684 log->Printf("[Debugger::FormatPrompt] string I am working with: %s",var_name_begin);
Enrico Granatac3e320a2011-08-02 17:27:39 +00001685
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001686 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
Enrico Granata86cc9822012-03-19 22:58:49 +00001687 ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001688 ValueObject::GetValueForExpressionPathOptions options;
Enrico Granata8c9d3562011-08-11 17:08:01 +00001689 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
Enrico Granata86cc9822012-03-19 22:58:49 +00001690 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
Greg Clayton34132752011-07-06 04:07:21 +00001691 ValueObject* target = NULL;
Greg Clayton4d122c42011-09-17 08:33:22 +00001692 Format custom_format = eFormatInvalid;
Greg Clayton34132752011-07-06 04:07:21 +00001693 const char* var_name_final = NULL;
1694 const char* var_name_final_if_array_range = NULL;
1695 const char* close_bracket_position = NULL;
1696 int64_t index_lower = -1;
1697 int64_t index_higher = -1;
1698 bool is_array_range = false;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001699 const char* first_unparsed;
Enrico Granata85933ed2011-08-18 16:38:26 +00001700 bool was_plain_var = false;
1701 bool was_var_format = false;
Enrico Granataa777dc22012-05-08 21:49:57 +00001702 bool was_var_indexed = false;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001703
Enrico Granatac482a192011-08-17 22:13:59 +00001704 if (!valobj) break;
1705 // simplest case ${var}, just print valobj's value
Michael Sartain0769b2b2013-07-30 16:44:36 +00001706 if (IsToken (var_name_begin, "var}"))
Enrico Granata4becb372011-06-29 22:27:15 +00001707 {
Enrico Granata85933ed2011-08-18 16:38:26 +00001708 was_plain_var = true;
Enrico Granatac482a192011-08-17 22:13:59 +00001709 target = valobj;
Enrico Granata86cc9822012-03-19 22:58:49 +00001710 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
Greg Clayton34132752011-07-06 04:07:21 +00001711 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00001712 else if (IsToken (var_name_begin,"var%"))
Greg Clayton34132752011-07-06 04:07:21 +00001713 {
Enrico Granata85933ed2011-08-18 16:38:26 +00001714 was_var_format = true;
Greg Clayton34132752011-07-06 04:07:21 +00001715 // this is a variable with some custom format applied to it
1716 const char* percent_position;
Enrico Granatac482a192011-08-17 22:13:59 +00001717 target = valobj;
Enrico Granata86cc9822012-03-19 22:58:49 +00001718 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
Greg Clayton34132752011-07-06 04:07:21 +00001719 ScanFormatDescriptor (var_name_begin,
1720 var_name_end,
1721 &var_name_final,
1722 &percent_position,
1723 &custom_format,
1724 &val_obj_display);
1725 }
1726 // this is ${var.something} or multiple .something nested
Michael Sartain0769b2b2013-07-30 16:44:36 +00001727 else if (IsToken (var_name_begin, "var"))
Greg Clayton34132752011-07-06 04:07:21 +00001728 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00001729 if (IsToken (var_name_begin, "var["))
Enrico Granataa777dc22012-05-08 21:49:57 +00001730 was_var_indexed = true;
Greg Clayton34132752011-07-06 04:07:21 +00001731 const char* percent_position;
1732 ScanFormatDescriptor (var_name_begin,
1733 var_name_end,
1734 &var_name_final,
1735 &percent_position,
1736 &custom_format,
1737 &val_obj_display);
1738
1739 const char* open_bracket_position;
1740 const char* separator_position;
1741 ScanBracketedRange (var_name_begin,
1742 var_name_end,
1743 var_name_final,
1744 &open_bracket_position,
1745 &separator_position,
1746 &close_bracket_position,
1747 &var_name_final_if_array_range,
1748 &index_lower,
1749 &index_higher);
1750
1751 Error error;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001752
Enrico Granata599171a2013-02-01 23:59:44 +00001753 std::string expr_path(var_name_final-var_name_begin-1,0);
1754 memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1755
1756 if (log)
1757 log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1758
1759 target = valobj->GetValueForExpressionPath(expr_path.c_str(),
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001760 &first_unparsed,
1761 &reason_to_stop,
1762 &final_value_type,
1763 options,
1764 &what_next).get();
1765
1766 if (!target)
Enrico Granata9fc19442011-07-06 02:13:41 +00001767 {
Enrico Granatae992a082011-07-22 17:03:19 +00001768 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001769 log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001770 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001771 first_unparsed, reason_to_stop, final_value_type);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001772 break;
Enrico Granata9fc19442011-07-06 02:13:41 +00001773 }
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001774 else
1775 {
Enrico Granatae992a082011-07-22 17:03:19 +00001776 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001777 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001778 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001779 first_unparsed, reason_to_stop, final_value_type);
1780 }
Enrico Granata4becb372011-06-29 22:27:15 +00001781 }
Greg Clayton34132752011-07-06 04:07:21 +00001782 else
Enrico Granata9fc19442011-07-06 02:13:41 +00001783 break;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001784
Enrico Granata86cc9822012-03-19 22:58:49 +00001785 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1786 final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001787
Enrico Granata86cc9822012-03-19 22:58:49 +00001788 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
Enrico Granata9fc19442011-07-06 02:13:41 +00001789
Enrico Granataa7187d02011-07-06 19:27:11 +00001790 if (do_deref_pointer && !is_array_range)
Enrico Granata9fc19442011-07-06 02:13:41 +00001791 {
Greg Clayton34132752011-07-06 04:07:21 +00001792 // I have not deref-ed yet, let's do it
1793 // this happens when we are not going through GetValueForVariableExpressionPath
1794 // to get to the target ValueObject
Enrico Granata9fc19442011-07-06 02:13:41 +00001795 Error error;
Greg Clayton34132752011-07-06 04:07:21 +00001796 target = target->Dereference(error).get();
Enrico Granatadc940732011-08-23 00:32:52 +00001797 if (error.Fail())
1798 {
1799 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001800 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
Enrico Granatadc940732011-08-23 00:32:52 +00001801 break;
1802 }
Greg Clayton34132752011-07-06 04:07:21 +00001803 do_deref_pointer = false;
Enrico Granata9fc19442011-07-06 02:13:41 +00001804 }
Enrico Granataf4efecd2011-07-12 22:56:10 +00001805
Jim Inghamf164d942014-03-11 18:17:23 +00001806 if (!target)
1807 {
1808 if (log)
1809 log->Printf("[Debugger::FormatPrompt] could not calculate target for prompt expression");
1810 break;
1811 }
1812
Enrico Granataa777dc22012-05-08 21:49:57 +00001813 // we do not want to use the summary for a bitfield of type T:n
1814 // if we were originally dealing with just a T - that would get
1815 // us into an endless recursion
1816 if (target->IsBitfield() && was_var_indexed)
1817 {
1818 // TODO: check for a (T:n)-specific summary - we should still obey that
1819 StreamString bitfield_name;
1820 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1821 lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1822 if (!DataVisualization::GetSummaryForType(type_sp))
1823 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1824 }
1825
Enrico Granata85933ed2011-08-18 16:38:26 +00001826 // TODO use flags for these
Greg Clayton57ee3062013-07-11 22:46:58 +00001827 const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
1828 bool is_array = (type_info_flags & ClangASTType::eTypeIsArray) != 0;
1829 bool is_pointer = (type_info_flags & ClangASTType::eTypeIsPointer) != 0;
1830 bool is_aggregate = target->GetClangType().IsAggregateType();
Enrico Granataf4efecd2011-07-12 22:56:10 +00001831
Enrico Granata86cc9822012-03-19 22:58:49 +00001832 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
Enrico Granataf4efecd2011-07-12 22:56:10 +00001833 {
Enrico Granata85933ed2011-08-18 16:38:26 +00001834 StreamString str_temp;
Enrico Granatae992a082011-07-22 17:03:19 +00001835 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001836 log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001837
Greg Clayton5088c482013-03-25 21:06:13 +00001838 if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
Enrico Granata85933ed2011-08-18 16:38:26 +00001839 {
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001840 // try to use the special cases
1841 var_success = target->DumpPrintableRepresentation(str_temp,
1842 val_obj_display,
1843 custom_format);
1844 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001845 log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001846
1847 // should not happen
Greg Clayton5088c482013-03-25 21:06:13 +00001848 if (var_success)
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001849 s << str_temp.GetData();
Enrico Granata85933ed2011-08-18 16:38:26 +00001850 var_success = true;
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001851 break;
Enrico Granata85933ed2011-08-18 16:38:26 +00001852 }
1853 else
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001854 {
Enrico Granata88da35f2011-08-23 21:26:09 +00001855 if (was_plain_var) // if ${var}
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001856 {
1857 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1858 }
Enrico Granata88da35f2011-08-23 21:26:09 +00001859 else if (is_pointer) // if pointer, value is the address stored
1860 {
Greg Clayton23f59502012-07-17 03:23:13 +00001861 target->DumpPrintableRepresentation (s,
1862 val_obj_display,
1863 custom_format,
1864 ValueObject::ePrintableRepresentationSpecialCasesDisable);
Enrico Granata88da35f2011-08-23 21:26:09 +00001865 }
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001866 var_success = true;
1867 break;
1868 }
1869 }
1870
1871 // if directly trying to print ${var}, and this is an aggregate, display a nice
1872 // type @ location message
1873 if (is_aggregate && was_plain_var)
1874 {
1875 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1876 var_success = true;
Enrico Granata85933ed2011-08-18 16:38:26 +00001877 break;
1878 }
1879
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001880 // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
Enrico Granata86cc9822012-03-19 22:58:49 +00001881 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
Enrico Granata85933ed2011-08-18 16:38:26 +00001882 {
1883 s << "<invalid use of aggregate type>";
1884 var_success = true;
Enrico Granataf4efecd2011-07-12 22:56:10 +00001885 break;
1886 }
Greg Clayton34132752011-07-06 04:07:21 +00001887
1888 if (!is_array_range)
Enrico Granatae992a082011-07-22 17:03:19 +00001889 {
1890 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001891 log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
Greg Clayton34132752011-07-06 04:07:21 +00001892 var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
Enrico Granatae992a082011-07-22 17:03:19 +00001893 }
Greg Clayton34132752011-07-06 04:07:21 +00001894 else
Enrico Granatae992a082011-07-22 17:03:19 +00001895 {
1896 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001897 log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
Greg Clayton34132752011-07-06 04:07:21 +00001898 if (!is_array && !is_pointer)
1899 break;
Enrico Granatae992a082011-07-22 17:03:19 +00001900 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001901 log->Printf("[Debugger::FormatPrompt] handle as array");
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001902 const char* special_directions = NULL;
1903 StreamString special_directions_writer;
Greg Clayton34132752011-07-06 04:07:21 +00001904 if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1905 {
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001906 ConstString additional_data;
1907 additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1908 special_directions_writer.Printf("${%svar%s}",
1909 do_deref_pointer ? "*" : "",
1910 additional_data.GetCString());
1911 special_directions = special_directions_writer.GetData();
Greg Clayton34132752011-07-06 04:07:21 +00001912 }
1913
1914 // let us display items index_lower thru index_higher of this array
1915 s.PutChar('[');
1916 var_success = true;
1917
1918 if (index_higher < 0)
Enrico Granatac482a192011-08-17 22:13:59 +00001919 index_higher = valobj->GetNumChildren() - 1;
Greg Clayton34132752011-07-06 04:07:21 +00001920
Greg Claytoncc4d0142012-02-17 07:49:44 +00001921 uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
Enrico Granata22c55d12011-08-12 02:00:06 +00001922
Greg Clayton34132752011-07-06 04:07:21 +00001923 for (;index_lower<=index_higher;index_lower++)
1924 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001925 ValueObject* item = ExpandIndexedExpression (target,
1926 index_lower,
1927 exe_ctx->GetFramePtr(),
1928 false).get();
Greg Clayton34132752011-07-06 04:07:21 +00001929
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001930 if (!item)
1931 {
Enrico Granatae992a082011-07-22 17:03:19 +00001932 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001933 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001934 }
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001935 else
1936 {
Enrico Granatae992a082011-07-22 17:03:19 +00001937 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001938 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001939 }
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001940
Greg Clayton34132752011-07-06 04:07:21 +00001941 if (!special_directions)
1942 var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1943 else
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001944 var_success &= FormatPromptRecurse(special_directions, sc, exe_ctx, addr, s, NULL, item);
Greg Clayton34132752011-07-06 04:07:21 +00001945
Enrico Granata22c55d12011-08-12 02:00:06 +00001946 if (--max_num_children == 0)
1947 {
1948 s.PutCString(", ...");
1949 break;
1950 }
1951
Greg Clayton34132752011-07-06 04:07:21 +00001952 if (index_lower < index_higher)
1953 s.PutChar(',');
1954 }
1955 s.PutChar(']');
1956 }
Enrico Granata4becb372011-06-29 22:27:15 +00001957 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001958 break;
Greg Clayton1b654882010-09-19 02:33:57 +00001959 case 'a':
Michael Sartain0769b2b2013-07-30 16:44:36 +00001960 if (IsToken (var_name_begin, "addr}"))
Greg Clayton1b654882010-09-19 02:33:57 +00001961 {
1962 if (addr && addr->IsValid())
1963 {
1964 var_success = true;
1965 format_addr = *addr;
1966 }
1967 }
1968 break;
1969
1970 case 'p':
Michael Sartain0769b2b2013-07-30 16:44:36 +00001971 if (IsToken (var_name_begin, "process."))
Greg Clayton1b654882010-09-19 02:33:57 +00001972 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001973 if (exe_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00001974 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001975 Process *process = exe_ctx->GetProcessPtr();
1976 if (process)
Greg Clayton1b654882010-09-19 02:33:57 +00001977 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001978 var_name_begin += ::strlen ("process.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00001979 if (IsTokenWithFormat (var_name_begin, "id", token_format, "%" PRIu64, exe_ctx, sc))
Greg Clayton1b654882010-09-19 02:33:57 +00001980 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00001981 s.Printf(token_format.c_str(), process->GetID());
Greg Claytonc14ee322011-09-22 04:58:26 +00001982 var_success = true;
1983 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00001984 else if ((IsToken (var_name_begin, "name}")) ||
1985 (IsToken (var_name_begin, "file.basename}")) ||
1986 (IsToken (var_name_begin, "file.fullpath}")))
Greg Claytonc14ee322011-09-22 04:58:26 +00001987 {
1988 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1989 if (exe_module)
Greg Clayton1b654882010-09-19 02:33:57 +00001990 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001991 if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
1992 {
1993 format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00001994 var_success = (bool)format_file_spec;
Greg Claytonc14ee322011-09-22 04:58:26 +00001995 }
1996 else
1997 {
1998 format_file_spec = exe_module->GetFileSpec();
Sean Callanan9076c0f2013-10-04 21:35:29 +00001999 var_success = (bool)format_file_spec;
Greg Claytonc14ee322011-09-22 04:58:26 +00002000 }
Greg Clayton1b654882010-09-19 02:33:57 +00002001 }
2002 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002003 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002004 {
2005 var_name_begin += ::strlen("script:");
2006 std::string script_name(var_name_begin,var_name_end);
2007 ScriptInterpreter* script_interpreter = process->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002008 if (RunScriptFormatKeyword (s, script_interpreter, process, script_name))
2009 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002010 }
Greg Clayton1b654882010-09-19 02:33:57 +00002011 }
Greg Claytonc14ee322011-09-22 04:58:26 +00002012 }
Greg Clayton1b654882010-09-19 02:33:57 +00002013 }
2014 break;
2015
2016 case 't':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002017 if (IsToken (var_name_begin, "thread."))
Greg Clayton1b654882010-09-19 02:33:57 +00002018 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002019 if (exe_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00002020 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002021 Thread *thread = exe_ctx->GetThreadPtr();
2022 if (thread)
Greg Clayton1b654882010-09-19 02:33:57 +00002023 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002024 var_name_begin += ::strlen ("thread.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002025 if (IsTokenWithFormat (var_name_begin, "id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
Greg Clayton1b654882010-09-19 02:33:57 +00002026 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002027 s.Printf(token_format.c_str(), thread->GetID());
Greg Claytonc14ee322011-09-22 04:58:26 +00002028 var_success = true;
2029 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002030 else if (IsTokenWithFormat (var_name_begin, "protocol_id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
Greg Clayton160c9d82013-05-01 21:54:04 +00002031 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002032 s.Printf(token_format.c_str(), thread->GetProtocolID());
Greg Clayton160c9d82013-05-01 21:54:04 +00002033 var_success = true;
2034 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002035 else if (IsTokenWithFormat (var_name_begin, "index", token_format, "%" PRIu64, exe_ctx, sc))
Greg Claytonc14ee322011-09-22 04:58:26 +00002036 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002037 s.Printf(token_format.c_str(), (uint64_t)thread->GetIndexID());
Greg Claytonc14ee322011-09-22 04:58:26 +00002038 var_success = true;
2039 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002040 else if (IsToken (var_name_begin, "name}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002041 {
2042 cstr = thread->GetName();
2043 var_success = cstr && cstr[0];
2044 if (var_success)
Greg Clayton1b654882010-09-19 02:33:57 +00002045 s.PutCString(cstr);
Greg Claytonc14ee322011-09-22 04:58:26 +00002046 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002047 else if (IsToken (var_name_begin, "queue}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002048 {
2049 cstr = thread->GetQueueName();
2050 var_success = cstr && cstr[0];
2051 if (var_success)
2052 s.PutCString(cstr);
2053 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002054 else if (IsToken (var_name_begin, "stop-reason}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002055 {
2056 StopInfoSP stop_info_sp = thread->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00002057 if (stop_info_sp && stop_info_sp->IsValid())
Greg Claytonc14ee322011-09-22 04:58:26 +00002058 {
2059 cstr = stop_info_sp->GetDescription();
2060 if (cstr && cstr[0])
2061 {
2062 s.PutCString(cstr);
2063 var_success = true;
2064 }
Greg Clayton1b654882010-09-19 02:33:57 +00002065 }
2066 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002067 else if (IsToken (var_name_begin, "return-value}"))
Jim Ingham73ca05a2011-12-17 01:35:57 +00002068 {
2069 StopInfoSP stop_info_sp = thread->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00002070 if (stop_info_sp && stop_info_sp->IsValid())
Jim Ingham73ca05a2011-12-17 01:35:57 +00002071 {
2072 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
2073 if (return_valobj_sp)
2074 {
Enrico Granata4d93b8c2013-09-30 19:11:51 +00002075 return_valobj_sp->Dump(s);
Jim Inghamef651602011-12-22 19:12:40 +00002076 var_success = true;
Jim Ingham73ca05a2011-12-17 01:35:57 +00002077 }
2078 }
2079 }
Jim Ingham30fadaf2014-07-08 01:07:32 +00002080 else if (IsToken (var_name_begin, "completed-expression}"))
2081 {
2082 StopInfoSP stop_info_sp = thread->GetStopInfo ();
2083 if (stop_info_sp && stop_info_sp->IsValid())
2084 {
2085 ClangExpressionVariableSP expression_var_sp = StopInfo::GetExpressionVariable (stop_info_sp);
2086 if (expression_var_sp && expression_var_sp->GetValueObject())
2087 {
2088 expression_var_sp->GetValueObject()->Dump(s);
2089 var_success = true;
2090 }
2091 }
2092 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002093 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002094 {
2095 var_name_begin += ::strlen("script:");
2096 std::string script_name(var_name_begin,var_name_end);
2097 ScriptInterpreter* script_interpreter = thread->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002098 if (RunScriptFormatKeyword (s, script_interpreter, thread, script_name))
2099 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002100 }
Jason Molenda705b1802014-06-13 02:37:02 +00002101 else if (IsToken (var_name_begin, "info."))
2102 {
2103 var_name_begin += ::strlen("info.");
2104 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
2105 if (object_sp && object_sp->GetType() == StructuredData::Type::eTypeDictionary)
2106 {
2107 var_success = FormatThreadExtendedInfoRecurse (var_name_begin, object_sp, sc, exe_ctx, s);
2108 }
2109 }
Greg Clayton1b654882010-09-19 02:33:57 +00002110 }
2111 }
2112 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002113 else if (IsToken (var_name_begin, "target."))
Greg Clayton1b654882010-09-19 02:33:57 +00002114 {
Greg Clayton67cc0632012-08-22 17:17:09 +00002115 // TODO: hookup properties
2116// if (!target_properties_sp)
2117// {
2118// Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2119// if (target)
2120// target_properties_sp = target->GetProperties();
2121// }
2122//
2123// if (target_properties_sp)
2124// {
2125// var_name_begin += ::strlen ("target.");
2126// const char *end_property = strchr(var_name_begin, '}');
2127// if (end_property)
2128// {
2129// ConstString property_name(var_name_begin, end_property - var_name_begin);
2130// std::string property_value (target_properties_sp->GetPropertyValue(property_name));
2131// if (!property_value.empty())
2132// {
2133// s.PutCString (property_value.c_str());
2134// var_success = true;
2135// }
2136// }
2137// }
Greg Clayton0603aa92010-10-04 01:05:56 +00002138 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2139 if (target)
Greg Clayton1b654882010-09-19 02:33:57 +00002140 {
Greg Clayton1b654882010-09-19 02:33:57 +00002141 var_name_begin += ::strlen ("target.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002142 if (IsToken (var_name_begin, "arch}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002143 {
2144 ArchSpec arch (target->GetArchitecture ());
2145 if (arch.IsValid())
2146 {
Greg Clayton64195a22011-02-23 00:35:02 +00002147 s.PutCString (arch.GetArchitectureName());
Greg Clayton1b654882010-09-19 02:33:57 +00002148 var_success = true;
2149 }
2150 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002151 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002152 {
2153 var_name_begin += ::strlen("script:");
2154 std::string script_name(var_name_begin,var_name_end);
2155 ScriptInterpreter* script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002156 if (RunScriptFormatKeyword (s, script_interpreter, target, script_name))
2157 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002158 }
Greg Clayton67cc0632012-08-22 17:17:09 +00002159 }
Greg Clayton1b654882010-09-19 02:33:57 +00002160 }
2161 break;
2162
2163
2164 case 'm':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002165 if (IsToken (var_name_begin, "module."))
Greg Clayton1b654882010-09-19 02:33:57 +00002166 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002167 if (sc && sc->module_sp.get())
Greg Clayton1b654882010-09-19 02:33:57 +00002168 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002169 Module *module = sc->module_sp.get();
Greg Clayton1b654882010-09-19 02:33:57 +00002170 var_name_begin += ::strlen ("module.");
2171
Michael Sartain0769b2b2013-07-30 16:44:36 +00002172 if (IsToken (var_name_begin, "file."))
Greg Clayton1b654882010-09-19 02:33:57 +00002173 {
2174 if (module->GetFileSpec())
2175 {
2176 var_name_begin += ::strlen ("file.");
2177
Michael Sartain0769b2b2013-07-30 16:44:36 +00002178 if (IsToken (var_name_begin, "basename}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002179 {
2180 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002181 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002182 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002183 else if (IsToken (var_name_begin, "fullpath}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002184 {
2185 format_file_spec = module->GetFileSpec();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002186 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002187 }
2188 }
2189 }
2190 }
2191 }
2192 break;
2193
2194
2195 case 'f':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002196 if (IsToken (var_name_begin, "file."))
Greg Clayton1b654882010-09-19 02:33:57 +00002197 {
2198 if (sc && sc->comp_unit != NULL)
2199 {
2200 var_name_begin += ::strlen ("file.");
2201
Michael Sartain0769b2b2013-07-30 16:44:36 +00002202 if (IsToken (var_name_begin, "basename}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002203 {
2204 format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002205 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002206 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002207 else if (IsToken (var_name_begin, "fullpath}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002208 {
2209 format_file_spec = *sc->comp_unit;
Sean Callanan9076c0f2013-10-04 21:35:29 +00002210 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002211 }
2212 }
2213 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002214 else if (IsToken (var_name_begin, "frame."))
Greg Clayton1b654882010-09-19 02:33:57 +00002215 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002216 if (exe_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00002217 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002218 StackFrame *frame = exe_ctx->GetFramePtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002219 if (frame)
Greg Clayton1b654882010-09-19 02:33:57 +00002220 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002221 var_name_begin += ::strlen ("frame.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002222 if (IsToken (var_name_begin, "index}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002223 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002224 s.Printf("%u", frame->GetFrameIndex());
2225 var_success = true;
2226 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002227 else if (IsToken (var_name_begin, "pc}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002228 {
2229 reg_kind = eRegisterKindGeneric;
2230 reg_num = LLDB_REGNUM_GENERIC_PC;
2231 var_success = true;
2232 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002233 else if (IsToken (var_name_begin, "sp}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002234 {
2235 reg_kind = eRegisterKindGeneric;
2236 reg_num = LLDB_REGNUM_GENERIC_SP;
2237 var_success = true;
2238 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002239 else if (IsToken (var_name_begin, "fp}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002240 {
2241 reg_kind = eRegisterKindGeneric;
2242 reg_num = LLDB_REGNUM_GENERIC_FP;
2243 var_success = true;
2244 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002245 else if (IsToken (var_name_begin, "flags}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002246 {
2247 reg_kind = eRegisterKindGeneric;
2248 reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2249 var_success = true;
2250 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002251 else if (IsToken (var_name_begin, "reg."))
Greg Claytonc14ee322011-09-22 04:58:26 +00002252 {
2253 reg_ctx = frame->GetRegisterContext().get();
2254 if (reg_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00002255 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002256 var_name_begin += ::strlen ("reg.");
2257 if (var_name_begin < var_name_end)
2258 {
2259 std::string reg_name (var_name_begin, var_name_end);
2260 reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2261 if (reg_info)
2262 var_success = true;
2263 }
Greg Clayton1b654882010-09-19 02:33:57 +00002264 }
2265 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002266 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002267 {
2268 var_name_begin += ::strlen("script:");
2269 std::string script_name(var_name_begin,var_name_end);
2270 ScriptInterpreter* script_interpreter = frame->GetThread()->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002271 if (RunScriptFormatKeyword (s, script_interpreter, frame, script_name))
2272 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002273 }
Greg Clayton1b654882010-09-19 02:33:57 +00002274 }
2275 }
2276 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002277 else if (IsToken (var_name_begin, "function."))
Greg Clayton1b654882010-09-19 02:33:57 +00002278 {
2279 if (sc && (sc->function != NULL || sc->symbol != NULL))
2280 {
2281 var_name_begin += ::strlen ("function.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002282 if (IsToken (var_name_begin, "id}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002283 {
2284 if (sc->function)
Daniel Malead01b2952012-11-29 21:49:15 +00002285 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
Greg Clayton1b654882010-09-19 02:33:57 +00002286 else
2287 s.Printf("symbol[%u]", sc->symbol->GetID());
2288
2289 var_success = true;
2290 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002291 else if (IsToken (var_name_begin, "name}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002292 {
2293 if (sc->function)
2294 cstr = sc->function->GetName().AsCString (NULL);
2295 else if (sc->symbol)
2296 cstr = sc->symbol->GetName().AsCString (NULL);
2297 if (cstr)
2298 {
2299 s.PutCString(cstr);
Greg Clayton0d9c9932010-10-04 17:26:49 +00002300
2301 if (sc->block)
2302 {
2303 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2304 if (inline_block)
2305 {
2306 const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2307 if (inline_info)
2308 {
2309 s.PutCString(" [inlined] ");
2310 inline_info->GetName().Dump(&s);
2311 }
2312 }
2313 }
Greg Clayton1b654882010-09-19 02:33:57 +00002314 var_success = true;
2315 }
2316 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002317 else if (IsToken (var_name_begin, "name-with-args}"))
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002318 {
2319 // Print the function name with arguments in it
2320
2321 if (sc->function)
2322 {
2323 var_success = true;
2324 ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2325 cstr = sc->function->GetName().AsCString (NULL);
2326 if (cstr)
2327 {
2328 const InlineFunctionInfo *inline_info = NULL;
2329 VariableListSP variable_list_sp;
2330 bool get_function_vars = true;
2331 if (sc->block)
2332 {
2333 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2334
2335 if (inline_block)
2336 {
2337 get_function_vars = false;
2338 inline_info = sc->block->GetInlinedFunctionInfo();
2339 if (inline_info)
2340 variable_list_sp = inline_block->GetBlockVariableList (true);
2341 }
2342 }
2343
2344 if (get_function_vars)
2345 {
2346 variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2347 }
2348
2349 if (inline_info)
2350 {
2351 s.PutCString (cstr);
2352 s.PutCString (" [inlined] ");
2353 cstr = inline_info->GetName().GetCString();
2354 }
2355
2356 VariableList args;
2357 if (variable_list_sp)
Enrico Granatacc7f9bf2013-05-08 20:27:37 +00002358 variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002359 if (args.GetSize() > 0)
2360 {
2361 const char *open_paren = strchr (cstr, '(');
Enrico Granatae4a4f5d2014-08-16 00:56:04 +00002362 const char *close_paren = nullptr;
2363 const char *generic = strchr(cstr, '<');
2364 // if before the arguments list begins there is a template sign
2365 // then scan to the end of the generic args before you try to find
2366 // the arguments list
2367 if (generic && open_paren && generic < open_paren)
2368 {
2369 int generic_depth = 1;
2370 ++generic;
2371 for (;
2372 *generic && generic_depth > 0;
2373 generic++)
2374 {
2375 if (*generic == '<')
2376 generic_depth++;
2377 if (*generic == '>')
2378 generic_depth--;
2379 }
2380 if (*generic)
2381 open_paren = strchr(generic, '(');
2382 else
2383 open_paren = nullptr;
2384 }
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002385 if (open_paren)
Greg Clayton855958c2013-03-26 01:45:43 +00002386 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002387 if (IsToken (open_paren, "(anonymous namespace)"))
Greg Clayton855958c2013-03-26 01:45:43 +00002388 {
2389 open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2390 if (open_paren)
2391 close_paren = strchr (open_paren, ')');
2392 }
2393 else
2394 close_paren = strchr (open_paren, ')');
2395 }
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002396
2397 if (open_paren)
2398 s.Write(cstr, open_paren - cstr + 1);
2399 else
2400 {
2401 s.PutCString (cstr);
2402 s.PutChar ('(');
2403 }
Greg Clayton5b6889b2012-01-18 21:56:18 +00002404 const size_t num_args = args.GetSize();
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002405 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2406 {
Enrico Granata894f7352014-03-25 22:03:52 +00002407 std::string buffer;
2408
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002409 VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2410 ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
Enrico Granata894f7352014-03-25 22:03:52 +00002411 const char *var_representation = nullptr;
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002412 const char *var_name = var_value_sp->GetName().GetCString();
Enrico Granata894f7352014-03-25 22:03:52 +00002413 if (var_value_sp->GetClangType().IsAggregateType() &&
2414 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp.get()))
2415 {
2416 static StringSummaryFormat format(TypeSummaryImpl::Flags()
2417 .SetHideItemNames(false)
2418 .SetShowMembersOneLiner(true),
2419 "");
2420 format.FormatObject(var_value_sp.get(), buffer);
2421 var_representation = buffer.c_str();
2422 }
2423 else
2424 var_representation = var_value_sp->GetValueAsCString();
Greg Clayton3b188b12012-12-10 22:26:34 +00002425 if (arg_idx > 0)
2426 s.PutCString (", ");
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002427 if (var_value_sp->GetError().Success())
Enrico Granatacc7f9bf2013-05-08 20:27:37 +00002428 {
Enrico Granata894f7352014-03-25 22:03:52 +00002429 if (var_representation)
2430 s.Printf ("%s=%s", var_name, var_representation);
Enrico Granatacc7f9bf2013-05-08 20:27:37 +00002431 else
2432 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2433 }
Greg Clayton3b188b12012-12-10 22:26:34 +00002434 else
2435 s.Printf ("%s=<unavailable>", var_name);
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002436 }
2437
2438 if (close_paren)
2439 s.PutCString (close_paren);
2440 else
2441 s.PutChar(')');
2442
2443 }
2444 else
2445 {
2446 s.PutCString(cstr);
2447 }
2448 }
2449 }
2450 else if (sc->symbol)
2451 {
2452 cstr = sc->symbol->GetName().AsCString (NULL);
2453 if (cstr)
2454 {
2455 s.PutCString(cstr);
2456 var_success = true;
2457 }
2458 }
2459 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002460 else if (IsToken (var_name_begin, "addr-offset}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002461 {
2462 var_success = addr != NULL;
2463 if (var_success)
2464 {
2465 format_addr = *addr;
2466 calculate_format_addr_function_offset = true;
2467 }
2468 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002469 else if (IsToken (var_name_begin, "line-offset}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002470 {
2471 var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2472 if (var_success)
2473 {
2474 format_addr = sc->line_entry.range.GetBaseAddress();
2475 calculate_format_addr_function_offset = true;
2476 }
2477 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002478 else if (IsToken (var_name_begin, "pc-offset}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002479 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002480 StackFrame *frame = exe_ctx->GetFramePtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002481 var_success = frame != NULL;
Greg Clayton1b654882010-09-19 02:33:57 +00002482 if (var_success)
2483 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002484 format_addr = frame->GetFrameCodeAddress();
Greg Clayton1b654882010-09-19 02:33:57 +00002485 calculate_format_addr_function_offset = true;
2486 }
2487 }
2488 }
2489 }
2490 break;
2491
2492 case 'l':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002493 if (IsToken (var_name_begin, "line."))
Greg Clayton1b654882010-09-19 02:33:57 +00002494 {
2495 if (sc && sc->line_entry.IsValid())
2496 {
2497 var_name_begin += ::strlen ("line.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002498 if (IsToken (var_name_begin, "file."))
Greg Clayton1b654882010-09-19 02:33:57 +00002499 {
2500 var_name_begin += ::strlen ("file.");
2501
Michael Sartain0769b2b2013-07-30 16:44:36 +00002502 if (IsToken (var_name_begin, "basename}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002503 {
2504 format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002505 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002506 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002507 else if (IsToken (var_name_begin, "fullpath}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002508 {
2509 format_file_spec = sc->line_entry.file;
Sean Callanan9076c0f2013-10-04 21:35:29 +00002510 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002511 }
2512 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002513 else if (IsTokenWithFormat (var_name_begin, "number", token_format, "%" PRIu64, exe_ctx, sc))
Greg Clayton1b654882010-09-19 02:33:57 +00002514 {
2515 var_success = true;
Michael Sartain0769b2b2013-07-30 16:44:36 +00002516 s.Printf(token_format.c_str(), (uint64_t)sc->line_entry.line);
Greg Clayton1b654882010-09-19 02:33:57 +00002517 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002518 else if ((IsToken (var_name_begin, "start-addr}")) ||
2519 (IsToken (var_name_begin, "end-addr}")))
Greg Clayton1b654882010-09-19 02:33:57 +00002520 {
2521 var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2522 if (var_success)
2523 {
2524 format_addr = sc->line_entry.range.GetBaseAddress();
2525 if (var_name_begin[0] == 'e')
2526 format_addr.Slide (sc->line_entry.range.GetByteSize());
2527 }
2528 }
2529 }
2530 }
2531 break;
2532 }
2533
2534 if (var_success)
2535 {
2536 // If format addr is valid, then we need to print an address
2537 if (reg_num != LLDB_INVALID_REGNUM)
2538 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002539 StackFrame *frame = exe_ctx->GetFramePtr();
Greg Clayton1b654882010-09-19 02:33:57 +00002540 // We have a register value to display...
2541 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2542 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002543 format_addr = frame->GetFrameCodeAddress();
Greg Clayton1b654882010-09-19 02:33:57 +00002544 }
2545 else
2546 {
2547 if (reg_ctx == NULL)
Greg Claytonc14ee322011-09-22 04:58:26 +00002548 reg_ctx = frame->GetRegisterContext().get();
Greg Clayton1b654882010-09-19 02:33:57 +00002549
2550 if (reg_ctx)
2551 {
2552 if (reg_kind != kNumRegisterKinds)
2553 reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2554 reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2555 var_success = reg_info != NULL;
2556 }
2557 }
2558 }
2559
2560 if (reg_info != NULL)
2561 {
Greg Clayton7349bd92011-05-09 20:18:18 +00002562 RegisterValue reg_value;
2563 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2564 if (var_success)
Greg Clayton1b654882010-09-19 02:33:57 +00002565 {
Greg Clayton9a8fa912011-05-15 04:12:07 +00002566 reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
Greg Clayton1b654882010-09-19 02:33:57 +00002567 }
2568 }
2569
2570 if (format_file_spec)
2571 {
2572 s << format_file_spec;
2573 }
2574
2575 // If format addr is valid, then we need to print an address
2576 if (format_addr.IsValid())
2577 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002578 var_success = false;
2579
Greg Clayton1b654882010-09-19 02:33:57 +00002580 if (calculate_format_addr_function_offset)
2581 {
2582 Address func_addr;
Greg Clayton1b654882010-09-19 02:33:57 +00002583
Greg Clayton0603aa92010-10-04 01:05:56 +00002584 if (sc)
2585 {
2586 if (sc->function)
Greg Clayton0d9c9932010-10-04 17:26:49 +00002587 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002588 func_addr = sc->function->GetAddressRange().GetBaseAddress();
Greg Clayton0d9c9932010-10-04 17:26:49 +00002589 if (sc->block)
2590 {
2591 // Check to make sure we aren't in an inline
2592 // function. If we are, use the inline block
2593 // range that contains "format_addr" since
2594 // blocks can be discontiguous.
2595 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2596 AddressRange inline_range;
2597 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2598 func_addr = inline_range.GetBaseAddress();
2599 }
2600 }
Greg Claytone7612132012-03-07 21:03:09 +00002601 else if (sc->symbol && sc->symbol->ValueIsAddress())
2602 func_addr = sc->symbol->GetAddress();
Greg Clayton0603aa92010-10-04 01:05:56 +00002603 }
2604
2605 if (func_addr.IsValid())
Greg Clayton1b654882010-09-19 02:33:57 +00002606 {
2607 if (func_addr.GetSection() == format_addr.GetSection())
2608 {
2609 addr_t func_file_addr = func_addr.GetFileAddress();
2610 addr_t addr_file_addr = format_addr.GetFileAddress();
2611 if (addr_file_addr > func_file_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002612 s.Printf(" + %" PRIu64, addr_file_addr - func_file_addr);
Greg Clayton1b654882010-09-19 02:33:57 +00002613 else if (addr_file_addr < func_file_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002614 s.Printf(" - %" PRIu64, func_file_addr - addr_file_addr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002615 var_success = true;
Greg Clayton1b654882010-09-19 02:33:57 +00002616 }
2617 else
Greg Clayton0603aa92010-10-04 01:05:56 +00002618 {
2619 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2620 if (target)
2621 {
2622 addr_t func_load_addr = func_addr.GetLoadAddress (target);
2623 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2624 if (addr_load_addr > func_load_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002625 s.Printf(" + %" PRIu64, addr_load_addr - func_load_addr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002626 else if (addr_load_addr < func_load_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002627 s.Printf(" - %" PRIu64, func_load_addr - addr_load_addr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002628 var_success = true;
2629 }
2630 }
Greg Clayton1b654882010-09-19 02:33:57 +00002631 }
2632 }
2633 else
2634 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002635 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
Greg Clayton1b654882010-09-19 02:33:57 +00002636 addr_t vaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0603aa92010-10-04 01:05:56 +00002637 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2638 vaddr = format_addr.GetLoadAddress (target);
Greg Clayton1b654882010-09-19 02:33:57 +00002639 if (vaddr == LLDB_INVALID_ADDRESS)
2640 vaddr = format_addr.GetFileAddress ();
2641
2642 if (vaddr != LLDB_INVALID_ADDRESS)
Greg Clayton0603aa92010-10-04 01:05:56 +00002643 {
Greg Clayton514487e2011-02-15 21:59:32 +00002644 int addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
Greg Clayton35f1a0d2010-11-19 04:16:11 +00002645 if (addr_width == 0)
2646 addr_width = 16;
Daniel Malead01b2952012-11-29 21:49:15 +00002647 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002648 var_success = true;
2649 }
Greg Clayton1b654882010-09-19 02:33:57 +00002650 }
2651 }
2652 }
2653
2654 if (var_success == false)
2655 success = false;
2656 }
2657 p = var_name_end;
2658 }
2659 else
2660 break;
2661 }
2662 else
2663 {
2664 // We got a dollar sign with no '{' after it, it must just be a dollar sign
2665 s.PutChar(*p);
2666 }
2667 }
2668 else if (*p == '\\')
2669 {
2670 ++p; // skip the slash
2671 switch (*p)
2672 {
2673 case 'a': s.PutChar ('\a'); break;
2674 case 'b': s.PutChar ('\b'); break;
2675 case 'f': s.PutChar ('\f'); break;
2676 case 'n': s.PutChar ('\n'); break;
2677 case 'r': s.PutChar ('\r'); break;
2678 case 't': s.PutChar ('\t'); break;
2679 case 'v': s.PutChar ('\v'); break;
2680 case '\'': s.PutChar ('\''); break;
2681 case '\\': s.PutChar ('\\'); break;
2682 case '0':
2683 // 1 to 3 octal chars
2684 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002685 // Make a string that can hold onto the initial zero char,
2686 // up to 3 octal digits, and a terminating NULL.
2687 char oct_str[5] = { 0, 0, 0, 0, 0 };
2688
2689 int i;
2690 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2691 oct_str[i] = p[i];
2692
2693 // We don't want to consume the last octal character since
2694 // the main for loop will do this for us, so we advance p by
2695 // one less than i (even if i is zero)
2696 p += i - 1;
2697 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2698 if (octal_value <= UINT8_MAX)
Greg Clayton1b654882010-09-19 02:33:57 +00002699 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002700 s.PutChar((char)octal_value);
Greg Clayton1b654882010-09-19 02:33:57 +00002701 }
Greg Clayton1b654882010-09-19 02:33:57 +00002702 }
2703 break;
2704
2705 case 'x':
2706 // hex number in the format
Greg Clayton0603aa92010-10-04 01:05:56 +00002707 if (isxdigit(p[1]))
Greg Clayton1b654882010-09-19 02:33:57 +00002708 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002709 ++p; // Skip the 'x'
Greg Clayton1b654882010-09-19 02:33:57 +00002710
Greg Clayton0603aa92010-10-04 01:05:56 +00002711 // Make a string that can hold onto two hex chars plus a
2712 // NULL terminator
2713 char hex_str[3] = { 0,0,0 };
2714 hex_str[0] = *p;
2715 if (isxdigit(p[1]))
Greg Clayton1b654882010-09-19 02:33:57 +00002716 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002717 ++p; // Skip the first of the two hex chars
2718 hex_str[1] = *p;
2719 }
2720
2721 unsigned long hex_value = strtoul (hex_str, NULL, 16);
2722 if (hex_value <= UINT8_MAX)
Greg Claytonc7bece562013-01-25 18:06:21 +00002723 s.PutChar ((char)hex_value);
Greg Clayton0603aa92010-10-04 01:05:56 +00002724 }
2725 else
2726 {
2727 s.PutChar('x');
Greg Clayton1b654882010-09-19 02:33:57 +00002728 }
2729 break;
2730
2731 default:
Greg Clayton0603aa92010-10-04 01:05:56 +00002732 // Just desensitize any other character by just printing what
2733 // came after the '\'
2734 s << *p;
Greg Clayton1b654882010-09-19 02:33:57 +00002735 break;
2736
2737 }
2738
2739 }
2740 }
2741 if (end)
2742 *end = p;
2743 return success;
2744}
2745
Michael Sartainc3ce7f272013-05-23 20:47:45 +00002746bool
2747Debugger::FormatPrompt
2748(
2749 const char *format,
2750 const SymbolContext *sc,
2751 const ExecutionContext *exe_ctx,
2752 const Address *addr,
2753 Stream &s,
2754 ValueObject* valobj
2755)
2756{
2757 bool use_color = exe_ctx ? exe_ctx->GetTargetRef().GetDebugger().GetUseColor() : true;
2758 std::string format_str = lldb_utility::ansi::FormatAnsiTerminalCodes (format, use_color);
2759 if (format_str.length())
2760 format = format_str.c_str();
2761 return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, valobj);
2762}
2763
Jim Ingham228063c2012-02-21 02:23:08 +00002764void
2765Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2766{
Jim Ingham4f02b222012-02-22 22:49:20 +00002767 // For simplicity's sake, I am not going to deal with how to close down any
2768 // open logging streams, I just redirect everything from here on out to the
2769 // callback.
Jim Ingham228063c2012-02-21 02:23:08 +00002770 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2771}
2772
2773bool
2774Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2775{
2776 Log::Callbacks log_callbacks;
2777
2778 StreamSP log_stream_sp;
Sean Callanan9a028512012-08-09 00:50:26 +00002779 if (m_log_callback_stream_sp)
Jim Ingham228063c2012-02-21 02:23:08 +00002780 {
2781 log_stream_sp = m_log_callback_stream_sp;
2782 // For now when using the callback mode you always get thread & timestamp.
2783 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2784 }
2785 else if (log_file == NULL || *log_file == '\0')
2786 {
Greg Clayton44d93782014-01-27 23:43:24 +00002787 log_stream_sp = GetOutputFile();
Jim Ingham228063c2012-02-21 02:23:08 +00002788 }
2789 else
2790 {
2791 LogStreamMap::iterator pos = m_log_streams.find(log_file);
Greg Claytonc1b2ccf2013-01-08 00:01:36 +00002792 if (pos != m_log_streams.end())
2793 log_stream_sp = pos->second.lock();
2794 if (!log_stream_sp)
Jim Ingham228063c2012-02-21 02:23:08 +00002795 {
2796 log_stream_sp.reset (new StreamFile (log_file));
2797 m_log_streams[log_file] = log_stream_sp;
2798 }
Jim Ingham228063c2012-02-21 02:23:08 +00002799 }
2800 assert (log_stream_sp.get());
2801
2802 if (log_options == 0)
2803 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2804
Greg Clayton57abc5d2013-05-10 21:47:16 +00002805 if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
Jim Ingham228063c2012-02-21 02:23:08 +00002806 {
2807 log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2808 return true;
2809 }
2810 else
2811 {
2812 LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2813 if (log_channel_sp)
2814 {
2815 if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2816 {
2817 return true;
2818 }
2819 else
2820 {
2821 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2822 return false;
2823 }
2824 }
2825 else
2826 {
2827 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2828 return false;
2829 }
2830 }
2831 return false;
2832}
2833
Greg Clayton9585fbf2013-03-19 00:20:55 +00002834SourceManager &
2835Debugger::GetSourceManager ()
2836{
2837 if (m_source_manager_ap.get() == NULL)
2838 m_source_manager_ap.reset (new SourceManager (shared_from_this()));
2839 return *m_source_manager_ap;
2840}
2841
2842
Greg Clayton44d93782014-01-27 23:43:24 +00002843
2844// This function handles events that were broadcast by the process.
2845void
2846Debugger::HandleBreakpointEvent (const EventSP &event_sp)
2847{
2848 using namespace lldb;
2849 const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
2850
2851// if (event_type & eBreakpointEventTypeAdded
2852// || event_type & eBreakpointEventTypeRemoved
2853// || event_type & eBreakpointEventTypeEnabled
2854// || event_type & eBreakpointEventTypeDisabled
2855// || event_type & eBreakpointEventTypeCommandChanged
2856// || event_type & eBreakpointEventTypeConditionChanged
2857// || event_type & eBreakpointEventTypeIgnoreChanged
2858// || event_type & eBreakpointEventTypeLocationsResolved)
2859// {
2860// // Don't do anything about these events, since the breakpoint commands already echo these actions.
2861// }
2862//
2863 if (event_type & eBreakpointEventTypeLocationsAdded)
2864 {
2865 uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
2866 if (num_new_locations > 0)
2867 {
2868 BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
2869 StreamFileSP output_sp (GetOutputFile());
2870 if (output_sp)
2871 {
2872 output_sp->Printf("%d location%s added to breakpoint %d\n",
2873 num_new_locations,
2874 num_new_locations == 1 ? "" : "s",
2875 breakpoint->GetID());
2876 RefreshTopIOHandler();
2877 }
2878 }
2879 }
2880// else if (event_type & eBreakpointEventTypeLocationsRemoved)
2881// {
2882// // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
2883// }
2884// else if (event_type & eBreakpointEventTypeLocationsResolved)
2885// {
2886// // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
2887// }
2888}
2889
2890size_t
2891Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
2892{
2893 size_t total_bytes = 0;
2894 if (stream == NULL)
2895 stream = GetOutputFile().get();
2896
2897 if (stream)
2898 {
2899 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
2900 if (process == NULL)
2901 {
2902 TargetSP target_sp = GetTargetList().GetSelectedTarget();
2903 if (target_sp)
2904 process = target_sp->GetProcessSP().get();
2905 }
2906 if (process)
2907 {
2908 Error error;
2909 size_t len;
2910 char stdio_buffer[1024];
2911 while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2912 {
2913 stream->Write(stdio_buffer, len);
2914 total_bytes += len;
2915 }
2916 }
2917 stream->Flush();
2918 }
2919 return total_bytes;
2920}
2921
2922size_t
2923Debugger::GetProcessSTDERR (Process *process, Stream *stream)
2924{
2925 size_t total_bytes = 0;
2926 if (stream == NULL)
2927 stream = GetOutputFile().get();
2928
2929 if (stream)
2930 {
2931 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2932 if (process == NULL)
2933 {
2934 TargetSP target_sp = GetTargetList().GetSelectedTarget();
2935 if (target_sp)
2936 process = target_sp->GetProcessSP().get();
2937 }
2938 if (process)
2939 {
2940 Error error;
2941 size_t len;
2942 char stdio_buffer[1024];
2943 while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2944 {
2945 stream->Write(stdio_buffer, len);
2946 total_bytes += len;
2947 }
2948 }
2949 stream->Flush();
2950 }
2951 return total_bytes;
2952}
2953
2954// This function handles events that were broadcast by the process.
2955void
2956Debugger::HandleProcessEvent (const EventSP &event_sp)
2957{
2958 using namespace lldb;
2959 const uint32_t event_type = event_sp->GetType();
2960 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
2961
Greg Claytonb4874f12014-02-28 18:22:24 +00002962 StreamString output_stream;
2963 StreamString error_stream;
Greg Clayton44d93782014-01-27 23:43:24 +00002964 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00002965
Greg Claytonb4874f12014-02-28 18:22:24 +00002966 if (!gui_enabled)
2967 {
2968 bool pop_process_io_handler = false;
2969 assert (process_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00002970
Greg Claytonb4874f12014-02-28 18:22:24 +00002971 if (event_type & Process::eBroadcastBitSTDOUT || event_type & Process::eBroadcastBitStateChanged)
Greg Clayton44d93782014-01-27 23:43:24 +00002972 {
Greg Claytonb4874f12014-02-28 18:22:24 +00002973 GetProcessSTDOUT (process_sp.get(), &output_stream);
2974 }
2975
2976 if (event_type & Process::eBroadcastBitSTDERR || event_type & Process::eBroadcastBitStateChanged)
2977 {
2978 GetProcessSTDERR (process_sp.get(), &error_stream);
2979 }
2980
2981 if (event_type & Process::eBroadcastBitStateChanged)
2982 {
2983
2984 // Drain all stout and stderr so we don't see any output come after
2985 // we print our prompts
Greg Clayton44d93782014-01-27 23:43:24 +00002986 // Something changed in the process; get the event and report the process's current status and location to
2987 // the user.
2988 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
2989 if (event_state == eStateInvalid)
2990 return;
2991
2992 switch (event_state)
2993 {
2994 case eStateInvalid:
2995 case eStateUnloaded:
2996 case eStateConnected:
2997 case eStateAttaching:
2998 case eStateLaunching:
2999 case eStateStepping:
3000 case eStateDetached:
3001 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003002 output_stream.Printf("Process %" PRIu64 " %s\n",
3003 process_sp->GetID(),
3004 StateAsCString (event_state));
3005
3006 if (event_state == eStateDetached)
3007 pop_process_io_handler = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003008 }
3009 break;
3010
3011 case eStateRunning:
3012 // Don't be chatty when we run...
3013 break;
3014
3015 case eStateExited:
Greg Claytonb4874f12014-02-28 18:22:24 +00003016 process_sp->GetStatus(output_stream);
3017 pop_process_io_handler = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003018 break;
3019
3020 case eStateStopped:
3021 case eStateCrashed:
3022 case eStateSuspended:
3023 // Make sure the program hasn't been auto-restarted:
3024 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
3025 {
3026 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
3027 if (num_reasons > 0)
3028 {
3029 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
3030 if (num_reasons == 1)
3031 {
3032 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
Greg Claytonb4874f12014-02-28 18:22:24 +00003033 output_stream.Printf("Process %" PRIu64 " stopped and restarted: %s\n",
3034 process_sp->GetID(),
3035 reason ? reason : "<UNKNOWN REASON>");
Greg Clayton44d93782014-01-27 23:43:24 +00003036 }
3037 else
3038 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003039 output_stream.Printf("Process %" PRIu64 " stopped and restarted, reasons:\n",
3040 process_sp->GetID());
Greg Clayton44d93782014-01-27 23:43:24 +00003041
3042
3043 for (size_t i = 0; i < num_reasons; i++)
3044 {
3045 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
Greg Claytonb4874f12014-02-28 18:22:24 +00003046 output_stream.Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
Greg Clayton44d93782014-01-27 23:43:24 +00003047 }
3048 }
3049 }
3050 }
3051 else
3052 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003053 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
Greg Clayton44d93782014-01-27 23:43:24 +00003054 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003055 ThreadList &thread_list = process_sp->GetThreadList();
3056 Mutex::Locker locker (thread_list.GetMutex());
3057
3058 ThreadSP curr_thread (thread_list.GetSelectedThread());
3059 ThreadSP thread;
3060 StopReason curr_thread_stop_reason = eStopReasonInvalid;
3061 if (curr_thread)
3062 curr_thread_stop_reason = curr_thread->GetStopReason();
3063 if (!curr_thread ||
3064 !curr_thread->IsValid() ||
3065 curr_thread_stop_reason == eStopReasonInvalid ||
3066 curr_thread_stop_reason == eStopReasonNone)
Greg Clayton44d93782014-01-27 23:43:24 +00003067 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003068 // Prefer a thread that has just completed its plan over another thread as current thread.
3069 ThreadSP plan_thread;
3070 ThreadSP other_thread;
3071 const size_t num_threads = thread_list.GetSize();
3072 size_t i;
3073 for (i = 0; i < num_threads; ++i)
Greg Clayton44d93782014-01-27 23:43:24 +00003074 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003075 thread = thread_list.GetThreadAtIndex(i);
3076 StopReason thread_stop_reason = thread->GetStopReason();
3077 switch (thread_stop_reason)
3078 {
3079 case eStopReasonInvalid:
3080 case eStopReasonNone:
3081 break;
3082
3083 case eStopReasonTrace:
3084 case eStopReasonBreakpoint:
3085 case eStopReasonWatchpoint:
3086 case eStopReasonSignal:
3087 case eStopReasonException:
3088 case eStopReasonExec:
3089 case eStopReasonThreadExiting:
3090 if (!other_thread)
3091 other_thread = thread;
3092 break;
3093 case eStopReasonPlanComplete:
3094 if (!plan_thread)
3095 plan_thread = thread;
3096 break;
3097 }
3098 }
3099 if (plan_thread)
3100 thread_list.SetSelectedThreadByID (plan_thread->GetID());
3101 else if (other_thread)
3102 thread_list.SetSelectedThreadByID (other_thread->GetID());
3103 else
3104 {
3105 if (curr_thread && curr_thread->IsValid())
3106 thread = curr_thread;
3107 else
3108 thread = thread_list.GetThreadAtIndex(0);
3109
3110 if (thread)
3111 thread_list.SetSelectedThreadByID (thread->GetID());
Greg Clayton44d93782014-01-27 23:43:24 +00003112 }
3113 }
Greg Clayton44d93782014-01-27 23:43:24 +00003114 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00003115 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
3116 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
3117 // have a hard time restarting the process.
Greg Clayton44d93782014-01-27 23:43:24 +00003118
3119 if (GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
3120 {
3121 const bool only_threads_with_stop_reason = true;
3122 const uint32_t start_frame = 0;
3123 const uint32_t num_frames = 1;
3124 const uint32_t num_frames_with_source = 1;
Greg Claytonb4874f12014-02-28 18:22:24 +00003125 process_sp->GetStatus(output_stream);
3126 process_sp->GetThreadStatus (output_stream,
Greg Clayton44d93782014-01-27 23:43:24 +00003127 only_threads_with_stop_reason,
3128 start_frame,
3129 num_frames,
3130 num_frames_with_source);
3131 }
3132 else
3133 {
3134 uint32_t target_idx = GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
3135 if (target_idx != UINT32_MAX)
Greg Claytonb4874f12014-02-28 18:22:24 +00003136 output_stream.Printf ("Target %d: (", target_idx);
Greg Clayton44d93782014-01-27 23:43:24 +00003137 else
Greg Claytonb4874f12014-02-28 18:22:24 +00003138 output_stream.Printf ("Target <unknown index>: (");
3139 process_sp->GetTarget().Dump (&output_stream, eDescriptionLevelBrief);
3140 output_stream.Printf (") stopped.\n");
Greg Clayton44d93782014-01-27 23:43:24 +00003141 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003142
3143 // Pop the process IO handler
3144 pop_process_io_handler = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003145 }
3146 break;
3147 }
3148 }
Greg Clayton44d93782014-01-27 23:43:24 +00003149
Greg Claytonb4874f12014-02-28 18:22:24 +00003150 if (output_stream.GetSize() || error_stream.GetSize())
3151 {
3152 StreamFileSP error_stream_sp (GetOutputFile());
Greg Clayton6fea17e2014-03-03 19:15:20 +00003153 bool top_io_handler_hid = false;
3154
3155 if (process_sp->ProcessIOHandlerIsActive() == false)
3156 top_io_handler_hid = HideTopIOHandler();
Greg Claytonb4874f12014-02-28 18:22:24 +00003157
3158 if (output_stream.GetSize())
3159 {
3160 StreamFileSP output_stream_sp (GetOutputFile());
3161 if (output_stream_sp)
3162 output_stream_sp->Write (output_stream.GetData(), output_stream.GetSize());
3163 }
3164
3165 if (error_stream.GetSize())
3166 {
3167 StreamFileSP error_stream_sp (GetErrorFile());
3168 if (error_stream_sp)
3169 error_stream_sp->Write (error_stream.GetData(), error_stream.GetSize());
3170 }
3171
3172 if (top_io_handler_hid)
3173 RefreshTopIOHandler();
3174 }
3175
3176 if (pop_process_io_handler)
3177 process_sp->PopProcessIOHandler();
3178 }
Greg Clayton44d93782014-01-27 23:43:24 +00003179}
3180
3181void
3182Debugger::HandleThreadEvent (const EventSP &event_sp)
3183{
3184 // At present the only thread event we handle is the Frame Changed event,
3185 // and all we do for that is just reprint the thread status for that thread.
3186 using namespace lldb;
3187 const uint32_t event_type = event_sp->GetType();
3188 if (event_type == Thread::eBroadcastBitStackChanged ||
3189 event_type == Thread::eBroadcastBitThreadSelected )
3190 {
3191 ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
3192 if (thread_sp)
3193 {
3194 HideTopIOHandler();
3195 StreamFileSP stream_sp (GetOutputFile());
3196 thread_sp->GetStatus(*stream_sp, 0, 1, 1);
3197 RefreshTopIOHandler();
3198 }
3199 }
3200}
3201
3202bool
3203Debugger::IsForwardingEvents ()
3204{
3205 return (bool)m_forward_listener_sp;
3206}
3207
3208void
3209Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
3210{
3211 m_forward_listener_sp = listener_sp;
3212}
3213
3214void
3215Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
3216{
3217 m_forward_listener_sp.reset();
3218}
3219
3220
3221void
3222Debugger::DefaultEventHandler()
3223{
3224 Listener& listener(GetListener());
3225 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
3226 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
3227 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
3228 BroadcastEventSpec target_event_spec (broadcaster_class_target,
3229 Target::eBroadcastBitBreakpointChanged);
3230
3231 BroadcastEventSpec process_event_spec (broadcaster_class_process,
3232 Process::eBroadcastBitStateChanged |
3233 Process::eBroadcastBitSTDOUT |
3234 Process::eBroadcastBitSTDERR);
3235
3236 BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
3237 Thread::eBroadcastBitStackChanged |
3238 Thread::eBroadcastBitThreadSelected );
3239
3240 listener.StartListeningForEventSpec (*this, target_event_spec);
3241 listener.StartListeningForEventSpec (*this, process_event_spec);
3242 listener.StartListeningForEventSpec (*this, thread_event_spec);
3243 listener.StartListeningForEvents (m_command_interpreter_ap.get(),
3244 CommandInterpreter::eBroadcastBitQuitCommandReceived |
3245 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
3246 CommandInterpreter::eBroadcastBitAsynchronousErrorData );
3247
3248 bool done = false;
3249 while (!done)
3250 {
3251// Mutex::Locker locker;
3252// if (locker.TryLock(m_input_reader_stack.GetMutex()))
3253// {
3254// if (m_input_reader_stack.IsEmpty())
3255// break;
3256// }
3257//
3258 EventSP event_sp;
3259 if (listener.WaitForEvent(NULL, event_sp))
3260 {
3261 if (event_sp)
3262 {
3263 Broadcaster *broadcaster = event_sp->GetBroadcaster();
3264 if (broadcaster)
3265 {
3266 uint32_t event_type = event_sp->GetType();
3267 ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
3268 if (broadcaster_class == broadcaster_class_process)
3269 {
3270 HandleProcessEvent (event_sp);
3271 }
3272 else if (broadcaster_class == broadcaster_class_target)
3273 {
3274 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
3275 {
3276 HandleBreakpointEvent (event_sp);
3277 }
3278 }
3279 else if (broadcaster_class == broadcaster_class_thread)
3280 {
3281 HandleThreadEvent (event_sp);
3282 }
3283 else if (broadcaster == m_command_interpreter_ap.get())
3284 {
3285 if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
3286 {
3287 done = true;
3288 }
3289 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
3290 {
3291 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3292 if (data && data[0])
3293 {
3294 StreamFileSP error_sp (GetErrorFile());
3295 if (error_sp)
3296 {
3297 HideTopIOHandler();
3298 error_sp->PutCString(data);
3299 error_sp->Flush();
3300 RefreshTopIOHandler();
3301 }
3302 }
3303 }
3304 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
3305 {
3306 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3307 if (data && data[0])
3308 {
3309 StreamFileSP output_sp (GetOutputFile());
3310 if (output_sp)
3311 {
3312 HideTopIOHandler();
3313 output_sp->PutCString(data);
3314 output_sp->Flush();
3315 RefreshTopIOHandler();
3316 }
3317 }
3318 }
3319 }
3320 }
3321
3322 if (m_forward_listener_sp)
3323 m_forward_listener_sp->AddEvent(event_sp);
3324 }
3325 }
3326 }
3327}
3328
3329lldb::thread_result_t
3330Debugger::EventHandlerThread (lldb::thread_arg_t arg)
3331{
3332 ((Debugger *)arg)->DefaultEventHandler();
3333 return NULL;
3334}
3335
3336bool
3337Debugger::StartEventHandlerThread()
3338{
Zachary Turner39de3112014-09-09 20:54:56 +00003339 if (m_event_handler_thread.GetState() != eThreadStateRunning)
3340 m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread, this, NULL);
3341 return m_event_handler_thread.GetState() == eThreadStateRunning;
Greg Clayton44d93782014-01-27 23:43:24 +00003342}
3343
3344void
3345Debugger::StopEventHandlerThread()
3346{
Zachary Turner39de3112014-09-09 20:54:56 +00003347 if (m_event_handler_thread.GetState() == eThreadStateRunning)
Greg Clayton44d93782014-01-27 23:43:24 +00003348 {
3349 GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
Zachary Turner39de3112014-09-09 20:54:56 +00003350 m_event_handler_thread.Join(nullptr);
3351 m_event_handler_thread.Reset();
Greg Clayton44d93782014-01-27 23:43:24 +00003352 }
3353}
3354
3355
3356lldb::thread_result_t
3357Debugger::IOHandlerThread (lldb::thread_arg_t arg)
3358{
3359 Debugger *debugger = (Debugger *)arg;
3360 debugger->ExecuteIOHanders();
3361 debugger->StopEventHandlerThread();
3362 return NULL;
3363}
3364
3365bool
3366Debugger::StartIOHandlerThread()
3367{
Zachary Turner39de3112014-09-09 20:54:56 +00003368 if (m_io_handler_thread.GetState() != eThreadStateRunning)
3369 m_io_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.io-handler", IOHandlerThread, this, NULL);
3370 return m_io_handler_thread.GetState() == eThreadStateRunning;
Greg Clayton44d93782014-01-27 23:43:24 +00003371}
3372
3373void
3374Debugger::StopIOHandlerThread()
3375{
Zachary Turner39de3112014-09-09 20:54:56 +00003376 if (m_io_handler_thread.GetState() == eThreadStateRunning)
Greg Clayton44d93782014-01-27 23:43:24 +00003377 {
3378 if (m_input_file_sp)
3379 m_input_file_sp->GetFile().Close();
Zachary Turner39de3112014-09-09 20:54:56 +00003380 m_io_handler_thread.Join(nullptr);
3381 m_io_handler_thread.Reset();
Greg Clayton44d93782014-01-27 23:43:24 +00003382 }
3383}
3384
3385