blob: 178296347677bc965b14516f8eb0c64668fa6683 [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"
Greg Clayton66111032010-06-23 01:19:29 +000039#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000040#include "lldb/Interpreter/OptionValueSInt64.h"
41#include "lldb/Interpreter/OptionValueString.h"
Greg Clayton1f746072012-08-29 21:13:06 +000042#include "lldb/Symbol/ClangASTContext.h"
43#include "lldb/Symbol/CompileUnit.h"
44#include "lldb/Symbol/Function.h"
45#include "lldb/Symbol/Symbol.h"
Greg Clayton6d3dbf52012-01-13 08:39:16 +000046#include "lldb/Symbol/VariableList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Target/TargetList.h"
48#include "lldb/Target/Process.h"
Greg Clayton1b654882010-09-19 02:33:57 +000049#include "lldb/Target/RegisterContext.h"
Greg Clayton5fb8f792013-12-02 19:35:49 +000050#include "lldb/Target/SectionLoadList.h"
Greg Clayton1b654882010-09-19 02:33:57 +000051#include "lldb/Target/StopInfo.h"
Enrico Granata84a53df2013-05-20 22:29:23 +000052#include "lldb/Target/Target.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/Thread.h"
Greg Clayton5a314712011-10-14 07:41:33 +000054#include "lldb/Utility/AnsiTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055
Zachary Turner58a559c2014-08-27 20:15:09 +000056#include "llvm/Support/DynamicLibrary.h"
57
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058using namespace lldb;
59using namespace lldb_private;
60
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061
Greg Clayton1b654882010-09-19 02:33:57 +000062static uint32_t g_shared_debugger_refcount = 0;
Caroline Ticeebc1bb22010-06-30 16:22:25 +000063static lldb::user_id_t g_unique_id = 1;
64
Greg Clayton1b654882010-09-19 02:33:57 +000065#pragma mark Static Functions
66
67static Mutex &
68GetDebuggerListMutex ()
69{
70 static Mutex g_mutex(Mutex::eMutexTypeRecursive);
71 return g_mutex;
72}
73
74typedef std::vector<DebuggerSP> DebuggerList;
75
76static DebuggerList &
77GetDebuggerList()
78{
79 // hide the static debugger list inside a singleton accessor to avoid
Bruce Mitchener6a7f3332014-06-27 02:42:12 +000080 // global init constructors
Greg Clayton1b654882010-09-19 02:33:57 +000081 static DebuggerList g_list;
82 return g_list;
83}
Greg Claytone372b982011-11-21 21:44:34 +000084
85OptionEnumValueElement
Greg Clayton67cc0632012-08-22 17:17:09 +000086g_show_disassembly_enum_values[] =
Greg Claytone372b982011-11-21 21:44:34 +000087{
Greg Clayton67cc0632012-08-22 17:17:09 +000088 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."},
89 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
90 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."},
Greg Claytone372b982011-11-21 21:44:34 +000091 { 0, NULL, NULL }
92};
93
Greg Clayton67cc0632012-08-22 17:17:09 +000094OptionEnumValueElement
95g_language_enumerators[] =
96{
97 { eScriptLanguageNone, "none", "Disable scripting languages."},
98 { eScriptLanguagePython, "python", "Select python as the default scripting language."},
99 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."},
Greg Claytona12993c2012-09-13 23:03:20 +0000100 { 0, NULL, NULL }
Greg Clayton67cc0632012-08-22 17:17:09 +0000101};
Greg Claytone372b982011-11-21 21:44:34 +0000102
Greg Clayton67cc0632012-08-22 17:17:09 +0000103#define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
104#define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
105
Michael Sartain0769b2b2013-07-30 16:44:36 +0000106#define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
Greg Clayton67cc0632012-08-22 17:17:09 +0000107 "{, ${frame.pc}}"\
108 MODULE_WITH_FUNC\
109 FILE_AND_LINE\
Michael Sartain0769b2b2013-07-30 16:44:36 +0000110 "{, name = '${thread.name}'}"\
111 "{, queue = '${thread.queue}'}"\
Jason Molenda705b1802014-06-13 02:37:02 +0000112 "{, activity = '${thread.info.activity.name}'}" \
113 "{, ${thread.info.trace_messages} messages}" \
Greg Clayton67cc0632012-08-22 17:17:09 +0000114 "{, stop reason = ${thread.stop-reason}}"\
115 "{\\nReturn value: ${thread.return-value}}"\
Jim Ingham30fadaf2014-07-08 01:07:32 +0000116 "{\\nCompleted expression: ${thread.completed-expression}}"\
Greg Clayton67cc0632012-08-22 17:17:09 +0000117 "\\n"
118
119#define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
120 MODULE_WITH_FUNC\
121 FILE_AND_LINE\
122 "\\n"
123
124
125
Greg Clayton754a9362012-08-23 00:22:02 +0000126static PropertyDefinition
127g_properties[] =
Greg Clayton67cc0632012-08-22 17:17:09 +0000128{
129{ "auto-confirm", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
130{ "frame-format", OptionValue::eTypeString , true, 0 , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
131{ "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 +0000132{ "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000133{ "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
134{ "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
135{ "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
136{ "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." },
137{ "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." },
138{ "term-width", OptionValue::eTypeSInt64 , true, 80 , NULL, NULL, "The maximum number of columns to use for displaying text." },
139{ "thread-format", OptionValue::eTypeString , true, 0 , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
140{ "use-external-editor", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Whether to use an external editor or not." },
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000141{ "use-color", OptionValue::eTypeBoolean, true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
Enrico Granata90a8db32013-10-31 21:01:07 +0000142{ "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 +0000143
144 { NULL, OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
Greg Clayton67cc0632012-08-22 17:17:09 +0000145};
146
147enum
148{
149 ePropertyAutoConfirm = 0,
150 ePropertyFrameFormat,
151 ePropertyNotiftVoid,
152 ePropertyPrompt,
153 ePropertyScriptLanguage,
154 ePropertyStopDisassemblyCount,
155 ePropertyStopDisassemblyDisplay,
156 ePropertyStopLineCountAfter,
157 ePropertyStopLineCountBefore,
158 ePropertyTerminalWidth,
159 ePropertyThreadFormat,
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000160 ePropertyUseExternalEditor,
161 ePropertyUseColor,
Enrico Granata90a8db32013-10-31 21:01:07 +0000162 ePropertyAutoOneLineSummaries
Greg Clayton67cc0632012-08-22 17:17:09 +0000163};
164
Greg Clayton5fb8f792013-12-02 19:35:49 +0000165Debugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
Greg Clayton4c054102012-09-01 00:38:36 +0000166
167Error
168Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
169 VarSetOperationType op,
170 const char *property_path,
171 const char *value)
172{
Enrico Granata84a53df2013-05-20 22:29:23 +0000173 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
174 TargetSP target_sp;
Enrico Granata397ddd52013-05-21 20:13:34 +0000175 LoadScriptFromSymFile load_script_old_value;
Enrico Granata84a53df2013-05-20 22:29:23 +0000176 if (is_load_script && exe_ctx->GetTargetSP())
177 {
178 target_sp = exe_ctx->GetTargetSP();
179 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
180 }
Greg Clayton4c054102012-09-01 00:38:36 +0000181 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
182 if (error.Success())
183 {
Enrico Granata84a53df2013-05-20 22:29:23 +0000184 // FIXME it would be nice to have "on-change" callbacks for properties
Greg Clayton4c054102012-09-01 00:38:36 +0000185 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
186 {
187 const char *new_prompt = GetPrompt();
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000188 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
189 if (str.length())
190 new_prompt = str.c_str();
Greg Clayton44d93782014-01-27 23:43:24 +0000191 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton4c054102012-09-01 00:38:36 +0000192 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
193 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
194 }
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000195 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
196 {
197 // use-color changed. Ping the prompt so it can reset the ansi terminal codes.
198 SetPrompt (GetPrompt());
199 }
Enrico Granata397ddd52013-05-21 20:13:34 +0000200 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
Enrico Granata84a53df2013-05-20 22:29:23 +0000201 {
Enrico Granata397ddd52013-05-21 20:13:34 +0000202 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
Enrico Granata84a53df2013-05-20 22:29:23 +0000203 {
204 std::list<Error> errors;
Enrico Granata97303392013-05-21 00:00:30 +0000205 StreamString feedback_stream;
206 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
Enrico Granata84a53df2013-05-20 22:29:23 +0000207 {
Greg Clayton44d93782014-01-27 23:43:24 +0000208 StreamFileSP stream_sp (GetErrorFile());
209 if (stream_sp)
Enrico Granata84a53df2013-05-20 22:29:23 +0000210 {
Greg Clayton44d93782014-01-27 23:43:24 +0000211 for (auto error : errors)
212 {
213 stream_sp->Printf("%s\n",error.AsCString());
214 }
215 if (feedback_stream.GetSize())
216 stream_sp->Printf("%s",feedback_stream.GetData());
Enrico Granata84a53df2013-05-20 22:29:23 +0000217 }
218 }
219 }
220 }
Greg Clayton4c054102012-09-01 00:38:36 +0000221 }
222 return error;
223}
224
Greg Clayton67cc0632012-08-22 17:17:09 +0000225bool
226Debugger::GetAutoConfirm () const
227{
228 const uint32_t idx = ePropertyAutoConfirm;
Greg Clayton754a9362012-08-23 00:22:02 +0000229 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000230}
231
232const char *
233Debugger::GetFrameFormat() const
234{
235 const uint32_t idx = ePropertyFrameFormat;
Greg Clayton754a9362012-08-23 00:22:02 +0000236 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000237}
238
239bool
240Debugger::GetNotifyVoid () const
241{
242 const uint32_t idx = ePropertyNotiftVoid;
Greg Clayton754a9362012-08-23 00:22:02 +0000243 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000244}
245
246const char *
247Debugger::GetPrompt() const
248{
249 const uint32_t idx = ePropertyPrompt;
Greg Clayton754a9362012-08-23 00:22:02 +0000250 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000251}
252
253void
254Debugger::SetPrompt(const char *p)
255{
256 const uint32_t idx = ePropertyPrompt;
257 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
258 const char *new_prompt = GetPrompt();
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000259 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
260 if (str.length())
261 new_prompt = str.c_str();
Greg Clayton44d93782014-01-27 23:43:24 +0000262 GetCommandInterpreter().UpdatePrompt(new_prompt);
Greg Clayton67cc0632012-08-22 17:17:09 +0000263}
264
265const char *
266Debugger::GetThreadFormat() const
267{
268 const uint32_t idx = ePropertyThreadFormat;
Greg Clayton754a9362012-08-23 00:22:02 +0000269 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000270}
271
272lldb::ScriptLanguage
273Debugger::GetScriptLanguage() const
274{
275 const uint32_t idx = ePropertyScriptLanguage;
Greg Clayton754a9362012-08-23 00:22:02 +0000276 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000277}
278
279bool
280Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
281{
282 const uint32_t idx = ePropertyScriptLanguage;
283 return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
284}
285
286uint32_t
287Debugger::GetTerminalWidth () const
288{
289 const uint32_t idx = ePropertyTerminalWidth;
Greg Clayton754a9362012-08-23 00:22:02 +0000290 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000291}
292
293bool
294Debugger::SetTerminalWidth (uint32_t term_width)
295{
296 const uint32_t idx = ePropertyTerminalWidth;
297 return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
298}
299
300bool
301Debugger::GetUseExternalEditor () const
302{
303 const uint32_t idx = ePropertyUseExternalEditor;
Greg Clayton754a9362012-08-23 00:22:02 +0000304 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000305}
306
307bool
308Debugger::SetUseExternalEditor (bool b)
309{
310 const uint32_t idx = ePropertyUseExternalEditor;
311 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
312}
313
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000314bool
315Debugger::GetUseColor () const
316{
317 const uint32_t idx = ePropertyUseColor;
318 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
319}
320
321bool
322Debugger::SetUseColor (bool b)
323{
324 const uint32_t idx = ePropertyUseColor;
325 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
326 SetPrompt (GetPrompt());
327 return ret;
328}
329
Greg Clayton67cc0632012-08-22 17:17:09 +0000330uint32_t
331Debugger::GetStopSourceLineCount (bool before) const
332{
333 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
Greg Clayton754a9362012-08-23 00:22:02 +0000334 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000335}
336
337Debugger::StopDisassemblyType
338Debugger::GetStopDisassemblyDisplay () const
339{
340 const uint32_t idx = ePropertyStopDisassemblyDisplay;
Greg Clayton754a9362012-08-23 00:22:02 +0000341 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000342}
343
344uint32_t
345Debugger::GetDisassemblyLineCount () const
346{
347 const uint32_t idx = ePropertyStopDisassemblyCount;
Greg Clayton754a9362012-08-23 00:22:02 +0000348 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +0000349}
Greg Claytone372b982011-11-21 21:44:34 +0000350
Enrico Granata553fad52013-10-25 23:09:40 +0000351bool
Enrico Granata90a8db32013-10-31 21:01:07 +0000352Debugger::GetAutoOneLineSummaries () const
Enrico Granata553fad52013-10-25 23:09:40 +0000353{
Enrico Granata90a8db32013-10-31 21:01:07 +0000354 const uint32_t idx = ePropertyAutoOneLineSummaries;
Enrico Granata553fad52013-10-25 23:09:40 +0000355 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
356
357}
358
Greg Clayton1b654882010-09-19 02:33:57 +0000359#pragma mark Debugger
360
Greg Clayton67cc0632012-08-22 17:17:09 +0000361//const DebuggerPropertiesSP &
362//Debugger::GetSettings() const
363//{
364// return m_properties_sp;
365//}
366//
Greg Clayton99d0faf2010-11-18 23:32:35 +0000367
Caroline Tice2f88aad2011-01-14 00:29:16 +0000368int
369Debugger::TestDebuggerRefCount ()
370{
371 return g_shared_debugger_refcount;
372}
373
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374void
Greg Clayton5fb8f792013-12-02 19:35:49 +0000375Debugger::Initialize (LoadPluginCallbackType load_plugin_callback)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376{
Greg Clayton5fb8f792013-12-02 19:35:49 +0000377 g_load_plugin_callback = load_plugin_callback;
Greg Claytonc15f55e2012-03-30 20:53:46 +0000378 if (g_shared_debugger_refcount++ == 0)
Greg Claytondbe54502010-11-19 03:46:01 +0000379 lldb_private::Initialize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380}
381
382void
383Debugger::Terminate ()
384{
Greg Clayton66111032010-06-23 01:19:29 +0000385 if (g_shared_debugger_refcount > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 {
Greg Clayton66111032010-06-23 01:19:29 +0000387 g_shared_debugger_refcount--;
388 if (g_shared_debugger_refcount == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000389 {
Greg Claytondbe54502010-11-19 03:46:01 +0000390 lldb_private::WillTerminate();
391 lldb_private::Terminate();
Caroline Tice6760a512011-01-17 21:55:19 +0000392
393 // Clear our master list of debugger objects
394 Mutex::Locker locker (GetDebuggerListMutex ());
395 GetDebuggerList().clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397 }
398}
399
Caroline Tice20bd37f2011-03-10 22:14:10 +0000400void
401Debugger::SettingsInitialize ()
402{
Greg Clayton6920b522012-08-22 18:39:03 +0000403 Target::SettingsInitialize ();
Caroline Tice20bd37f2011-03-10 22:14:10 +0000404}
405
406void
407Debugger::SettingsTerminate ()
408{
Greg Clayton6920b522012-08-22 18:39:03 +0000409 Target::SettingsTerminate ();
Caroline Tice20bd37f2011-03-10 22:14:10 +0000410}
411
Enrico Granata21dfcd92012-09-28 23:57:51 +0000412bool
Enrico Granatae743c782013-04-24 21:29:08 +0000413Debugger::LoadPlugin (const FileSpec& spec, Error& error)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000414{
Greg Clayton5fb8f792013-12-02 19:35:49 +0000415 if (g_load_plugin_callback)
Enrico Granatae743c782013-04-24 21:29:08 +0000416 {
Zachary Turner58a559c2014-08-27 20:15:09 +0000417 llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
418 if (dynlib.isValid())
Greg Clayton5fb8f792013-12-02 19:35:49 +0000419 {
Zachary Turner58a559c2014-08-27 20:15:09 +0000420 m_loaded_plugins.push_back(dynlib);
Greg Clayton5fb8f792013-12-02 19:35:49 +0000421 return true;
422 }
Enrico Granatae743c782013-04-24 21:29:08 +0000423 }
Greg Clayton5fb8f792013-12-02 19:35:49 +0000424 else
Enrico Granatae743c782013-04-24 21:29:08 +0000425 {
Greg Clayton5fb8f792013-12-02 19:35:49 +0000426 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
427 // and if the public API layer isn't available (code is linking against
428 // all of the internal LLDB static libraries), then we can't load plugins
429 error.SetErrorString("Public API layer is not available");
Enrico Granatae743c782013-04-24 21:29:08 +0000430 }
Enrico Granata21dfcd92012-09-28 23:57:51 +0000431 return false;
432}
433
434static FileSpec::EnumerateDirectoryResult
435LoadPluginCallback
436(
437 void *baton,
438 FileSpec::FileType file_type,
439 const FileSpec &file_spec
440 )
441{
442 Error error;
443
444 static ConstString g_dylibext("dylib");
Michael Sartain3cf443d2013-07-17 00:26:30 +0000445 static ConstString g_solibext("so");
Enrico Granata21dfcd92012-09-28 23:57:51 +0000446
447 if (!baton)
448 return FileSpec::eEnumerateDirectoryResultQuit;
449
450 Debugger *debugger = (Debugger*)baton;
451
452 // If we have a regular file, a symbolic link or unknown file type, try
453 // and process the file. We must handle unknown as sometimes the directory
454 // enumeration might be enumerating a file system that doesn't have correct
455 // file type information.
456 if (file_type == FileSpec::eFileTypeRegular ||
457 file_type == FileSpec::eFileTypeSymbolicLink ||
458 file_type == FileSpec::eFileTypeUnknown )
459 {
460 FileSpec plugin_file_spec (file_spec);
461 plugin_file_spec.ResolvePath ();
462
Michael Sartain3cf443d2013-07-17 00:26:30 +0000463 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
464 plugin_file_spec.GetFileNameExtension() != g_solibext)
465 {
Enrico Granata21dfcd92012-09-28 23:57:51 +0000466 return FileSpec::eEnumerateDirectoryResultNext;
Michael Sartain3cf443d2013-07-17 00:26:30 +0000467 }
Enrico Granata21dfcd92012-09-28 23:57:51 +0000468
Enrico Granatae743c782013-04-24 21:29:08 +0000469 Error plugin_load_error;
470 debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000471
472 return FileSpec::eEnumerateDirectoryResultNext;
473 }
474
475 else if (file_type == FileSpec::eFileTypeUnknown ||
476 file_type == FileSpec::eFileTypeDirectory ||
477 file_type == FileSpec::eFileTypeSymbolicLink )
478 {
479 // Try and recurse into anything that a directory or symbolic link.
480 // We must also do this for unknown as sometimes the directory enumeration
Bruce Mitchener6a7f3332014-06-27 02:42:12 +0000481 // might be enumerating a file system that doesn't have correct file type
Enrico Granata21dfcd92012-09-28 23:57:51 +0000482 // information.
483 return FileSpec::eEnumerateDirectoryResultEnter;
484 }
485
486 return FileSpec::eEnumerateDirectoryResultNext;
487}
488
489void
490Debugger::InstanceInitialize ()
491{
492 FileSpec dir_spec;
493 const bool find_directories = true;
494 const bool find_files = true;
495 const bool find_other = true;
496 char dir_path[PATH_MAX];
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000497 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000498 {
499 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
500 {
501 FileSpec::EnumerateDirectory (dir_path,
502 find_directories,
503 find_files,
504 find_other,
505 LoadPluginCallback,
506 this);
507 }
508 }
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000509
510 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000511 {
512 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
513 {
514 FileSpec::EnumerateDirectory (dir_path,
515 find_directories,
516 find_files,
517 find_other,
518 LoadPluginCallback,
519 this);
520 }
521 }
Greg Claytone8cd0c92012-10-19 18:02:49 +0000522
523 PluginManager::DebuggerInitialize (*this);
Enrico Granata21dfcd92012-09-28 23:57:51 +0000524}
525
Greg Clayton66111032010-06-23 01:19:29 +0000526DebuggerSP
Jim Ingham228063c2012-02-21 02:23:08 +0000527Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
Greg Clayton66111032010-06-23 01:19:29 +0000528{
Jim Ingham228063c2012-02-21 02:23:08 +0000529 DebuggerSP debugger_sp (new Debugger(log_callback, baton));
Greg Claytonc15f55e2012-03-30 20:53:46 +0000530 if (g_shared_debugger_refcount > 0)
Greg Clayton66111032010-06-23 01:19:29 +0000531 {
532 Mutex::Locker locker (GetDebuggerListMutex ());
533 GetDebuggerList().push_back(debugger_sp);
534 }
Enrico Granata21dfcd92012-09-28 23:57:51 +0000535 debugger_sp->InstanceInitialize ();
Greg Clayton66111032010-06-23 01:19:29 +0000536 return debugger_sp;
537}
538
Caroline Ticee02657b2011-01-22 01:02:07 +0000539void
Greg Clayton4d122c42011-09-17 08:33:22 +0000540Debugger::Destroy (DebuggerSP &debugger_sp)
Caroline Ticee02657b2011-01-22 01:02:07 +0000541{
542 if (debugger_sp.get() == NULL)
543 return;
544
Jim Ingham8314c522011-09-15 21:36:42 +0000545 debugger_sp->Clear();
546
Greg Claytonc15f55e2012-03-30 20:53:46 +0000547 if (g_shared_debugger_refcount > 0)
Caroline Ticee02657b2011-01-22 01:02:07 +0000548 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000549 Mutex::Locker locker (GetDebuggerListMutex ());
550 DebuggerList &debugger_list = GetDebuggerList ();
551 DebuggerList::iterator pos, end = debugger_list.end();
552 for (pos = debugger_list.begin (); pos != end; ++pos)
Caroline Ticee02657b2011-01-22 01:02:07 +0000553 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000554 if ((*pos).get() == debugger_sp.get())
555 {
556 debugger_list.erase (pos);
557 return;
558 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000559 }
560 }
Caroline Ticee02657b2011-01-22 01:02:07 +0000561}
562
Greg Clayton4d122c42011-09-17 08:33:22 +0000563DebuggerSP
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000564Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
565{
Greg Clayton4d122c42011-09-17 08:33:22 +0000566 DebuggerSP debugger_sp;
Greg Clayton6920b522012-08-22 18:39:03 +0000567 if (g_shared_debugger_refcount > 0)
568 {
569 Mutex::Locker locker (GetDebuggerListMutex ());
570 DebuggerList &debugger_list = GetDebuggerList();
571 DebuggerList::iterator pos, end = debugger_list.end();
572
573 for (pos = debugger_list.begin(); pos != end; ++pos)
574 {
575 if ((*pos).get()->m_instance_name == instance_name)
576 {
577 debugger_sp = *pos;
578 break;
579 }
580 }
581 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000582 return debugger_sp;
583}
Greg Clayton66111032010-06-23 01:19:29 +0000584
585TargetSP
586Debugger::FindTargetWithProcessID (lldb::pid_t pid)
587{
Greg Clayton4d122c42011-09-17 08:33:22 +0000588 TargetSP target_sp;
Greg Claytonc15f55e2012-03-30 20:53:46 +0000589 if (g_shared_debugger_refcount > 0)
Greg Clayton66111032010-06-23 01:19:29 +0000590 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000591 Mutex::Locker locker (GetDebuggerListMutex ());
592 DebuggerList &debugger_list = GetDebuggerList();
593 DebuggerList::iterator pos, end = debugger_list.end();
594 for (pos = debugger_list.begin(); pos != end; ++pos)
595 {
596 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
597 if (target_sp)
598 break;
599 }
Greg Clayton66111032010-06-23 01:19:29 +0000600 }
601 return target_sp;
602}
603
Greg Claytone4e45922011-11-16 05:37:56 +0000604TargetSP
605Debugger::FindTargetWithProcess (Process *process)
606{
607 TargetSP target_sp;
Greg Claytonc15f55e2012-03-30 20:53:46 +0000608 if (g_shared_debugger_refcount > 0)
Greg Claytone4e45922011-11-16 05:37:56 +0000609 {
Greg Claytonc15f55e2012-03-30 20:53:46 +0000610 Mutex::Locker locker (GetDebuggerListMutex ());
611 DebuggerList &debugger_list = GetDebuggerList();
612 DebuggerList::iterator pos, end = debugger_list.end();
613 for (pos = debugger_list.begin(); pos != end; ++pos)
614 {
615 target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
616 if (target_sp)
617 break;
618 }
Greg Claytone4e45922011-11-16 05:37:56 +0000619 }
620 return target_sp;
621}
622
Jim Ingham228063c2012-02-21 02:23:08 +0000623Debugger::Debugger (lldb::LogOutputCallback log_callback, void *baton) :
Caroline Ticeebc1bb22010-06-30 16:22:25 +0000624 UserID (g_unique_id++),
Greg Clayton67cc0632012-08-22 17:17:09 +0000625 Properties(OptionValuePropertiesSP(new OptionValueProperties())),
Greg Clayton44d93782014-01-27 23:43:24 +0000626 m_input_file_sp (new StreamFile (stdin, false)),
627 m_output_file_sp (new StreamFile (stdout, false)),
628 m_error_file_sp (new StreamFile (stderr, false)),
Jim Inghamc5917d92012-11-30 20:23:19 +0000629 m_terminal_state (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000630 m_target_list (*this),
Greg Claytonded470d2011-03-19 01:12:21 +0000631 m_platform_list (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632 m_listener ("lldb.Debugger"),
Greg Clayton9585fbf2013-03-19 00:20:55 +0000633 m_source_manager_ap(),
Jim Inghame37d6052011-09-13 00:29:56 +0000634 m_source_file_cache(),
Greg Clayton66111032010-06-23 01:19:29 +0000635 m_command_interpreter_ap (new CommandInterpreter (*this, eScriptLanguageDefault, false)),
Caroline Ticed5a0a01b2011-06-02 19:18:55 +0000636 m_input_reader_stack (),
Greg Clayton44d93782014-01-27 23:43:24 +0000637 m_instance_name (),
638 m_loaded_plugins (),
639 m_event_handler_thread (LLDB_INVALID_HOST_THREAD),
Greg Claytonb4874f12014-02-28 18:22:24 +0000640 m_io_handler_thread (LLDB_INVALID_HOST_THREAD)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000641{
Greg Clayton67cc0632012-08-22 17:17:09 +0000642 char instance_cstr[256];
643 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
644 m_instance_name.SetCString(instance_cstr);
Jim Ingham228063c2012-02-21 02:23:08 +0000645 if (log_callback)
646 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
Greg Clayton66111032010-06-23 01:19:29 +0000647 m_command_interpreter_ap->Initialize ();
Greg Claytonded470d2011-03-19 01:12:21 +0000648 // Always add our default platform to the platform list
649 PlatformSP default_platform_sp (Platform::GetDefaultPlatform());
650 assert (default_platform_sp.get());
651 m_platform_list.Append (default_platform_sp, true);
Greg Clayton67cc0632012-08-22 17:17:09 +0000652
Greg Clayton754a9362012-08-23 00:22:02 +0000653 m_collection_sp->Initialize (g_properties);
Greg Clayton67cc0632012-08-22 17:17:09 +0000654 m_collection_sp->AppendProperty (ConstString("target"),
655 ConstString("Settings specify to debugging targets."),
656 true,
657 Target::GetGlobalProperties()->GetValueProperties());
Greg Clayton754a9362012-08-23 00:22:02 +0000658 if (m_command_interpreter_ap.get())
659 {
660 m_collection_sp->AppendProperty (ConstString("interpreter"),
661 ConstString("Settings specify to the debugger's command interpreter."),
662 true,
663 m_command_interpreter_ap->GetValueProperties());
664 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000665 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
666 term_width->SetMinimumValue(10);
667 term_width->SetMaximumValue(1024);
Michael Sartainc3ce7f272013-05-23 20:47:45 +0000668
669 // Turn off use-color if this is a dumb terminal.
670 const char *term = getenv ("TERM");
671 if (term && !strcmp (term, "dumb"))
672 SetUseColor (false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673}
674
675Debugger::~Debugger ()
676{
Jim Ingham8314c522011-09-15 21:36:42 +0000677 Clear();
678}
679
680void
681Debugger::Clear()
682{
Greg Clayton44d93782014-01-27 23:43:24 +0000683 ClearIOHandlers();
684 StopIOHandlerThread();
685 StopEventHandlerThread();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000686 m_listener.Clear();
Greg Clayton66111032010-06-23 01:19:29 +0000687 int num_targets = m_target_list.GetNumTargets();
688 for (int i = 0; i < num_targets; i++)
689 {
Greg Claytonccbc08e2012-01-14 17:04:19 +0000690 TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
691 if (target_sp)
Jim Ingham8314c522011-09-15 21:36:42 +0000692 {
Greg Claytonccbc08e2012-01-14 17:04:19 +0000693 ProcessSP process_sp (target_sp->GetProcessSP());
694 if (process_sp)
Jim Ingham1fd07052013-02-27 19:13:05 +0000695 process_sp->Finalize();
Greg Claytonccbc08e2012-01-14 17:04:19 +0000696 target_sp->Destroy();
Jim Ingham8314c522011-09-15 21:36:42 +0000697 }
Greg Clayton66111032010-06-23 01:19:29 +0000698 }
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000699 BroadcasterManager::Clear ();
Greg Clayton0d69a3a2012-05-16 00:11:54 +0000700
701 // Close the input file _before_ we close the input read communications class
702 // as it does NOT own the input file, our m_input_file does.
Jim Inghamc5917d92012-11-30 20:23:19 +0000703 m_terminal_state.Clear();
Greg Clayton44d93782014-01-27 23:43:24 +0000704 if (m_input_file_sp)
705 m_input_file_sp->GetFile().Close ();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000706
707 m_command_interpreter_ap->Clear();
Jim Ingham8314c522011-09-15 21:36:42 +0000708}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000709
710bool
Greg Claytonfc3f0272011-05-29 04:06:55 +0000711Debugger::GetCloseInputOnEOF () const
712{
Greg Clayton44d93782014-01-27 23:43:24 +0000713// return m_input_comm.GetCloseOnEOF();
714 return false;
Greg Claytonfc3f0272011-05-29 04:06:55 +0000715}
716
717void
718Debugger::SetCloseInputOnEOF (bool b)
719{
Greg Clayton44d93782014-01-27 23:43:24 +0000720// m_input_comm.SetCloseOnEOF(b);
Greg Claytonfc3f0272011-05-29 04:06:55 +0000721}
722
723bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724Debugger::GetAsyncExecution ()
725{
Greg Clayton66111032010-06-23 01:19:29 +0000726 return !m_command_interpreter_ap->GetSynchronous();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727}
728
729void
730Debugger::SetAsyncExecution (bool async_execution)
731{
Greg Clayton66111032010-06-23 01:19:29 +0000732 m_command_interpreter_ap->SetSynchronous (!async_execution);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733}
734
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735
736void
737Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
738{
Greg Clayton44d93782014-01-27 23:43:24 +0000739 if (m_input_file_sp)
740 m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
741 else
742 m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
743
744 File &in_file = m_input_file_sp->GetFile();
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000745 if (in_file.IsValid() == false)
746 in_file.SetStream (stdin, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747
Jim Inghamc5917d92012-11-30 20:23:19 +0000748 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
749 SaveInputTerminalState ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750}
751
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752void
753Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
754{
Greg Clayton44d93782014-01-27 23:43:24 +0000755 if (m_output_file_sp)
756 m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
757 else
758 m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
759
760 File &out_file = m_output_file_sp->GetFile();
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000761 if (out_file.IsValid() == false)
762 out_file.SetStream (stdout, false);
Caroline Tice2f88aad2011-01-14 00:29:16 +0000763
Enrico Granatab5887262012-10-29 21:18:03 +0000764 // do not create the ScriptInterpreter just for setting the output file handle
765 // as the constructor will know how to do the right thing on its own
766 const bool can_create = false;
767 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
768 if (script_interpreter)
769 script_interpreter->ResetOutputFileHandle (fh);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000770}
771
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772void
773Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
774{
Greg Clayton44d93782014-01-27 23:43:24 +0000775 if (m_error_file_sp)
776 m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
777 else
778 m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
779
780 File &err_file = m_error_file_sp->GetFile();
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000781 if (err_file.IsValid() == false)
782 err_file.SetStream (stderr, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783}
784
Jim Inghamc5917d92012-11-30 20:23:19 +0000785void
786Debugger::SaveInputTerminalState ()
787{
Greg Clayton44d93782014-01-27 23:43:24 +0000788 if (m_input_file_sp)
789 {
790 File &in_file = m_input_file_sp->GetFile();
791 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
792 m_terminal_state.Save(in_file.GetDescriptor(), true);
793 }
Jim Inghamc5917d92012-11-30 20:23:19 +0000794}
795
796void
797Debugger::RestoreInputTerminalState ()
798{
799 m_terminal_state.Restore();
800}
801
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000802ExecutionContext
Jim Ingham2976d002010-08-26 21:32:51 +0000803Debugger::GetSelectedExecutionContext ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804{
805 ExecutionContext exe_ctx;
Greg Claytonc14ee322011-09-22 04:58:26 +0000806 TargetSP target_sp(GetSelectedTarget());
807 exe_ctx.SetTargetSP (target_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808
809 if (target_sp)
810 {
Greg Claytonc14ee322011-09-22 04:58:26 +0000811 ProcessSP process_sp (target_sp->GetProcessSP());
812 exe_ctx.SetProcessSP (process_sp);
813 if (process_sp && process_sp->IsRunning() == false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814 {
Greg Claytonc14ee322011-09-22 04:58:26 +0000815 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
816 if (thread_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000817 {
Greg Claytonc14ee322011-09-22 04:58:26 +0000818 exe_ctx.SetThreadSP (thread_sp);
819 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
820 if (exe_ctx.GetFramePtr() == NULL)
821 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822 }
823 }
824 }
825 return exe_ctx;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826}
827
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828void
Caroline Ticeefed6132010-11-19 20:47:54 +0000829Debugger::DispatchInputInterrupt ()
830{
Greg Clayton44d93782014-01-27 23:43:24 +0000831 Mutex::Locker locker (m_input_reader_stack.GetMutex());
832 IOHandlerSP reader_sp (m_input_reader_stack.Top());
Caroline Ticeb44880c2011-02-10 01:15:13 +0000833 if (reader_sp)
Greg Clayton44d93782014-01-27 23:43:24 +0000834 reader_sp->Interrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +0000835}
836
837void
838Debugger::DispatchInputEndOfFile ()
839{
Greg Clayton44d93782014-01-27 23:43:24 +0000840 Mutex::Locker locker (m_input_reader_stack.GetMutex());
841 IOHandlerSP reader_sp (m_input_reader_stack.Top());
Caroline Ticeb44880c2011-02-10 01:15:13 +0000842 if (reader_sp)
Greg Clayton44d93782014-01-27 23:43:24 +0000843 reader_sp->GotEOF();
Caroline Ticeefed6132010-11-19 20:47:54 +0000844}
845
846void
Greg Clayton44d93782014-01-27 23:43:24 +0000847Debugger::ClearIOHandlers ()
Caroline Tice3d6086f2010-12-20 18:35:50 +0000848{
Caroline Ticeb44880c2011-02-10 01:15:13 +0000849 // 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 +0000850 Mutex::Locker locker (m_input_reader_stack.GetMutex());
Caroline Ticed5a0a01b2011-06-02 19:18:55 +0000851 while (m_input_reader_stack.GetSize() > 1)
Caroline Tice3d6086f2010-12-20 18:35:50 +0000852 {
Greg Clayton44d93782014-01-27 23:43:24 +0000853 IOHandlerSP reader_sp (m_input_reader_stack.Top());
Caroline Tice3d6086f2010-12-20 18:35:50 +0000854 if (reader_sp)
855 {
Greg Clayton44d93782014-01-27 23:43:24 +0000856 m_input_reader_stack.Pop();
857 reader_sp->SetIsDone(true);
Greg Claytone68f5d62014-02-24 22:50:57 +0000858 reader_sp->Cancel();
Caroline Tice3d6086f2010-12-20 18:35:50 +0000859 }
860 }
861}
862
863void
Greg Clayton44d93782014-01-27 23:43:24 +0000864Debugger::ExecuteIOHanders()
Caroline Tice969ed3d2011-05-02 20:41:46 +0000865{
Caroline Tice9088b062011-05-09 23:06:58 +0000866
Greg Clayton44d93782014-01-27 23:43:24 +0000867 while (1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868 {
Greg Clayton44d93782014-01-27 23:43:24 +0000869 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000870 if (!reader_sp)
871 break;
872
Greg Clayton44d93782014-01-27 23:43:24 +0000873 reader_sp->Activate();
874 reader_sp->Run();
875 reader_sp->Deactivate();
876
877 // Remove all input readers that are done from the top of the stack
878 while (1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879 {
Greg Clayton44d93782014-01-27 23:43:24 +0000880 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
881 if (top_reader_sp && top_reader_sp->GetIsDone())
882 m_input_reader_stack.Pop();
883 else
884 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 }
886 }
Greg Clayton44d93782014-01-27 23:43:24 +0000887 ClearIOHandlers();
888}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889
Greg Clayton44d93782014-01-27 23:43:24 +0000890bool
891Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
892{
893 return m_input_reader_stack.IsTop (reader_sp);
894}
895
896
897ConstString
898Debugger::GetTopIOHandlerControlSequence(char ch)
899{
900 return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901}
902
903void
Greg Clayton44d93782014-01-27 23:43:24 +0000904Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
905{
906 Mutex::Locker locker (m_input_reader_stack.GetMutex());
907 PushIOHandler (reader_sp);
Greg Clayton577508d2014-06-20 00:23:57 +0000908
909 IOHandlerSP top_reader_sp = reader_sp;
910 while (top_reader_sp)
911 {
912 top_reader_sp->Activate();
913 top_reader_sp->Run();
914 top_reader_sp->Deactivate();
915
916 if (top_reader_sp.get() == reader_sp.get())
917 {
918 if (PopIOHandler (reader_sp))
919 break;
920 }
921
922 while (1)
923 {
924 top_reader_sp = m_input_reader_stack.Top();
925 if (top_reader_sp && top_reader_sp->GetIsDone())
926 m_input_reader_stack.Pop();
927 else
928 break;
929 }
930 }
Greg Clayton44d93782014-01-27 23:43:24 +0000931}
932
933void
934Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
935{
936 // Before an IOHandler runs, it must have in/out/err streams.
937 // This function is called when one ore more of the streams
938 // are NULL. We use the top input reader's in/out/err streams,
939 // or fall back to the debugger file handles, or we fall back
940 // onto stdin/stdout/stderr as a last resort.
941
942 Mutex::Locker locker (m_input_reader_stack.GetMutex());
943 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
944 // If no STDIN has been set, then set it appropriately
945 if (!in)
946 {
947 if (top_reader_sp)
948 in = top_reader_sp->GetInputStreamFile();
949 else
950 in = GetInputFile();
951
952 // If there is nothing, use stdin
953 if (!in)
954 in = StreamFileSP(new StreamFile(stdin, false));
955 }
956 // If no STDOUT has been set, then set it appropriately
957 if (!out)
958 {
959 if (top_reader_sp)
960 out = top_reader_sp->GetOutputStreamFile();
961 else
962 out = GetOutputFile();
963
964 // If there is nothing, use stdout
965 if (!out)
966 out = StreamFileSP(new StreamFile(stdout, false));
967 }
968 // If no STDERR has been set, then set it appropriately
969 if (!err)
970 {
971 if (top_reader_sp)
972 err = top_reader_sp->GetErrorStreamFile();
973 else
974 err = GetErrorFile();
975
976 // If there is nothing, use stderr
977 if (!err)
978 err = StreamFileSP(new StreamFile(stdout, false));
979
980 }
981}
982
983void
984Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985{
986 if (!reader_sp)
987 return;
Caroline Ticeb44880c2011-02-10 01:15:13 +0000988
Greg Clayton44d93782014-01-27 23:43:24 +0000989 // Got the current top input reader...
990 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
Caroline Ticeb44880c2011-02-10 01:15:13 +0000991
Greg Claytonb4874f12014-02-28 18:22:24 +0000992 // Don't push the same IO handler twice...
993 if (reader_sp.get() != top_reader_sp.get())
994 {
995 // Push our new input reader
996 m_input_reader_stack.Push (reader_sp);
Greg Clayton44d93782014-01-27 23:43:24 +0000997
Greg Claytonb4874f12014-02-28 18:22:24 +0000998 // Interrupt the top input reader to it will exit its Run() function
999 // and let this new input reader take over
1000 if (top_reader_sp)
1001 top_reader_sp->Deactivate();
1002 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003}
1004
1005bool
Greg Clayton44d93782014-01-27 23:43:24 +00001006Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007{
1008 bool result = false;
Greg Clayton44d93782014-01-27 23:43:24 +00001009
1010 Mutex::Locker locker (m_input_reader_stack.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011
1012 // The reader on the stop of the stack is done, so let the next
Bruce Mitchener6a7f3332014-06-27 02:42:12 +00001013 // read on the stack refresh its prompt and if there is one...
Caroline Ticed5a0a01b2011-06-02 19:18:55 +00001014 if (!m_input_reader_stack.IsEmpty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 {
Greg Clayton44d93782014-01-27 23:43:24 +00001016 IOHandlerSP reader_sp(m_input_reader_stack.Top());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017
1018 if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
1019 {
Greg Clayton44d93782014-01-27 23:43:24 +00001020 reader_sp->Deactivate();
Greg Claytonb4874f12014-02-28 18:22:24 +00001021 reader_sp->Cancel();
Caroline Ticed5a0a01b2011-06-02 19:18:55 +00001022 m_input_reader_stack.Pop ();
Greg Clayton44d93782014-01-27 23:43:24 +00001023
1024 reader_sp = m_input_reader_stack.Top();
1025 if (reader_sp)
1026 reader_sp->Activate();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027
Greg Clayton44d93782014-01-27 23:43:24 +00001028 result = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001029 }
1030 }
1031 return result;
1032}
1033
1034bool
Greg Clayton44d93782014-01-27 23:43:24 +00001035Debugger::HideTopIOHandler()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036{
Greg Clayton44d93782014-01-27 23:43:24 +00001037 Mutex::Locker locker;
1038
1039 if (locker.TryLock(m_input_reader_stack.GetMutex()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040 {
Greg Clayton44d93782014-01-27 23:43:24 +00001041 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1042 if (reader_sp)
1043 reader_sp->Hide();
1044 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 }
Greg Clayton44d93782014-01-27 23:43:24 +00001046 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047}
1048
1049void
Greg Clayton44d93782014-01-27 23:43:24 +00001050Debugger::RefreshTopIOHandler()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051{
Greg Clayton44d93782014-01-27 23:43:24 +00001052 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1053 if (reader_sp)
1054 reader_sp->Refresh();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055}
Greg Clayton66111032010-06-23 01:19:29 +00001056
Greg Clayton44d93782014-01-27 23:43:24 +00001057
Jim Ingham5b52f0c2011-06-02 23:58:26 +00001058StreamSP
1059Debugger::GetAsyncOutputStream ()
1060{
1061 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1062 CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1063}
1064
1065StreamSP
1066Debugger::GetAsyncErrorStream ()
1067{
1068 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1069 CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1070}
1071
Greg Claytonc7bece562013-01-25 18:06:21 +00001072size_t
Enrico Granata061858c2012-02-15 02:34:21 +00001073Debugger::GetNumDebuggers()
1074{
Greg Claytonc15f55e2012-03-30 20:53:46 +00001075 if (g_shared_debugger_refcount > 0)
1076 {
1077 Mutex::Locker locker (GetDebuggerListMutex ());
1078 return GetDebuggerList().size();
1079 }
1080 return 0;
Enrico Granata061858c2012-02-15 02:34:21 +00001081}
1082
1083lldb::DebuggerSP
Greg Claytonc7bece562013-01-25 18:06:21 +00001084Debugger::GetDebuggerAtIndex (size_t index)
Enrico Granata061858c2012-02-15 02:34:21 +00001085{
1086 DebuggerSP debugger_sp;
1087
Greg Claytonc15f55e2012-03-30 20:53:46 +00001088 if (g_shared_debugger_refcount > 0)
1089 {
1090 Mutex::Locker locker (GetDebuggerListMutex ());
1091 DebuggerList &debugger_list = GetDebuggerList();
Enrico Granata061858c2012-02-15 02:34:21 +00001092
Greg Claytonc15f55e2012-03-30 20:53:46 +00001093 if (index < debugger_list.size())
1094 debugger_sp = debugger_list[index];
1095 }
1096
Enrico Granata061858c2012-02-15 02:34:21 +00001097 return debugger_sp;
1098}
1099
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001100DebuggerSP
1101Debugger::FindDebuggerWithID (lldb::user_id_t id)
1102{
Greg Clayton4d122c42011-09-17 08:33:22 +00001103 DebuggerSP debugger_sp;
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001104
Greg Claytonc15f55e2012-03-30 20:53:46 +00001105 if (g_shared_debugger_refcount > 0)
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001106 {
Greg Claytonc15f55e2012-03-30 20:53:46 +00001107 Mutex::Locker locker (GetDebuggerListMutex ());
1108 DebuggerList &debugger_list = GetDebuggerList();
1109 DebuggerList::iterator pos, end = debugger_list.end();
1110 for (pos = debugger_list.begin(); pos != end; ++pos)
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001111 {
Greg Claytonc15f55e2012-03-30 20:53:46 +00001112 if ((*pos).get()->GetID() == id)
1113 {
1114 debugger_sp = *pos;
1115 break;
1116 }
Caroline Ticeebc1bb22010-06-30 16:22:25 +00001117 }
1118 }
1119 return debugger_sp;
1120}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00001121
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001122#if 0
Greg Clayton1b654882010-09-19 02:33:57 +00001123static void
Jason Molendab57e4a12013-11-04 09:33:30 +00001124TestPromptFormats (StackFrame *frame)
Greg Clayton1b654882010-09-19 02:33:57 +00001125{
1126 if (frame == NULL)
1127 return;
1128
1129 StreamString s;
1130 const char *prompt_format =
1131 "{addr = '${addr}'\n}"
1132 "{process.id = '${process.id}'\n}"
1133 "{process.name = '${process.name}'\n}"
1134 "{process.file.basename = '${process.file.basename}'\n}"
1135 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1136 "{thread.id = '${thread.id}'\n}"
1137 "{thread.index = '${thread.index}'\n}"
1138 "{thread.name = '${thread.name}'\n}"
1139 "{thread.queue = '${thread.queue}'\n}"
1140 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1141 "{target.arch = '${target.arch}'\n}"
1142 "{module.file.basename = '${module.file.basename}'\n}"
1143 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1144 "{file.basename = '${file.basename}'\n}"
1145 "{file.fullpath = '${file.fullpath}'\n}"
1146 "{frame.index = '${frame.index}'\n}"
1147 "{frame.pc = '${frame.pc}'\n}"
1148 "{frame.sp = '${frame.sp}'\n}"
1149 "{frame.fp = '${frame.fp}'\n}"
1150 "{frame.flags = '${frame.flags}'\n}"
1151 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1152 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1153 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1154 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1155 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1156 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1157 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1158 "{function.id = '${function.id}'\n}"
1159 "{function.name = '${function.name}'\n}"
Greg Claytonccbc08e2012-01-14 17:04:19 +00001160 "{function.name-with-args = '${function.name-with-args}'\n}"
Greg Clayton1b654882010-09-19 02:33:57 +00001161 "{function.addr-offset = '${function.addr-offset}'\n}"
1162 "{function.line-offset = '${function.line-offset}'\n}"
1163 "{function.pc-offset = '${function.pc-offset}'\n}"
1164 "{line.file.basename = '${line.file.basename}'\n}"
1165 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1166 "{line.number = '${line.number}'\n}"
1167 "{line.start-addr = '${line.start-addr}'\n}"
1168 "{line.end-addr = '${line.end-addr}'\n}"
1169;
1170
1171 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1172 ExecutionContext exe_ctx;
Greg Clayton0603aa92010-10-04 01:05:56 +00001173 frame->CalculateExecutionContext(exe_ctx);
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001174 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
Greg Clayton1b654882010-09-19 02:33:57 +00001175 {
1176 printf("%s\n", s.GetData());
1177 }
1178 else
1179 {
Greg Clayton1b654882010-09-19 02:33:57 +00001180 printf ("what we got: %s\n", s.GetData());
1181 }
1182}
Saleem Abdulrasool2643b902014-03-20 06:08:21 +00001183#endif
Greg Clayton1b654882010-09-19 02:33:57 +00001184
Enrico Granata9fc19442011-07-06 02:13:41 +00001185static bool
Enrico Granatadc940732011-08-23 00:32:52 +00001186ScanFormatDescriptor (const char* var_name_begin,
1187 const char* var_name_end,
1188 const char** var_name_final,
1189 const char** percent_position,
Greg Clayton4d122c42011-09-17 08:33:22 +00001190 Format* custom_format,
Enrico Granatadc940732011-08-23 00:32:52 +00001191 ValueObject::ValueObjectRepresentationStyle* val_obj_display)
Enrico Granata9fc19442011-07-06 02:13:41 +00001192{
Greg Clayton5160ce52013-03-27 23:08:40 +00001193 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Enrico Granata9fc19442011-07-06 02:13:41 +00001194 *percent_position = ::strchr(var_name_begin,'%');
Greg Clayton34132752011-07-06 04:07:21 +00001195 if (!*percent_position || *percent_position > var_name_end)
Enrico Granatae992a082011-07-22 17:03:19 +00001196 {
1197 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001198 log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
Enrico Granata9fc19442011-07-06 02:13:41 +00001199 *var_name_final = var_name_end;
Enrico Granatae992a082011-07-22 17:03:19 +00001200 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001201 else
1202 {
1203 *var_name_final = *percent_position;
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001204 std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
Enrico Granatae992a082011-07-22 17:03:19 +00001205 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001206 log->Printf("[ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001207 if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
Enrico Granata9fc19442011-07-06 02:13:41 +00001208 true,
1209 *custom_format) )
1210 {
Enrico Granatae992a082011-07-22 17:03:19 +00001211 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001212 log->Printf("[ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001213
1214 switch (format_name.front())
1215 {
1216 case '@': // if this is an @ sign, print ObjC description
1217 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1218 break;
1219 case 'V': // if this is a V, print the value using the default format
1220 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1221 break;
1222 case 'L': // if this is an L, print the location of the value
1223 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1224 break;
1225 case 'S': // if this is an S, print the summary after all
1226 *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1227 break;
1228 case '#': // if this is a '#', print the number of children
1229 *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1230 break;
1231 case 'T': // if this is a 'T', print the type
1232 *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1233 break;
Enrico Granata2c75f112013-06-21 00:04:51 +00001234 case 'N': // if this is a 'N', print the name
1235 *val_obj_display = ValueObject::eValueObjectRepresentationStyleName;
1236 break;
1237 case '>': // if this is a '>', print the name
1238 *val_obj_display = ValueObject::eValueObjectRepresentationStyleExpressionPath;
1239 break;
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001240 default:
Jim Ingham5c42d8a2013-05-15 18:27:08 +00001241 if (log)
1242 log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
Enrico Granata36aa5ae2013-05-06 17:18:22 +00001243 break;
1244 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001245 }
1246 // a good custom format tells us to print the value using it
1247 else
Enrico Granatae992a082011-07-22 17:03:19 +00001248 {
1249 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001250 log->Printf("[ScanFormatDescriptor] will display value for this VO");
Enrico Granata86cc9822012-03-19 22:58:49 +00001251 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
Enrico Granatae992a082011-07-22 17:03:19 +00001252 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001253 }
Enrico Granatae992a082011-07-22 17:03:19 +00001254 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001255 log->Printf("[ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
Enrico Granatae992a082011-07-22 17:03:19 +00001256 *custom_format,
1257 *val_obj_display);
Enrico Granata9fc19442011-07-06 02:13:41 +00001258 return true;
1259}
1260
1261static bool
Enrico Granatadc940732011-08-23 00:32:52 +00001262ScanBracketedRange (const char* var_name_begin,
1263 const char* var_name_end,
1264 const char* var_name_final,
1265 const char** open_bracket_position,
1266 const char** separator_position,
1267 const char** close_bracket_position,
1268 const char** var_name_final_if_array_range,
1269 int64_t* index_lower,
1270 int64_t* index_higher)
Enrico Granata9fc19442011-07-06 02:13:41 +00001271{
Greg Clayton5160ce52013-03-27 23:08:40 +00001272 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Enrico Granata9fc19442011-07-06 02:13:41 +00001273 *open_bracket_position = ::strchr(var_name_begin,'[');
Greg Clayton34132752011-07-06 04:07:21 +00001274 if (*open_bracket_position && *open_bracket_position < var_name_final)
Enrico Granata9fc19442011-07-06 02:13:41 +00001275 {
1276 *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1277 *close_bracket_position = ::strchr(*open_bracket_position,']');
1278 // as usual, we assume that [] will come before %
1279 //printf("trying to expand a []\n");
1280 *var_name_final_if_array_range = *open_bracket_position;
Greg Clayton34132752011-07-06 04:07:21 +00001281 if (*close_bracket_position - *open_bracket_position == 1)
Enrico Granata9fc19442011-07-06 02:13:41 +00001282 {
Enrico Granatae992a082011-07-22 17:03:19 +00001283 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001284 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
Enrico Granata9fc19442011-07-06 02:13:41 +00001285 *index_lower = 0;
1286 }
1287 else if (*separator_position == NULL || *separator_position > var_name_end)
1288 {
1289 char *end = NULL;
1290 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1291 *index_higher = *index_lower;
Enrico Granatae992a082011-07-22 17:03:19 +00001292 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001293 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
Enrico Granata9fc19442011-07-06 02:13:41 +00001294 }
Greg Clayton34132752011-07-06 04:07:21 +00001295 else if (*close_bracket_position && *close_bracket_position < var_name_end)
Enrico Granata9fc19442011-07-06 02:13:41 +00001296 {
1297 char *end = NULL;
1298 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1299 *index_higher = ::strtoul (*separator_position+1, &end, 0);
Enrico Granatae992a082011-07-22 17:03:19 +00001300 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001301 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
Enrico Granata9fc19442011-07-06 02:13:41 +00001302 }
1303 else
Enrico Granatae992a082011-07-22 17:03:19 +00001304 {
1305 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001306 log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
Enrico Granata9fc19442011-07-06 02:13:41 +00001307 return false;
Enrico Granatae992a082011-07-22 17:03:19 +00001308 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001309 if (*index_lower > *index_higher && *index_higher > 0)
1310 {
Enrico Granatae992a082011-07-22 17:03:19 +00001311 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001312 log->Printf("[ScanBracketedRange] swapping indices");
Greg Claytonc7bece562013-01-25 18:06:21 +00001313 int64_t temp = *index_lower;
Enrico Granata9fc19442011-07-06 02:13:41 +00001314 *index_lower = *index_higher;
1315 *index_higher = temp;
1316 }
1317 }
Enrico Granatae992a082011-07-22 17:03:19 +00001318 else if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001319 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
Enrico Granata9fc19442011-07-06 02:13:41 +00001320 return true;
1321}
1322
Michael Sartain0769b2b2013-07-30 16:44:36 +00001323template <typename T>
1324static bool RunScriptFormatKeyword(Stream &s, ScriptInterpreter *script_interpreter, T t, const std::string& script_name)
1325{
1326 if (script_interpreter)
1327 {
1328 Error script_error;
1329 std::string script_output;
1330
1331 if (script_interpreter->RunScriptFormatKeyword(script_name.c_str(), t, script_output, script_error) && script_error.Success())
1332 {
1333 s.Printf("%s", script_output.c_str());
1334 return true;
1335 }
1336 else
1337 {
1338 s.Printf("<error: %s>",script_error.AsCString());
1339 }
1340 }
1341 return false;
1342}
1343
Enrico Granata9fc19442011-07-06 02:13:41 +00001344static ValueObjectSP
Enrico Granatadc940732011-08-23 00:32:52 +00001345ExpandIndexedExpression (ValueObject* valobj,
Greg Claytonc7bece562013-01-25 18:06:21 +00001346 size_t index,
Jason Molendab57e4a12013-11-04 09:33:30 +00001347 StackFrame* frame,
Enrico Granatadc940732011-08-23 00:32:52 +00001348 bool deref_pointer)
Enrico Granata9fc19442011-07-06 02:13:41 +00001349{
Greg Clayton5160ce52013-03-27 23:08:40 +00001350 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001351 const char* ptr_deref_format = "[%d]";
Enrico Granata599171a2013-02-01 23:59:44 +00001352 std::string ptr_deref_buffer(10,0);
1353 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
Enrico Granatae992a082011-07-22 17:03:19 +00001354 if (log)
Enrico Granata599171a2013-02-01 23:59:44 +00001355 log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001356 const char* first_unparsed;
1357 ValueObject::GetValueForExpressionPathOptions options;
1358 ValueObject::ExpressionPathEndResultType final_value_type;
1359 ValueObject::ExpressionPathScanEndReason reason_to_stop;
Enrico Granata86cc9822012-03-19 22:58:49 +00001360 ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
Enrico Granata599171a2013-02-01 23:59:44 +00001361 ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001362 &first_unparsed,
1363 &reason_to_stop,
1364 &final_value_type,
1365 options,
1366 &what_next);
1367 if (!item)
1368 {
Enrico Granatae992a082011-07-22 17:03:19 +00001369 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001370 log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001371 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001372 first_unparsed, reason_to_stop, final_value_type);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001373 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001374 else
1375 {
Enrico Granatae992a082011-07-22 17:03:19 +00001376 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001377 log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001378 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001379 first_unparsed, reason_to_stop, final_value_type);
Enrico Granata9fc19442011-07-06 02:13:41 +00001380 }
1381 return item;
1382}
1383
Michael Sartain0769b2b2013-07-30 16:44:36 +00001384static inline bool
1385IsToken(const char *var_name_begin, const char *var)
1386{
1387 return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1388}
1389
1390static bool
1391IsTokenWithFormat(const char *var_name_begin, const char *var, std::string &format, const char *default_format,
1392 const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1393{
1394 int var_len = strlen(var);
1395 if (::strncmp (var_name_begin, var, var_len) == 0)
1396 {
1397 var_name_begin += var_len;
1398 if (*var_name_begin == '}')
1399 {
1400 format = default_format;
1401 return true;
1402 }
1403 else if (*var_name_begin == '%')
1404 {
1405 // Allow format specifiers: x|X|u with optional width specifiers.
1406 // ${thread.id%x} ; hex
1407 // ${thread.id%X} ; uppercase hex
1408 // ${thread.id%u} ; unsigned decimal
1409 // ${thread.id%8.8X} ; width.precision + specifier
1410 // ${thread.id%tid} ; unsigned on FreeBSD/Linux, otherwise default_format (0x%4.4x for thread.id)
1411 int dot_count = 0;
1412 const char *specifier = NULL;
1413 int width_precision_length = 0;
1414 const char *width_precision = ++var_name_begin;
1415 while (isdigit(*var_name_begin) || *var_name_begin == '.')
1416 {
1417 dot_count += (*var_name_begin == '.');
1418 if (dot_count > 1)
1419 break;
1420 var_name_begin++;
1421 width_precision_length++;
1422 }
1423
1424 if (IsToken (var_name_begin, "tid}"))
1425 {
1426 Target *target = Target::GetTargetFromContexts (exe_ctx_ptr, sc_ptr);
1427 if (target)
1428 {
1429 ArchSpec arch (target->GetArchitecture ());
1430 llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1431 if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1432 specifier = PRIu64;
1433 }
1434 if (!specifier)
1435 {
1436 format = default_format;
1437 return true;
1438 }
1439 }
1440 else if (IsToken (var_name_begin, "x}"))
1441 specifier = PRIx64;
1442 else if (IsToken (var_name_begin, "X}"))
1443 specifier = PRIX64;
1444 else if (IsToken (var_name_begin, "u}"))
1445 specifier = PRIu64;
1446
1447 if (specifier)
1448 {
1449 format = "%";
1450 if (width_precision_length)
1451 format += std::string(width_precision, width_precision_length);
1452 format += specifier;
1453 return true;
1454 }
1455 }
1456 }
1457 return false;
1458}
1459
Jason Molenda705b1802014-06-13 02:37:02 +00001460// Find information for the "thread.info.*" specifiers in a format string
1461static bool
1462FormatThreadExtendedInfoRecurse
1463(
1464 const char *var_name_begin,
1465 StructuredData::ObjectSP thread_info_dictionary,
1466 const SymbolContext *sc,
1467 const ExecutionContext *exe_ctx,
1468 Stream &s
1469)
1470{
1471 bool var_success = false;
1472 std::string token_format;
1473
1474 llvm::StringRef var_name(var_name_begin);
1475 size_t percent_idx = var_name.find('%');
1476 size_t close_curly_idx = var_name.find('}');
1477 llvm::StringRef path = var_name;
1478 llvm::StringRef formatter = var_name;
1479
1480 // 'path' will be the dot separated list of objects to transverse up until we hit
1481 // a close curly brace, a percent sign, or an end of string.
1482 if (percent_idx != llvm::StringRef::npos || close_curly_idx != llvm::StringRef::npos)
1483 {
1484 if (percent_idx != llvm::StringRef::npos && close_curly_idx != llvm::StringRef::npos)
1485 {
1486 if (percent_idx < close_curly_idx)
1487 {
1488 path = var_name.slice(0, percent_idx);
1489 formatter = var_name.substr (percent_idx);
1490 }
1491 else
1492 {
1493 path = var_name.slice(0, close_curly_idx);
1494 formatter = var_name.substr (close_curly_idx);
1495 }
1496 }
1497 else if (percent_idx != llvm::StringRef::npos)
1498 {
1499 path = var_name.slice(0, percent_idx);
1500 formatter = var_name.substr (percent_idx);
1501 }
1502 else if (close_curly_idx != llvm::StringRef::npos)
1503 {
1504 path = var_name.slice(0, close_curly_idx);
1505 formatter = var_name.substr (close_curly_idx);
1506 }
1507 }
1508
1509 StructuredData::ObjectSP value = thread_info_dictionary->GetObjectForDotSeparatedPath (path);
1510
1511 if (value.get())
1512 {
1513 if (value->GetType() == StructuredData::Type::eTypeInteger)
1514 {
1515 if (IsTokenWithFormat (formatter.str().c_str(), "", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1516 {
1517 s.Printf(token_format.c_str(), value->GetAsInteger()->GetValue());
1518 var_success = true;
1519 }
1520 }
1521 else if (value->GetType() == StructuredData::Type::eTypeFloat)
1522 {
1523 s.Printf ("%f", value->GetAsFloat()->GetValue());
1524 var_success = true;
1525 }
1526 else if (value->GetType() == StructuredData::Type::eTypeString)
1527 {
1528 s.Printf("%s", value->GetAsString()->GetValue().c_str());
1529 var_success = true;
1530 }
1531 else if (value->GetType() == StructuredData::Type::eTypeArray)
1532 {
1533 if (value->GetAsArray()->GetSize() > 0)
1534 {
1535 s.Printf ("%zu", value->GetAsArray()->GetSize());
1536 var_success = true;
1537 }
1538 }
1539 else if (value->GetType() == StructuredData::Type::eTypeDictionary)
1540 {
1541 s.Printf ("%zu", value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1542 var_success = true;
1543 }
1544 }
1545
1546 return var_success;
1547}
1548
1549
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001550static bool
1551FormatPromptRecurse
Greg Clayton1b654882010-09-19 02:33:57 +00001552(
1553 const char *format,
1554 const SymbolContext *sc,
1555 const ExecutionContext *exe_ctx,
1556 const Address *addr,
1557 Stream &s,
Enrico Granata4becb372011-06-29 22:27:15 +00001558 const char **end,
Enrico Granatac482a192011-08-17 22:13:59 +00001559 ValueObject* valobj
Greg Clayton1b654882010-09-19 02:33:57 +00001560)
1561{
Enrico Granatac482a192011-08-17 22:13:59 +00001562 ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
Greg Clayton1b654882010-09-19 02:33:57 +00001563 bool success = true;
1564 const char *p;
Greg Clayton5160ce52013-03-27 23:08:40 +00001565 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001566
Greg Clayton1b654882010-09-19 02:33:57 +00001567 for (p = format; *p != '\0'; ++p)
1568 {
Enrico Granatac482a192011-08-17 22:13:59 +00001569 if (realvalobj)
Enrico Granata4becb372011-06-29 22:27:15 +00001570 {
Enrico Granatac482a192011-08-17 22:13:59 +00001571 valobj = realvalobj;
1572 realvalobj = NULL;
Enrico Granata4becb372011-06-29 22:27:15 +00001573 }
Greg Clayton1b654882010-09-19 02:33:57 +00001574 size_t non_special_chars = ::strcspn (p, "${}\\");
1575 if (non_special_chars > 0)
1576 {
1577 if (success)
1578 s.Write (p, non_special_chars);
1579 p += non_special_chars;
1580 }
1581
1582 if (*p == '\0')
1583 {
1584 break;
1585 }
1586 else if (*p == '{')
1587 {
1588 // Start a new scope that must have everything it needs if it is to
1589 // to make it into the final output stream "s". If you want to make
1590 // a format that only prints out the function or symbol name if there
1591 // is one in the symbol context you can use:
1592 // "{function =${function.name}}"
1593 // The first '{' starts a new scope that end with the matching '}' at
1594 // the end of the string. The contents "function =${function.name}"
1595 // will then be evaluated and only be output if there is a function
1596 // or symbol with a valid name.
1597 StreamString sub_strm;
1598
1599 ++p; // Skip the '{'
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001600
1601 if (FormatPromptRecurse (p, sc, exe_ctx, addr, sub_strm, &p, valobj))
Greg Clayton1b654882010-09-19 02:33:57 +00001602 {
1603 // The stream had all it needed
1604 s.Write(sub_strm.GetData(), sub_strm.GetSize());
1605 }
1606 if (*p != '}')
1607 {
1608 success = false;
1609 break;
1610 }
1611 }
1612 else if (*p == '}')
1613 {
1614 // End of a enclosing scope
1615 break;
1616 }
1617 else if (*p == '$')
1618 {
1619 // We have a prompt variable to print
1620 ++p;
1621 if (*p == '{')
1622 {
1623 ++p;
1624 const char *var_name_begin = p;
1625 const char *var_name_end = ::strchr (p, '}');
1626
1627 if (var_name_end && var_name_begin < var_name_end)
1628 {
1629 // if we have already failed to parse, skip this variable
1630 if (success)
1631 {
1632 const char *cstr = NULL;
Michael Sartain0769b2b2013-07-30 16:44:36 +00001633 std::string token_format;
Greg Clayton1b654882010-09-19 02:33:57 +00001634 Address format_addr;
1635 bool calculate_format_addr_function_offset = false;
1636 // Set reg_kind and reg_num to invalid values
1637 RegisterKind reg_kind = kNumRegisterKinds;
1638 uint32_t reg_num = LLDB_INVALID_REGNUM;
1639 FileSpec format_file_spec;
Greg Claytone0d378b2011-03-24 21:19:54 +00001640 const RegisterInfo *reg_info = NULL;
Greg Clayton1b654882010-09-19 02:33:57 +00001641 RegisterContext *reg_ctx = NULL;
Enrico Granata9fc19442011-07-06 02:13:41 +00001642 bool do_deref_pointer = false;
Enrico Granata86cc9822012-03-19 22:58:49 +00001643 ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1644 ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001645
Greg Clayton1b654882010-09-19 02:33:57 +00001646 // Each variable must set success to true below...
1647 bool var_success = false;
1648 switch (var_name_begin[0])
1649 {
Enrico Granata4becb372011-06-29 22:27:15 +00001650 case '*':
Enrico Granata4becb372011-06-29 22:27:15 +00001651 case 'v':
Enrico Granata6f3533f2011-07-29 19:53:35 +00001652 case 's':
Enrico Granata4becb372011-06-29 22:27:15 +00001653 {
Enrico Granatac482a192011-08-17 22:13:59 +00001654 if (!valobj)
Enrico Granata6f3533f2011-07-29 19:53:35 +00001655 break;
1656
Enrico Granatac3e320a2011-08-02 17:27:39 +00001657 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001658 log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
Enrico Granatac3e320a2011-08-02 17:27:39 +00001659
Enrico Granata6f3533f2011-07-29 19:53:35 +00001660 // check for *var and *svar
1661 if (*var_name_begin == '*')
1662 {
1663 do_deref_pointer = true;
1664 var_name_begin++;
Enrico Granata68ae4112013-06-18 18:23:07 +00001665 if (log)
1666 log->Printf("[Debugger::FormatPrompt] found a deref, new string is: %s",var_name_begin);
Enrico Granata6f3533f2011-07-29 19:53:35 +00001667 }
Enrico Granatac3e320a2011-08-02 17:27:39 +00001668
Enrico Granata6f3533f2011-07-29 19:53:35 +00001669 if (*var_name_begin == 's')
1670 {
Enrico Granatac5bc4122012-03-27 02:35:13 +00001671 if (!valobj->IsSynthetic())
1672 valobj = valobj->GetSyntheticValue().get();
Enrico Granata86cc9822012-03-19 22:58:49 +00001673 if (!valobj)
1674 break;
Enrico Granata6f3533f2011-07-29 19:53:35 +00001675 var_name_begin++;
Enrico Granata68ae4112013-06-18 18:23:07 +00001676 if (log)
1677 log->Printf("[Debugger::FormatPrompt] found a synthetic, new string is: %s",var_name_begin);
Enrico Granata6f3533f2011-07-29 19:53:35 +00001678 }
1679
1680 // should be a 'v' by now
1681 if (*var_name_begin != 'v')
1682 break;
1683
Enrico Granatac3e320a2011-08-02 17:27:39 +00001684 if (log)
Enrico Granata68ae4112013-06-18 18:23:07 +00001685 log->Printf("[Debugger::FormatPrompt] string I am working with: %s",var_name_begin);
Enrico Granatac3e320a2011-08-02 17:27:39 +00001686
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001687 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
Enrico Granata86cc9822012-03-19 22:58:49 +00001688 ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001689 ValueObject::GetValueForExpressionPathOptions options;
Enrico Granata8c9d3562011-08-11 17:08:01 +00001690 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
Enrico Granata86cc9822012-03-19 22:58:49 +00001691 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
Greg Clayton34132752011-07-06 04:07:21 +00001692 ValueObject* target = NULL;
Greg Clayton4d122c42011-09-17 08:33:22 +00001693 Format custom_format = eFormatInvalid;
Greg Clayton34132752011-07-06 04:07:21 +00001694 const char* var_name_final = NULL;
1695 const char* var_name_final_if_array_range = NULL;
1696 const char* close_bracket_position = NULL;
1697 int64_t index_lower = -1;
1698 int64_t index_higher = -1;
1699 bool is_array_range = false;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001700 const char* first_unparsed;
Enrico Granata85933ed2011-08-18 16:38:26 +00001701 bool was_plain_var = false;
1702 bool was_var_format = false;
Enrico Granataa777dc22012-05-08 21:49:57 +00001703 bool was_var_indexed = false;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001704
Enrico Granatac482a192011-08-17 22:13:59 +00001705 if (!valobj) break;
1706 // simplest case ${var}, just print valobj's value
Michael Sartain0769b2b2013-07-30 16:44:36 +00001707 if (IsToken (var_name_begin, "var}"))
Enrico Granata4becb372011-06-29 22:27:15 +00001708 {
Enrico Granata85933ed2011-08-18 16:38:26 +00001709 was_plain_var = true;
Enrico Granatac482a192011-08-17 22:13:59 +00001710 target = valobj;
Enrico Granata86cc9822012-03-19 22:58:49 +00001711 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
Greg Clayton34132752011-07-06 04:07:21 +00001712 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00001713 else if (IsToken (var_name_begin,"var%"))
Greg Clayton34132752011-07-06 04:07:21 +00001714 {
Enrico Granata85933ed2011-08-18 16:38:26 +00001715 was_var_format = true;
Greg Clayton34132752011-07-06 04:07:21 +00001716 // this is a variable with some custom format applied to it
1717 const char* percent_position;
Enrico Granatac482a192011-08-17 22:13:59 +00001718 target = valobj;
Enrico Granata86cc9822012-03-19 22:58:49 +00001719 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
Greg Clayton34132752011-07-06 04:07:21 +00001720 ScanFormatDescriptor (var_name_begin,
1721 var_name_end,
1722 &var_name_final,
1723 &percent_position,
1724 &custom_format,
1725 &val_obj_display);
1726 }
1727 // this is ${var.something} or multiple .something nested
Michael Sartain0769b2b2013-07-30 16:44:36 +00001728 else if (IsToken (var_name_begin, "var"))
Greg Clayton34132752011-07-06 04:07:21 +00001729 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00001730 if (IsToken (var_name_begin, "var["))
Enrico Granataa777dc22012-05-08 21:49:57 +00001731 was_var_indexed = true;
Greg Clayton34132752011-07-06 04:07:21 +00001732 const char* percent_position;
1733 ScanFormatDescriptor (var_name_begin,
1734 var_name_end,
1735 &var_name_final,
1736 &percent_position,
1737 &custom_format,
1738 &val_obj_display);
1739
1740 const char* open_bracket_position;
1741 const char* separator_position;
1742 ScanBracketedRange (var_name_begin,
1743 var_name_end,
1744 var_name_final,
1745 &open_bracket_position,
1746 &separator_position,
1747 &close_bracket_position,
1748 &var_name_final_if_array_range,
1749 &index_lower,
1750 &index_higher);
1751
1752 Error error;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001753
Enrico Granata599171a2013-02-01 23:59:44 +00001754 std::string expr_path(var_name_final-var_name_begin-1,0);
1755 memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1756
1757 if (log)
1758 log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1759
1760 target = valobj->GetValueForExpressionPath(expr_path.c_str(),
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001761 &first_unparsed,
1762 &reason_to_stop,
1763 &final_value_type,
1764 options,
1765 &what_next).get();
1766
1767 if (!target)
Enrico Granata9fc19442011-07-06 02:13:41 +00001768 {
Enrico Granatae992a082011-07-22 17:03:19 +00001769 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001770 log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001771 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001772 first_unparsed, reason_to_stop, final_value_type);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001773 break;
Enrico Granata9fc19442011-07-06 02:13:41 +00001774 }
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001775 else
1776 {
Enrico Granatae992a082011-07-22 17:03:19 +00001777 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001778 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
Enrico Granatae992a082011-07-22 17:03:19 +00001779 " final_value_type %d",
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001780 first_unparsed, reason_to_stop, final_value_type);
1781 }
Enrico Granata4becb372011-06-29 22:27:15 +00001782 }
Greg Clayton34132752011-07-06 04:07:21 +00001783 else
Enrico Granata9fc19442011-07-06 02:13:41 +00001784 break;
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001785
Enrico Granata86cc9822012-03-19 22:58:49 +00001786 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1787 final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001788
Enrico Granata86cc9822012-03-19 22:58:49 +00001789 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
Enrico Granata9fc19442011-07-06 02:13:41 +00001790
Enrico Granataa7187d02011-07-06 19:27:11 +00001791 if (do_deref_pointer && !is_array_range)
Enrico Granata9fc19442011-07-06 02:13:41 +00001792 {
Greg Clayton34132752011-07-06 04:07:21 +00001793 // I have not deref-ed yet, let's do it
1794 // this happens when we are not going through GetValueForVariableExpressionPath
1795 // to get to the target ValueObject
Enrico Granata9fc19442011-07-06 02:13:41 +00001796 Error error;
Greg Clayton34132752011-07-06 04:07:21 +00001797 target = target->Dereference(error).get();
Enrico Granatadc940732011-08-23 00:32:52 +00001798 if (error.Fail())
1799 {
1800 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001801 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
Enrico Granatadc940732011-08-23 00:32:52 +00001802 break;
1803 }
Greg Clayton34132752011-07-06 04:07:21 +00001804 do_deref_pointer = false;
Enrico Granata9fc19442011-07-06 02:13:41 +00001805 }
Enrico Granataf4efecd2011-07-12 22:56:10 +00001806
Jim Inghamf164d942014-03-11 18:17:23 +00001807 if (!target)
1808 {
1809 if (log)
1810 log->Printf("[Debugger::FormatPrompt] could not calculate target for prompt expression");
1811 break;
1812 }
1813
Enrico Granataa777dc22012-05-08 21:49:57 +00001814 // we do not want to use the summary for a bitfield of type T:n
1815 // if we were originally dealing with just a T - that would get
1816 // us into an endless recursion
1817 if (target->IsBitfield() && was_var_indexed)
1818 {
1819 // TODO: check for a (T:n)-specific summary - we should still obey that
1820 StreamString bitfield_name;
1821 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1822 lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1823 if (!DataVisualization::GetSummaryForType(type_sp))
1824 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1825 }
1826
Enrico Granata85933ed2011-08-18 16:38:26 +00001827 // TODO use flags for these
Greg Clayton57ee3062013-07-11 22:46:58 +00001828 const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
1829 bool is_array = (type_info_flags & ClangASTType::eTypeIsArray) != 0;
1830 bool is_pointer = (type_info_flags & ClangASTType::eTypeIsPointer) != 0;
1831 bool is_aggregate = target->GetClangType().IsAggregateType();
Enrico Granataf4efecd2011-07-12 22:56:10 +00001832
Enrico Granata86cc9822012-03-19 22:58:49 +00001833 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 +00001834 {
Enrico Granata85933ed2011-08-18 16:38:26 +00001835 StreamString str_temp;
Enrico Granatae992a082011-07-22 17:03:19 +00001836 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001837 log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001838
Greg Clayton5088c482013-03-25 21:06:13 +00001839 if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
Enrico Granata85933ed2011-08-18 16:38:26 +00001840 {
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001841 // try to use the special cases
1842 var_success = target->DumpPrintableRepresentation(str_temp,
1843 val_obj_display,
1844 custom_format);
1845 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001846 log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001847
1848 // should not happen
Greg Clayton5088c482013-03-25 21:06:13 +00001849 if (var_success)
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001850 s << str_temp.GetData();
Enrico Granata85933ed2011-08-18 16:38:26 +00001851 var_success = true;
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001852 break;
Enrico Granata85933ed2011-08-18 16:38:26 +00001853 }
1854 else
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001855 {
Enrico Granata88da35f2011-08-23 21:26:09 +00001856 if (was_plain_var) // if ${var}
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001857 {
1858 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1859 }
Enrico Granata88da35f2011-08-23 21:26:09 +00001860 else if (is_pointer) // if pointer, value is the address stored
1861 {
Greg Clayton23f59502012-07-17 03:23:13 +00001862 target->DumpPrintableRepresentation (s,
1863 val_obj_display,
1864 custom_format,
1865 ValueObject::ePrintableRepresentationSpecialCasesDisable);
Enrico Granata88da35f2011-08-23 21:26:09 +00001866 }
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001867 var_success = true;
1868 break;
1869 }
1870 }
1871
1872 // if directly trying to print ${var}, and this is an aggregate, display a nice
1873 // type @ location message
1874 if (is_aggregate && was_plain_var)
1875 {
1876 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1877 var_success = true;
Enrico Granata85933ed2011-08-18 16:38:26 +00001878 break;
1879 }
1880
Enrico Granatad64d0bc2011-08-19 21:13:46 +00001881 // 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 +00001882 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
Enrico Granata85933ed2011-08-18 16:38:26 +00001883 {
1884 s << "<invalid use of aggregate type>";
1885 var_success = true;
Enrico Granataf4efecd2011-07-12 22:56:10 +00001886 break;
1887 }
Greg Clayton34132752011-07-06 04:07:21 +00001888
1889 if (!is_array_range)
Enrico Granatae992a082011-07-22 17:03:19 +00001890 {
1891 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001892 log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
Greg Clayton34132752011-07-06 04:07:21 +00001893 var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
Enrico Granatae992a082011-07-22 17:03:19 +00001894 }
Greg Clayton34132752011-07-06 04:07:21 +00001895 else
Enrico Granatae992a082011-07-22 17:03:19 +00001896 {
1897 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001898 log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
Greg Clayton34132752011-07-06 04:07:21 +00001899 if (!is_array && !is_pointer)
1900 break;
Enrico Granatae992a082011-07-22 17:03:19 +00001901 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001902 log->Printf("[Debugger::FormatPrompt] handle as array");
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001903 const char* special_directions = NULL;
1904 StreamString special_directions_writer;
Greg Clayton34132752011-07-06 04:07:21 +00001905 if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1906 {
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001907 ConstString additional_data;
1908 additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1909 special_directions_writer.Printf("${%svar%s}",
1910 do_deref_pointer ? "*" : "",
1911 additional_data.GetCString());
1912 special_directions = special_directions_writer.GetData();
Greg Clayton34132752011-07-06 04:07:21 +00001913 }
1914
1915 // let us display items index_lower thru index_higher of this array
1916 s.PutChar('[');
1917 var_success = true;
1918
1919 if (index_higher < 0)
Enrico Granatac482a192011-08-17 22:13:59 +00001920 index_higher = valobj->GetNumChildren() - 1;
Greg Clayton34132752011-07-06 04:07:21 +00001921
Greg Claytoncc4d0142012-02-17 07:49:44 +00001922 uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
Enrico Granata22c55d12011-08-12 02:00:06 +00001923
Greg Clayton34132752011-07-06 04:07:21 +00001924 for (;index_lower<=index_higher;index_lower++)
1925 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001926 ValueObject* item = ExpandIndexedExpression (target,
1927 index_lower,
1928 exe_ctx->GetFramePtr(),
1929 false).get();
Greg Clayton34132752011-07-06 04:07:21 +00001930
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001931 if (!item)
1932 {
Enrico Granatae992a082011-07-22 17:03:19 +00001933 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001934 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001935 }
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001936 else
1937 {
Enrico Granatae992a082011-07-22 17:03:19 +00001938 if (log)
Enrico Granatad2284832012-10-17 22:23:56 +00001939 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001940 }
Enrico Granatafc7a7f32011-07-08 02:51:01 +00001941
Greg Clayton34132752011-07-06 04:07:21 +00001942 if (!special_directions)
1943 var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1944 else
Michael Sartainc3ce7f272013-05-23 20:47:45 +00001945 var_success &= FormatPromptRecurse(special_directions, sc, exe_ctx, addr, s, NULL, item);
Greg Clayton34132752011-07-06 04:07:21 +00001946
Enrico Granata22c55d12011-08-12 02:00:06 +00001947 if (--max_num_children == 0)
1948 {
1949 s.PutCString(", ...");
1950 break;
1951 }
1952
Greg Clayton34132752011-07-06 04:07:21 +00001953 if (index_lower < index_higher)
1954 s.PutChar(',');
1955 }
1956 s.PutChar(']');
1957 }
Enrico Granata4becb372011-06-29 22:27:15 +00001958 }
Enrico Granata9fc19442011-07-06 02:13:41 +00001959 break;
Greg Clayton1b654882010-09-19 02:33:57 +00001960 case 'a':
Michael Sartain0769b2b2013-07-30 16:44:36 +00001961 if (IsToken (var_name_begin, "addr}"))
Greg Clayton1b654882010-09-19 02:33:57 +00001962 {
1963 if (addr && addr->IsValid())
1964 {
1965 var_success = true;
1966 format_addr = *addr;
1967 }
1968 }
1969 break;
1970
1971 case 'p':
Michael Sartain0769b2b2013-07-30 16:44:36 +00001972 if (IsToken (var_name_begin, "process."))
Greg Clayton1b654882010-09-19 02:33:57 +00001973 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001974 if (exe_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00001975 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001976 Process *process = exe_ctx->GetProcessPtr();
1977 if (process)
Greg Clayton1b654882010-09-19 02:33:57 +00001978 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001979 var_name_begin += ::strlen ("process.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00001980 if (IsTokenWithFormat (var_name_begin, "id", token_format, "%" PRIu64, exe_ctx, sc))
Greg Clayton1b654882010-09-19 02:33:57 +00001981 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00001982 s.Printf(token_format.c_str(), process->GetID());
Greg Claytonc14ee322011-09-22 04:58:26 +00001983 var_success = true;
1984 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00001985 else if ((IsToken (var_name_begin, "name}")) ||
1986 (IsToken (var_name_begin, "file.basename}")) ||
1987 (IsToken (var_name_begin, "file.fullpath}")))
Greg Claytonc14ee322011-09-22 04:58:26 +00001988 {
1989 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1990 if (exe_module)
Greg Clayton1b654882010-09-19 02:33:57 +00001991 {
Greg Claytonc14ee322011-09-22 04:58:26 +00001992 if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
1993 {
1994 format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00001995 var_success = (bool)format_file_spec;
Greg Claytonc14ee322011-09-22 04:58:26 +00001996 }
1997 else
1998 {
1999 format_file_spec = exe_module->GetFileSpec();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002000 var_success = (bool)format_file_spec;
Greg Claytonc14ee322011-09-22 04:58:26 +00002001 }
Greg Clayton1b654882010-09-19 02:33:57 +00002002 }
2003 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002004 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002005 {
2006 var_name_begin += ::strlen("script:");
2007 std::string script_name(var_name_begin,var_name_end);
2008 ScriptInterpreter* script_interpreter = process->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002009 if (RunScriptFormatKeyword (s, script_interpreter, process, script_name))
2010 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002011 }
Greg Clayton1b654882010-09-19 02:33:57 +00002012 }
Greg Claytonc14ee322011-09-22 04:58:26 +00002013 }
Greg Clayton1b654882010-09-19 02:33:57 +00002014 }
2015 break;
2016
2017 case 't':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002018 if (IsToken (var_name_begin, "thread."))
Greg Clayton1b654882010-09-19 02:33:57 +00002019 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002020 if (exe_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00002021 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002022 Thread *thread = exe_ctx->GetThreadPtr();
2023 if (thread)
Greg Clayton1b654882010-09-19 02:33:57 +00002024 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002025 var_name_begin += ::strlen ("thread.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002026 if (IsTokenWithFormat (var_name_begin, "id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
Greg Clayton1b654882010-09-19 02:33:57 +00002027 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002028 s.Printf(token_format.c_str(), thread->GetID());
Greg Claytonc14ee322011-09-22 04:58:26 +00002029 var_success = true;
2030 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002031 else if (IsTokenWithFormat (var_name_begin, "protocol_id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
Greg Clayton160c9d82013-05-01 21:54:04 +00002032 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002033 s.Printf(token_format.c_str(), thread->GetProtocolID());
Greg Clayton160c9d82013-05-01 21:54:04 +00002034 var_success = true;
2035 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002036 else if (IsTokenWithFormat (var_name_begin, "index", token_format, "%" PRIu64, exe_ctx, sc))
Greg Claytonc14ee322011-09-22 04:58:26 +00002037 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002038 s.Printf(token_format.c_str(), (uint64_t)thread->GetIndexID());
Greg Claytonc14ee322011-09-22 04:58:26 +00002039 var_success = true;
2040 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002041 else if (IsToken (var_name_begin, "name}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002042 {
2043 cstr = thread->GetName();
2044 var_success = cstr && cstr[0];
2045 if (var_success)
Greg Clayton1b654882010-09-19 02:33:57 +00002046 s.PutCString(cstr);
Greg Claytonc14ee322011-09-22 04:58:26 +00002047 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002048 else if (IsToken (var_name_begin, "queue}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002049 {
2050 cstr = thread->GetQueueName();
2051 var_success = cstr && cstr[0];
2052 if (var_success)
2053 s.PutCString(cstr);
2054 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002055 else if (IsToken (var_name_begin, "stop-reason}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002056 {
2057 StopInfoSP stop_info_sp = thread->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00002058 if (stop_info_sp && stop_info_sp->IsValid())
Greg Claytonc14ee322011-09-22 04:58:26 +00002059 {
2060 cstr = stop_info_sp->GetDescription();
2061 if (cstr && cstr[0])
2062 {
2063 s.PutCString(cstr);
2064 var_success = true;
2065 }
Greg Clayton1b654882010-09-19 02:33:57 +00002066 }
2067 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002068 else if (IsToken (var_name_begin, "return-value}"))
Jim Ingham73ca05a2011-12-17 01:35:57 +00002069 {
2070 StopInfoSP stop_info_sp = thread->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00002071 if (stop_info_sp && stop_info_sp->IsValid())
Jim Ingham73ca05a2011-12-17 01:35:57 +00002072 {
2073 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
2074 if (return_valobj_sp)
2075 {
Enrico Granata4d93b8c2013-09-30 19:11:51 +00002076 return_valobj_sp->Dump(s);
Jim Inghamef651602011-12-22 19:12:40 +00002077 var_success = true;
Jim Ingham73ca05a2011-12-17 01:35:57 +00002078 }
2079 }
2080 }
Jim Ingham30fadaf2014-07-08 01:07:32 +00002081 else if (IsToken (var_name_begin, "completed-expression}"))
2082 {
2083 StopInfoSP stop_info_sp = thread->GetStopInfo ();
2084 if (stop_info_sp && stop_info_sp->IsValid())
2085 {
2086 ClangExpressionVariableSP expression_var_sp = StopInfo::GetExpressionVariable (stop_info_sp);
2087 if (expression_var_sp && expression_var_sp->GetValueObject())
2088 {
2089 expression_var_sp->GetValueObject()->Dump(s);
2090 var_success = true;
2091 }
2092 }
2093 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002094 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002095 {
2096 var_name_begin += ::strlen("script:");
2097 std::string script_name(var_name_begin,var_name_end);
2098 ScriptInterpreter* script_interpreter = thread->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002099 if (RunScriptFormatKeyword (s, script_interpreter, thread, script_name))
2100 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002101 }
Jason Molenda705b1802014-06-13 02:37:02 +00002102 else if (IsToken (var_name_begin, "info."))
2103 {
2104 var_name_begin += ::strlen("info.");
2105 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
2106 if (object_sp && object_sp->GetType() == StructuredData::Type::eTypeDictionary)
2107 {
2108 var_success = FormatThreadExtendedInfoRecurse (var_name_begin, object_sp, sc, exe_ctx, s);
2109 }
2110 }
Greg Clayton1b654882010-09-19 02:33:57 +00002111 }
2112 }
2113 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002114 else if (IsToken (var_name_begin, "target."))
Greg Clayton1b654882010-09-19 02:33:57 +00002115 {
Greg Clayton67cc0632012-08-22 17:17:09 +00002116 // TODO: hookup properties
2117// if (!target_properties_sp)
2118// {
2119// Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2120// if (target)
2121// target_properties_sp = target->GetProperties();
2122// }
2123//
2124// if (target_properties_sp)
2125// {
2126// var_name_begin += ::strlen ("target.");
2127// const char *end_property = strchr(var_name_begin, '}');
2128// if (end_property)
2129// {
2130// ConstString property_name(var_name_begin, end_property - var_name_begin);
2131// std::string property_value (target_properties_sp->GetPropertyValue(property_name));
2132// if (!property_value.empty())
2133// {
2134// s.PutCString (property_value.c_str());
2135// var_success = true;
2136// }
2137// }
2138// }
Greg Clayton0603aa92010-10-04 01:05:56 +00002139 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2140 if (target)
Greg Clayton1b654882010-09-19 02:33:57 +00002141 {
Greg Clayton1b654882010-09-19 02:33:57 +00002142 var_name_begin += ::strlen ("target.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002143 if (IsToken (var_name_begin, "arch}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002144 {
2145 ArchSpec arch (target->GetArchitecture ());
2146 if (arch.IsValid())
2147 {
Greg Clayton64195a22011-02-23 00:35:02 +00002148 s.PutCString (arch.GetArchitectureName());
Greg Clayton1b654882010-09-19 02:33:57 +00002149 var_success = true;
2150 }
2151 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002152 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002153 {
2154 var_name_begin += ::strlen("script:");
2155 std::string script_name(var_name_begin,var_name_end);
2156 ScriptInterpreter* script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002157 if (RunScriptFormatKeyword (s, script_interpreter, target, script_name))
2158 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002159 }
Greg Clayton67cc0632012-08-22 17:17:09 +00002160 }
Greg Clayton1b654882010-09-19 02:33:57 +00002161 }
2162 break;
2163
2164
2165 case 'm':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002166 if (IsToken (var_name_begin, "module."))
Greg Clayton1b654882010-09-19 02:33:57 +00002167 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002168 if (sc && sc->module_sp.get())
Greg Clayton1b654882010-09-19 02:33:57 +00002169 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002170 Module *module = sc->module_sp.get();
Greg Clayton1b654882010-09-19 02:33:57 +00002171 var_name_begin += ::strlen ("module.");
2172
Michael Sartain0769b2b2013-07-30 16:44:36 +00002173 if (IsToken (var_name_begin, "file."))
Greg Clayton1b654882010-09-19 02:33:57 +00002174 {
2175 if (module->GetFileSpec())
2176 {
2177 var_name_begin += ::strlen ("file.");
2178
Michael Sartain0769b2b2013-07-30 16:44:36 +00002179 if (IsToken (var_name_begin, "basename}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002180 {
2181 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002182 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002183 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002184 else if (IsToken (var_name_begin, "fullpath}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002185 {
2186 format_file_spec = module->GetFileSpec();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002187 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002188 }
2189 }
2190 }
2191 }
2192 }
2193 break;
2194
2195
2196 case 'f':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002197 if (IsToken (var_name_begin, "file."))
Greg Clayton1b654882010-09-19 02:33:57 +00002198 {
2199 if (sc && sc->comp_unit != NULL)
2200 {
2201 var_name_begin += ::strlen ("file.");
2202
Michael Sartain0769b2b2013-07-30 16:44:36 +00002203 if (IsToken (var_name_begin, "basename}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002204 {
2205 format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002206 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002207 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002208 else if (IsToken (var_name_begin, "fullpath}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002209 {
2210 format_file_spec = *sc->comp_unit;
Sean Callanan9076c0f2013-10-04 21:35:29 +00002211 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002212 }
2213 }
2214 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002215 else if (IsToken (var_name_begin, "frame."))
Greg Clayton1b654882010-09-19 02:33:57 +00002216 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002217 if (exe_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00002218 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002219 StackFrame *frame = exe_ctx->GetFramePtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002220 if (frame)
Greg Clayton1b654882010-09-19 02:33:57 +00002221 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002222 var_name_begin += ::strlen ("frame.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002223 if (IsToken (var_name_begin, "index}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002224 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002225 s.Printf("%u", frame->GetFrameIndex());
2226 var_success = true;
2227 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002228 else if (IsToken (var_name_begin, "pc}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002229 {
2230 reg_kind = eRegisterKindGeneric;
2231 reg_num = LLDB_REGNUM_GENERIC_PC;
2232 var_success = true;
2233 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002234 else if (IsToken (var_name_begin, "sp}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002235 {
2236 reg_kind = eRegisterKindGeneric;
2237 reg_num = LLDB_REGNUM_GENERIC_SP;
2238 var_success = true;
2239 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002240 else if (IsToken (var_name_begin, "fp}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002241 {
2242 reg_kind = eRegisterKindGeneric;
2243 reg_num = LLDB_REGNUM_GENERIC_FP;
2244 var_success = true;
2245 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002246 else if (IsToken (var_name_begin, "flags}"))
Greg Claytonc14ee322011-09-22 04:58:26 +00002247 {
2248 reg_kind = eRegisterKindGeneric;
2249 reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2250 var_success = true;
2251 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002252 else if (IsToken (var_name_begin, "reg."))
Greg Claytonc14ee322011-09-22 04:58:26 +00002253 {
2254 reg_ctx = frame->GetRegisterContext().get();
2255 if (reg_ctx)
Greg Clayton1b654882010-09-19 02:33:57 +00002256 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002257 var_name_begin += ::strlen ("reg.");
2258 if (var_name_begin < var_name_end)
2259 {
2260 std::string reg_name (var_name_begin, var_name_end);
2261 reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2262 if (reg_info)
2263 var_success = true;
2264 }
Greg Clayton1b654882010-09-19 02:33:57 +00002265 }
2266 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002267 else if (IsToken (var_name_begin, "script:"))
Enrico Granataaad8e482013-06-20 23:40:21 +00002268 {
2269 var_name_begin += ::strlen("script:");
2270 std::string script_name(var_name_begin,var_name_end);
2271 ScriptInterpreter* script_interpreter = frame->GetThread()->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Michael Sartain0769b2b2013-07-30 16:44:36 +00002272 if (RunScriptFormatKeyword (s, script_interpreter, frame, script_name))
2273 var_success = true;
Enrico Granataaad8e482013-06-20 23:40:21 +00002274 }
Greg Clayton1b654882010-09-19 02:33:57 +00002275 }
2276 }
2277 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002278 else if (IsToken (var_name_begin, "function."))
Greg Clayton1b654882010-09-19 02:33:57 +00002279 {
2280 if (sc && (sc->function != NULL || sc->symbol != NULL))
2281 {
2282 var_name_begin += ::strlen ("function.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002283 if (IsToken (var_name_begin, "id}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002284 {
2285 if (sc->function)
Daniel Malead01b2952012-11-29 21:49:15 +00002286 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
Greg Clayton1b654882010-09-19 02:33:57 +00002287 else
2288 s.Printf("symbol[%u]", sc->symbol->GetID());
2289
2290 var_success = true;
2291 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002292 else if (IsToken (var_name_begin, "name}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002293 {
2294 if (sc->function)
2295 cstr = sc->function->GetName().AsCString (NULL);
2296 else if (sc->symbol)
2297 cstr = sc->symbol->GetName().AsCString (NULL);
2298 if (cstr)
2299 {
2300 s.PutCString(cstr);
Greg Clayton0d9c9932010-10-04 17:26:49 +00002301
2302 if (sc->block)
2303 {
2304 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2305 if (inline_block)
2306 {
2307 const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2308 if (inline_info)
2309 {
2310 s.PutCString(" [inlined] ");
2311 inline_info->GetName().Dump(&s);
2312 }
2313 }
2314 }
Greg Clayton1b654882010-09-19 02:33:57 +00002315 var_success = true;
2316 }
2317 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002318 else if (IsToken (var_name_begin, "name-with-args}"))
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002319 {
2320 // Print the function name with arguments in it
2321
2322 if (sc->function)
2323 {
2324 var_success = true;
2325 ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2326 cstr = sc->function->GetName().AsCString (NULL);
2327 if (cstr)
2328 {
2329 const InlineFunctionInfo *inline_info = NULL;
2330 VariableListSP variable_list_sp;
2331 bool get_function_vars = true;
2332 if (sc->block)
2333 {
2334 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2335
2336 if (inline_block)
2337 {
2338 get_function_vars = false;
2339 inline_info = sc->block->GetInlinedFunctionInfo();
2340 if (inline_info)
2341 variable_list_sp = inline_block->GetBlockVariableList (true);
2342 }
2343 }
2344
2345 if (get_function_vars)
2346 {
2347 variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2348 }
2349
2350 if (inline_info)
2351 {
2352 s.PutCString (cstr);
2353 s.PutCString (" [inlined] ");
2354 cstr = inline_info->GetName().GetCString();
2355 }
2356
2357 VariableList args;
2358 if (variable_list_sp)
Enrico Granatacc7f9bf2013-05-08 20:27:37 +00002359 variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002360 if (args.GetSize() > 0)
2361 {
2362 const char *open_paren = strchr (cstr, '(');
Enrico Granatae4a4f5d2014-08-16 00:56:04 +00002363 const char *close_paren = nullptr;
2364 const char *generic = strchr(cstr, '<');
2365 // if before the arguments list begins there is a template sign
2366 // then scan to the end of the generic args before you try to find
2367 // the arguments list
2368 if (generic && open_paren && generic < open_paren)
2369 {
2370 int generic_depth = 1;
2371 ++generic;
2372 for (;
2373 *generic && generic_depth > 0;
2374 generic++)
2375 {
2376 if (*generic == '<')
2377 generic_depth++;
2378 if (*generic == '>')
2379 generic_depth--;
2380 }
2381 if (*generic)
2382 open_paren = strchr(generic, '(');
2383 else
2384 open_paren = nullptr;
2385 }
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002386 if (open_paren)
Greg Clayton855958c2013-03-26 01:45:43 +00002387 {
Michael Sartain0769b2b2013-07-30 16:44:36 +00002388 if (IsToken (open_paren, "(anonymous namespace)"))
Greg Clayton855958c2013-03-26 01:45:43 +00002389 {
2390 open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2391 if (open_paren)
2392 close_paren = strchr (open_paren, ')');
2393 }
2394 else
2395 close_paren = strchr (open_paren, ')');
2396 }
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002397
2398 if (open_paren)
2399 s.Write(cstr, open_paren - cstr + 1);
2400 else
2401 {
2402 s.PutCString (cstr);
2403 s.PutChar ('(');
2404 }
Greg Clayton5b6889b2012-01-18 21:56:18 +00002405 const size_t num_args = args.GetSize();
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002406 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2407 {
Enrico Granata894f7352014-03-25 22:03:52 +00002408 std::string buffer;
2409
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002410 VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2411 ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
Enrico Granata894f7352014-03-25 22:03:52 +00002412 const char *var_representation = nullptr;
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002413 const char *var_name = var_value_sp->GetName().GetCString();
Enrico Granata894f7352014-03-25 22:03:52 +00002414 if (var_value_sp->GetClangType().IsAggregateType() &&
2415 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp.get()))
2416 {
2417 static StringSummaryFormat format(TypeSummaryImpl::Flags()
2418 .SetHideItemNames(false)
2419 .SetShowMembersOneLiner(true),
2420 "");
2421 format.FormatObject(var_value_sp.get(), buffer);
2422 var_representation = buffer.c_str();
2423 }
2424 else
2425 var_representation = var_value_sp->GetValueAsCString();
Greg Clayton3b188b12012-12-10 22:26:34 +00002426 if (arg_idx > 0)
2427 s.PutCString (", ");
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002428 if (var_value_sp->GetError().Success())
Enrico Granatacc7f9bf2013-05-08 20:27:37 +00002429 {
Enrico Granata894f7352014-03-25 22:03:52 +00002430 if (var_representation)
2431 s.Printf ("%s=%s", var_name, var_representation);
Enrico Granatacc7f9bf2013-05-08 20:27:37 +00002432 else
2433 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2434 }
Greg Clayton3b188b12012-12-10 22:26:34 +00002435 else
2436 s.Printf ("%s=<unavailable>", var_name);
Greg Clayton6d3dbf52012-01-13 08:39:16 +00002437 }
2438
2439 if (close_paren)
2440 s.PutCString (close_paren);
2441 else
2442 s.PutChar(')');
2443
2444 }
2445 else
2446 {
2447 s.PutCString(cstr);
2448 }
2449 }
2450 }
2451 else if (sc->symbol)
2452 {
2453 cstr = sc->symbol->GetName().AsCString (NULL);
2454 if (cstr)
2455 {
2456 s.PutCString(cstr);
2457 var_success = true;
2458 }
2459 }
2460 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002461 else if (IsToken (var_name_begin, "addr-offset}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002462 {
2463 var_success = addr != NULL;
2464 if (var_success)
2465 {
2466 format_addr = *addr;
2467 calculate_format_addr_function_offset = true;
2468 }
2469 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002470 else if (IsToken (var_name_begin, "line-offset}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002471 {
2472 var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2473 if (var_success)
2474 {
2475 format_addr = sc->line_entry.range.GetBaseAddress();
2476 calculate_format_addr_function_offset = true;
2477 }
2478 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002479 else if (IsToken (var_name_begin, "pc-offset}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002480 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002481 StackFrame *frame = exe_ctx->GetFramePtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002482 var_success = frame != NULL;
Greg Clayton1b654882010-09-19 02:33:57 +00002483 if (var_success)
2484 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002485 format_addr = frame->GetFrameCodeAddress();
Greg Clayton1b654882010-09-19 02:33:57 +00002486 calculate_format_addr_function_offset = true;
2487 }
2488 }
2489 }
2490 }
2491 break;
2492
2493 case 'l':
Michael Sartain0769b2b2013-07-30 16:44:36 +00002494 if (IsToken (var_name_begin, "line."))
Greg Clayton1b654882010-09-19 02:33:57 +00002495 {
2496 if (sc && sc->line_entry.IsValid())
2497 {
2498 var_name_begin += ::strlen ("line.");
Michael Sartain0769b2b2013-07-30 16:44:36 +00002499 if (IsToken (var_name_begin, "file."))
Greg Clayton1b654882010-09-19 02:33:57 +00002500 {
2501 var_name_begin += ::strlen ("file.");
2502
Michael Sartain0769b2b2013-07-30 16:44:36 +00002503 if (IsToken (var_name_begin, "basename}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002504 {
2505 format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
Sean Callanan9076c0f2013-10-04 21:35:29 +00002506 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002507 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002508 else if (IsToken (var_name_begin, "fullpath}"))
Greg Clayton1b654882010-09-19 02:33:57 +00002509 {
2510 format_file_spec = sc->line_entry.file;
Sean Callanan9076c0f2013-10-04 21:35:29 +00002511 var_success = (bool)format_file_spec;
Greg Clayton1b654882010-09-19 02:33:57 +00002512 }
2513 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002514 else if (IsTokenWithFormat (var_name_begin, "number", token_format, "%" PRIu64, exe_ctx, sc))
Greg Clayton1b654882010-09-19 02:33:57 +00002515 {
2516 var_success = true;
Michael Sartain0769b2b2013-07-30 16:44:36 +00002517 s.Printf(token_format.c_str(), (uint64_t)sc->line_entry.line);
Greg Clayton1b654882010-09-19 02:33:57 +00002518 }
Michael Sartain0769b2b2013-07-30 16:44:36 +00002519 else if ((IsToken (var_name_begin, "start-addr}")) ||
2520 (IsToken (var_name_begin, "end-addr}")))
Greg Clayton1b654882010-09-19 02:33:57 +00002521 {
2522 var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2523 if (var_success)
2524 {
2525 format_addr = sc->line_entry.range.GetBaseAddress();
2526 if (var_name_begin[0] == 'e')
2527 format_addr.Slide (sc->line_entry.range.GetByteSize());
2528 }
2529 }
2530 }
2531 }
2532 break;
2533 }
2534
2535 if (var_success)
2536 {
2537 // If format addr is valid, then we need to print an address
2538 if (reg_num != LLDB_INVALID_REGNUM)
2539 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002540 StackFrame *frame = exe_ctx->GetFramePtr();
Greg Clayton1b654882010-09-19 02:33:57 +00002541 // We have a register value to display...
2542 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2543 {
Greg Claytonc14ee322011-09-22 04:58:26 +00002544 format_addr = frame->GetFrameCodeAddress();
Greg Clayton1b654882010-09-19 02:33:57 +00002545 }
2546 else
2547 {
2548 if (reg_ctx == NULL)
Greg Claytonc14ee322011-09-22 04:58:26 +00002549 reg_ctx = frame->GetRegisterContext().get();
Greg Clayton1b654882010-09-19 02:33:57 +00002550
2551 if (reg_ctx)
2552 {
2553 if (reg_kind != kNumRegisterKinds)
2554 reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2555 reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2556 var_success = reg_info != NULL;
2557 }
2558 }
2559 }
2560
2561 if (reg_info != NULL)
2562 {
Greg Clayton7349bd92011-05-09 20:18:18 +00002563 RegisterValue reg_value;
2564 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2565 if (var_success)
Greg Clayton1b654882010-09-19 02:33:57 +00002566 {
Greg Clayton9a8fa912011-05-15 04:12:07 +00002567 reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
Greg Clayton1b654882010-09-19 02:33:57 +00002568 }
2569 }
2570
2571 if (format_file_spec)
2572 {
2573 s << format_file_spec;
2574 }
2575
2576 // If format addr is valid, then we need to print an address
2577 if (format_addr.IsValid())
2578 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002579 var_success = false;
2580
Greg Clayton1b654882010-09-19 02:33:57 +00002581 if (calculate_format_addr_function_offset)
2582 {
2583 Address func_addr;
Greg Clayton1b654882010-09-19 02:33:57 +00002584
Greg Clayton0603aa92010-10-04 01:05:56 +00002585 if (sc)
2586 {
2587 if (sc->function)
Greg Clayton0d9c9932010-10-04 17:26:49 +00002588 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002589 func_addr = sc->function->GetAddressRange().GetBaseAddress();
Greg Clayton0d9c9932010-10-04 17:26:49 +00002590 if (sc->block)
2591 {
2592 // Check to make sure we aren't in an inline
2593 // function. If we are, use the inline block
2594 // range that contains "format_addr" since
2595 // blocks can be discontiguous.
2596 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2597 AddressRange inline_range;
2598 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2599 func_addr = inline_range.GetBaseAddress();
2600 }
2601 }
Greg Claytone7612132012-03-07 21:03:09 +00002602 else if (sc->symbol && sc->symbol->ValueIsAddress())
2603 func_addr = sc->symbol->GetAddress();
Greg Clayton0603aa92010-10-04 01:05:56 +00002604 }
2605
2606 if (func_addr.IsValid())
Greg Clayton1b654882010-09-19 02:33:57 +00002607 {
2608 if (func_addr.GetSection() == format_addr.GetSection())
2609 {
2610 addr_t func_file_addr = func_addr.GetFileAddress();
2611 addr_t addr_file_addr = format_addr.GetFileAddress();
2612 if (addr_file_addr > func_file_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002613 s.Printf(" + %" PRIu64, addr_file_addr - func_file_addr);
Greg Clayton1b654882010-09-19 02:33:57 +00002614 else if (addr_file_addr < func_file_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002615 s.Printf(" - %" PRIu64, func_file_addr - addr_file_addr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002616 var_success = true;
Greg Clayton1b654882010-09-19 02:33:57 +00002617 }
2618 else
Greg Clayton0603aa92010-10-04 01:05:56 +00002619 {
2620 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2621 if (target)
2622 {
2623 addr_t func_load_addr = func_addr.GetLoadAddress (target);
2624 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2625 if (addr_load_addr > func_load_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002626 s.Printf(" + %" PRIu64, addr_load_addr - func_load_addr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002627 else if (addr_load_addr < func_load_addr)
Daniel Malead01b2952012-11-29 21:49:15 +00002628 s.Printf(" - %" PRIu64, func_load_addr - addr_load_addr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002629 var_success = true;
2630 }
2631 }
Greg Clayton1b654882010-09-19 02:33:57 +00002632 }
2633 }
2634 else
2635 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002636 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
Greg Clayton1b654882010-09-19 02:33:57 +00002637 addr_t vaddr = LLDB_INVALID_ADDRESS;
Greg Clayton0603aa92010-10-04 01:05:56 +00002638 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2639 vaddr = format_addr.GetLoadAddress (target);
Greg Clayton1b654882010-09-19 02:33:57 +00002640 if (vaddr == LLDB_INVALID_ADDRESS)
2641 vaddr = format_addr.GetFileAddress ();
2642
2643 if (vaddr != LLDB_INVALID_ADDRESS)
Greg Clayton0603aa92010-10-04 01:05:56 +00002644 {
Greg Clayton514487e2011-02-15 21:59:32 +00002645 int addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
Greg Clayton35f1a0d2010-11-19 04:16:11 +00002646 if (addr_width == 0)
2647 addr_width = 16;
Daniel Malead01b2952012-11-29 21:49:15 +00002648 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
Greg Clayton0603aa92010-10-04 01:05:56 +00002649 var_success = true;
2650 }
Greg Clayton1b654882010-09-19 02:33:57 +00002651 }
2652 }
2653 }
2654
2655 if (var_success == false)
2656 success = false;
2657 }
2658 p = var_name_end;
2659 }
2660 else
2661 break;
2662 }
2663 else
2664 {
2665 // We got a dollar sign with no '{' after it, it must just be a dollar sign
2666 s.PutChar(*p);
2667 }
2668 }
2669 else if (*p == '\\')
2670 {
2671 ++p; // skip the slash
2672 switch (*p)
2673 {
2674 case 'a': s.PutChar ('\a'); break;
2675 case 'b': s.PutChar ('\b'); break;
2676 case 'f': s.PutChar ('\f'); break;
2677 case 'n': s.PutChar ('\n'); break;
2678 case 'r': s.PutChar ('\r'); break;
2679 case 't': s.PutChar ('\t'); break;
2680 case 'v': s.PutChar ('\v'); break;
2681 case '\'': s.PutChar ('\''); break;
2682 case '\\': s.PutChar ('\\'); break;
2683 case '0':
2684 // 1 to 3 octal chars
2685 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002686 // Make a string that can hold onto the initial zero char,
2687 // up to 3 octal digits, and a terminating NULL.
2688 char oct_str[5] = { 0, 0, 0, 0, 0 };
2689
2690 int i;
2691 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2692 oct_str[i] = p[i];
2693
2694 // We don't want to consume the last octal character since
2695 // the main for loop will do this for us, so we advance p by
2696 // one less than i (even if i is zero)
2697 p += i - 1;
2698 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2699 if (octal_value <= UINT8_MAX)
Greg Clayton1b654882010-09-19 02:33:57 +00002700 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002701 s.PutChar((char)octal_value);
Greg Clayton1b654882010-09-19 02:33:57 +00002702 }
Greg Clayton1b654882010-09-19 02:33:57 +00002703 }
2704 break;
2705
2706 case 'x':
2707 // hex number in the format
Greg Clayton0603aa92010-10-04 01:05:56 +00002708 if (isxdigit(p[1]))
Greg Clayton1b654882010-09-19 02:33:57 +00002709 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002710 ++p; // Skip the 'x'
Greg Clayton1b654882010-09-19 02:33:57 +00002711
Greg Clayton0603aa92010-10-04 01:05:56 +00002712 // Make a string that can hold onto two hex chars plus a
2713 // NULL terminator
2714 char hex_str[3] = { 0,0,0 };
2715 hex_str[0] = *p;
2716 if (isxdigit(p[1]))
Greg Clayton1b654882010-09-19 02:33:57 +00002717 {
Greg Clayton0603aa92010-10-04 01:05:56 +00002718 ++p; // Skip the first of the two hex chars
2719 hex_str[1] = *p;
2720 }
2721
2722 unsigned long hex_value = strtoul (hex_str, NULL, 16);
2723 if (hex_value <= UINT8_MAX)
Greg Claytonc7bece562013-01-25 18:06:21 +00002724 s.PutChar ((char)hex_value);
Greg Clayton0603aa92010-10-04 01:05:56 +00002725 }
2726 else
2727 {
2728 s.PutChar('x');
Greg Clayton1b654882010-09-19 02:33:57 +00002729 }
2730 break;
2731
2732 default:
Greg Clayton0603aa92010-10-04 01:05:56 +00002733 // Just desensitize any other character by just printing what
2734 // came after the '\'
2735 s << *p;
Greg Clayton1b654882010-09-19 02:33:57 +00002736 break;
2737
2738 }
2739
2740 }
2741 }
2742 if (end)
2743 *end = p;
2744 return success;
2745}
2746
Michael Sartainc3ce7f272013-05-23 20:47:45 +00002747bool
2748Debugger::FormatPrompt
2749(
2750 const char *format,
2751 const SymbolContext *sc,
2752 const ExecutionContext *exe_ctx,
2753 const Address *addr,
2754 Stream &s,
2755 ValueObject* valobj
2756)
2757{
2758 bool use_color = exe_ctx ? exe_ctx->GetTargetRef().GetDebugger().GetUseColor() : true;
2759 std::string format_str = lldb_utility::ansi::FormatAnsiTerminalCodes (format, use_color);
2760 if (format_str.length())
2761 format = format_str.c_str();
2762 return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, valobj);
2763}
2764
Jim Ingham228063c2012-02-21 02:23:08 +00002765void
2766Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2767{
Jim Ingham4f02b222012-02-22 22:49:20 +00002768 // For simplicity's sake, I am not going to deal with how to close down any
2769 // open logging streams, I just redirect everything from here on out to the
2770 // callback.
Jim Ingham228063c2012-02-21 02:23:08 +00002771 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2772}
2773
2774bool
2775Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2776{
2777 Log::Callbacks log_callbacks;
2778
2779 StreamSP log_stream_sp;
Sean Callanan9a028512012-08-09 00:50:26 +00002780 if (m_log_callback_stream_sp)
Jim Ingham228063c2012-02-21 02:23:08 +00002781 {
2782 log_stream_sp = m_log_callback_stream_sp;
2783 // For now when using the callback mode you always get thread & timestamp.
2784 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2785 }
2786 else if (log_file == NULL || *log_file == '\0')
2787 {
Greg Clayton44d93782014-01-27 23:43:24 +00002788 log_stream_sp = GetOutputFile();
Jim Ingham228063c2012-02-21 02:23:08 +00002789 }
2790 else
2791 {
2792 LogStreamMap::iterator pos = m_log_streams.find(log_file);
Greg Claytonc1b2ccf2013-01-08 00:01:36 +00002793 if (pos != m_log_streams.end())
2794 log_stream_sp = pos->second.lock();
2795 if (!log_stream_sp)
Jim Ingham228063c2012-02-21 02:23:08 +00002796 {
2797 log_stream_sp.reset (new StreamFile (log_file));
2798 m_log_streams[log_file] = log_stream_sp;
2799 }
Jim Ingham228063c2012-02-21 02:23:08 +00002800 }
2801 assert (log_stream_sp.get());
2802
2803 if (log_options == 0)
2804 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2805
Greg Clayton57abc5d2013-05-10 21:47:16 +00002806 if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
Jim Ingham228063c2012-02-21 02:23:08 +00002807 {
2808 log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2809 return true;
2810 }
2811 else
2812 {
2813 LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2814 if (log_channel_sp)
2815 {
2816 if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2817 {
2818 return true;
2819 }
2820 else
2821 {
2822 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2823 return false;
2824 }
2825 }
2826 else
2827 {
2828 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2829 return false;
2830 }
2831 }
2832 return false;
2833}
2834
Greg Clayton9585fbf2013-03-19 00:20:55 +00002835SourceManager &
2836Debugger::GetSourceManager ()
2837{
2838 if (m_source_manager_ap.get() == NULL)
2839 m_source_manager_ap.reset (new SourceManager (shared_from_this()));
2840 return *m_source_manager_ap;
2841}
2842
2843
Greg Clayton44d93782014-01-27 23:43:24 +00002844
2845// This function handles events that were broadcast by the process.
2846void
2847Debugger::HandleBreakpointEvent (const EventSP &event_sp)
2848{
2849 using namespace lldb;
2850 const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
2851
2852// if (event_type & eBreakpointEventTypeAdded
2853// || event_type & eBreakpointEventTypeRemoved
2854// || event_type & eBreakpointEventTypeEnabled
2855// || event_type & eBreakpointEventTypeDisabled
2856// || event_type & eBreakpointEventTypeCommandChanged
2857// || event_type & eBreakpointEventTypeConditionChanged
2858// || event_type & eBreakpointEventTypeIgnoreChanged
2859// || event_type & eBreakpointEventTypeLocationsResolved)
2860// {
2861// // Don't do anything about these events, since the breakpoint commands already echo these actions.
2862// }
2863//
2864 if (event_type & eBreakpointEventTypeLocationsAdded)
2865 {
2866 uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
2867 if (num_new_locations > 0)
2868 {
2869 BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
2870 StreamFileSP output_sp (GetOutputFile());
2871 if (output_sp)
2872 {
2873 output_sp->Printf("%d location%s added to breakpoint %d\n",
2874 num_new_locations,
2875 num_new_locations == 1 ? "" : "s",
2876 breakpoint->GetID());
2877 RefreshTopIOHandler();
2878 }
2879 }
2880 }
2881// else if (event_type & eBreakpointEventTypeLocationsRemoved)
2882// {
2883// // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
2884// }
2885// else if (event_type & eBreakpointEventTypeLocationsResolved)
2886// {
2887// // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
2888// }
2889}
2890
2891size_t
2892Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
2893{
2894 size_t total_bytes = 0;
2895 if (stream == NULL)
2896 stream = GetOutputFile().get();
2897
2898 if (stream)
2899 {
2900 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
2901 if (process == NULL)
2902 {
2903 TargetSP target_sp = GetTargetList().GetSelectedTarget();
2904 if (target_sp)
2905 process = target_sp->GetProcessSP().get();
2906 }
2907 if (process)
2908 {
2909 Error error;
2910 size_t len;
2911 char stdio_buffer[1024];
2912 while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2913 {
2914 stream->Write(stdio_buffer, len);
2915 total_bytes += len;
2916 }
2917 }
2918 stream->Flush();
2919 }
2920 return total_bytes;
2921}
2922
2923size_t
2924Debugger::GetProcessSTDERR (Process *process, Stream *stream)
2925{
2926 size_t total_bytes = 0;
2927 if (stream == NULL)
2928 stream = GetOutputFile().get();
2929
2930 if (stream)
2931 {
2932 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2933 if (process == NULL)
2934 {
2935 TargetSP target_sp = GetTargetList().GetSelectedTarget();
2936 if (target_sp)
2937 process = target_sp->GetProcessSP().get();
2938 }
2939 if (process)
2940 {
2941 Error error;
2942 size_t len;
2943 char stdio_buffer[1024];
2944 while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2945 {
2946 stream->Write(stdio_buffer, len);
2947 total_bytes += len;
2948 }
2949 }
2950 stream->Flush();
2951 }
2952 return total_bytes;
2953}
2954
2955// This function handles events that were broadcast by the process.
2956void
2957Debugger::HandleProcessEvent (const EventSP &event_sp)
2958{
2959 using namespace lldb;
2960 const uint32_t event_type = event_sp->GetType();
2961 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
2962
Greg Claytonb4874f12014-02-28 18:22:24 +00002963 StreamString output_stream;
2964 StreamString error_stream;
Greg Clayton44d93782014-01-27 23:43:24 +00002965 const bool gui_enabled = IsForwardingEvents();
Greg Clayton44d93782014-01-27 23:43:24 +00002966
Greg Claytonb4874f12014-02-28 18:22:24 +00002967 if (!gui_enabled)
2968 {
2969 bool pop_process_io_handler = false;
2970 assert (process_sp);
Greg Clayton44d93782014-01-27 23:43:24 +00002971
Greg Claytonb4874f12014-02-28 18:22:24 +00002972 if (event_type & Process::eBroadcastBitSTDOUT || event_type & Process::eBroadcastBitStateChanged)
Greg Clayton44d93782014-01-27 23:43:24 +00002973 {
Greg Claytonb4874f12014-02-28 18:22:24 +00002974 GetProcessSTDOUT (process_sp.get(), &output_stream);
2975 }
2976
2977 if (event_type & Process::eBroadcastBitSTDERR || event_type & Process::eBroadcastBitStateChanged)
2978 {
2979 GetProcessSTDERR (process_sp.get(), &error_stream);
2980 }
2981
2982 if (event_type & Process::eBroadcastBitStateChanged)
2983 {
2984
2985 // Drain all stout and stderr so we don't see any output come after
2986 // we print our prompts
Greg Clayton44d93782014-01-27 23:43:24 +00002987 // Something changed in the process; get the event and report the process's current status and location to
2988 // the user.
2989 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
2990 if (event_state == eStateInvalid)
2991 return;
2992
2993 switch (event_state)
2994 {
2995 case eStateInvalid:
2996 case eStateUnloaded:
2997 case eStateConnected:
2998 case eStateAttaching:
2999 case eStateLaunching:
3000 case eStateStepping:
3001 case eStateDetached:
3002 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003003 output_stream.Printf("Process %" PRIu64 " %s\n",
3004 process_sp->GetID(),
3005 StateAsCString (event_state));
3006
3007 if (event_state == eStateDetached)
3008 pop_process_io_handler = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003009 }
3010 break;
3011
3012 case eStateRunning:
3013 // Don't be chatty when we run...
3014 break;
3015
3016 case eStateExited:
Greg Claytonb4874f12014-02-28 18:22:24 +00003017 process_sp->GetStatus(output_stream);
3018 pop_process_io_handler = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003019 break;
3020
3021 case eStateStopped:
3022 case eStateCrashed:
3023 case eStateSuspended:
3024 // Make sure the program hasn't been auto-restarted:
3025 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
3026 {
3027 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
3028 if (num_reasons > 0)
3029 {
3030 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
3031 if (num_reasons == 1)
3032 {
3033 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
Greg Claytonb4874f12014-02-28 18:22:24 +00003034 output_stream.Printf("Process %" PRIu64 " stopped and restarted: %s\n",
3035 process_sp->GetID(),
3036 reason ? reason : "<UNKNOWN REASON>");
Greg Clayton44d93782014-01-27 23:43:24 +00003037 }
3038 else
3039 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003040 output_stream.Printf("Process %" PRIu64 " stopped and restarted, reasons:\n",
3041 process_sp->GetID());
Greg Clayton44d93782014-01-27 23:43:24 +00003042
3043
3044 for (size_t i = 0; i < num_reasons; i++)
3045 {
3046 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
Greg Claytonb4874f12014-02-28 18:22:24 +00003047 output_stream.Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
Greg Clayton44d93782014-01-27 23:43:24 +00003048 }
3049 }
3050 }
3051 }
3052 else
3053 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003054 // 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 +00003055 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003056 ThreadList &thread_list = process_sp->GetThreadList();
3057 Mutex::Locker locker (thread_list.GetMutex());
3058
3059 ThreadSP curr_thread (thread_list.GetSelectedThread());
3060 ThreadSP thread;
3061 StopReason curr_thread_stop_reason = eStopReasonInvalid;
3062 if (curr_thread)
3063 curr_thread_stop_reason = curr_thread->GetStopReason();
3064 if (!curr_thread ||
3065 !curr_thread->IsValid() ||
3066 curr_thread_stop_reason == eStopReasonInvalid ||
3067 curr_thread_stop_reason == eStopReasonNone)
Greg Clayton44d93782014-01-27 23:43:24 +00003068 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003069 // Prefer a thread that has just completed its plan over another thread as current thread.
3070 ThreadSP plan_thread;
3071 ThreadSP other_thread;
3072 const size_t num_threads = thread_list.GetSize();
3073 size_t i;
3074 for (i = 0; i < num_threads; ++i)
Greg Clayton44d93782014-01-27 23:43:24 +00003075 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00003076 thread = thread_list.GetThreadAtIndex(i);
3077 StopReason thread_stop_reason = thread->GetStopReason();
3078 switch (thread_stop_reason)
3079 {
3080 case eStopReasonInvalid:
3081 case eStopReasonNone:
3082 break;
3083
3084 case eStopReasonTrace:
3085 case eStopReasonBreakpoint:
3086 case eStopReasonWatchpoint:
3087 case eStopReasonSignal:
3088 case eStopReasonException:
3089 case eStopReasonExec:
3090 case eStopReasonThreadExiting:
3091 if (!other_thread)
3092 other_thread = thread;
3093 break;
3094 case eStopReasonPlanComplete:
3095 if (!plan_thread)
3096 plan_thread = thread;
3097 break;
3098 }
3099 }
3100 if (plan_thread)
3101 thread_list.SetSelectedThreadByID (plan_thread->GetID());
3102 else if (other_thread)
3103 thread_list.SetSelectedThreadByID (other_thread->GetID());
3104 else
3105 {
3106 if (curr_thread && curr_thread->IsValid())
3107 thread = curr_thread;
3108 else
3109 thread = thread_list.GetThreadAtIndex(0);
3110
3111 if (thread)
3112 thread_list.SetSelectedThreadByID (thread->GetID());
Greg Clayton44d93782014-01-27 23:43:24 +00003113 }
3114 }
Greg Clayton44d93782014-01-27 23:43:24 +00003115 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00003116 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
3117 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
3118 // have a hard time restarting the process.
Greg Clayton44d93782014-01-27 23:43:24 +00003119
3120 if (GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
3121 {
3122 const bool only_threads_with_stop_reason = true;
3123 const uint32_t start_frame = 0;
3124 const uint32_t num_frames = 1;
3125 const uint32_t num_frames_with_source = 1;
Greg Claytonb4874f12014-02-28 18:22:24 +00003126 process_sp->GetStatus(output_stream);
3127 process_sp->GetThreadStatus (output_stream,
Greg Clayton44d93782014-01-27 23:43:24 +00003128 only_threads_with_stop_reason,
3129 start_frame,
3130 num_frames,
3131 num_frames_with_source);
3132 }
3133 else
3134 {
3135 uint32_t target_idx = GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
3136 if (target_idx != UINT32_MAX)
Greg Claytonb4874f12014-02-28 18:22:24 +00003137 output_stream.Printf ("Target %d: (", target_idx);
Greg Clayton44d93782014-01-27 23:43:24 +00003138 else
Greg Claytonb4874f12014-02-28 18:22:24 +00003139 output_stream.Printf ("Target <unknown index>: (");
3140 process_sp->GetTarget().Dump (&output_stream, eDescriptionLevelBrief);
3141 output_stream.Printf (") stopped.\n");
Greg Clayton44d93782014-01-27 23:43:24 +00003142 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003143
3144 // Pop the process IO handler
3145 pop_process_io_handler = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003146 }
3147 break;
3148 }
3149 }
Greg Clayton44d93782014-01-27 23:43:24 +00003150
Greg Claytonb4874f12014-02-28 18:22:24 +00003151 if (output_stream.GetSize() || error_stream.GetSize())
3152 {
3153 StreamFileSP error_stream_sp (GetOutputFile());
Greg Clayton6fea17e2014-03-03 19:15:20 +00003154 bool top_io_handler_hid = false;
3155
3156 if (process_sp->ProcessIOHandlerIsActive() == false)
3157 top_io_handler_hid = HideTopIOHandler();
Greg Claytonb4874f12014-02-28 18:22:24 +00003158
3159 if (output_stream.GetSize())
3160 {
3161 StreamFileSP output_stream_sp (GetOutputFile());
3162 if (output_stream_sp)
3163 output_stream_sp->Write (output_stream.GetData(), output_stream.GetSize());
3164 }
3165
3166 if (error_stream.GetSize())
3167 {
3168 StreamFileSP error_stream_sp (GetErrorFile());
3169 if (error_stream_sp)
3170 error_stream_sp->Write (error_stream.GetData(), error_stream.GetSize());
3171 }
3172
3173 if (top_io_handler_hid)
3174 RefreshTopIOHandler();
3175 }
3176
3177 if (pop_process_io_handler)
3178 process_sp->PopProcessIOHandler();
3179 }
Greg Clayton44d93782014-01-27 23:43:24 +00003180}
3181
3182void
3183Debugger::HandleThreadEvent (const EventSP &event_sp)
3184{
3185 // At present the only thread event we handle is the Frame Changed event,
3186 // and all we do for that is just reprint the thread status for that thread.
3187 using namespace lldb;
3188 const uint32_t event_type = event_sp->GetType();
3189 if (event_type == Thread::eBroadcastBitStackChanged ||
3190 event_type == Thread::eBroadcastBitThreadSelected )
3191 {
3192 ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
3193 if (thread_sp)
3194 {
3195 HideTopIOHandler();
3196 StreamFileSP stream_sp (GetOutputFile());
3197 thread_sp->GetStatus(*stream_sp, 0, 1, 1);
3198 RefreshTopIOHandler();
3199 }
3200 }
3201}
3202
3203bool
3204Debugger::IsForwardingEvents ()
3205{
3206 return (bool)m_forward_listener_sp;
3207}
3208
3209void
3210Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
3211{
3212 m_forward_listener_sp = listener_sp;
3213}
3214
3215void
3216Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
3217{
3218 m_forward_listener_sp.reset();
3219}
3220
3221
3222void
3223Debugger::DefaultEventHandler()
3224{
3225 Listener& listener(GetListener());
3226 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
3227 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
3228 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
3229 BroadcastEventSpec target_event_spec (broadcaster_class_target,
3230 Target::eBroadcastBitBreakpointChanged);
3231
3232 BroadcastEventSpec process_event_spec (broadcaster_class_process,
3233 Process::eBroadcastBitStateChanged |
3234 Process::eBroadcastBitSTDOUT |
3235 Process::eBroadcastBitSTDERR);
3236
3237 BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
3238 Thread::eBroadcastBitStackChanged |
3239 Thread::eBroadcastBitThreadSelected );
3240
3241 listener.StartListeningForEventSpec (*this, target_event_spec);
3242 listener.StartListeningForEventSpec (*this, process_event_spec);
3243 listener.StartListeningForEventSpec (*this, thread_event_spec);
3244 listener.StartListeningForEvents (m_command_interpreter_ap.get(),
3245 CommandInterpreter::eBroadcastBitQuitCommandReceived |
3246 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
3247 CommandInterpreter::eBroadcastBitAsynchronousErrorData );
3248
3249 bool done = false;
3250 while (!done)
3251 {
3252// Mutex::Locker locker;
3253// if (locker.TryLock(m_input_reader_stack.GetMutex()))
3254// {
3255// if (m_input_reader_stack.IsEmpty())
3256// break;
3257// }
3258//
3259 EventSP event_sp;
3260 if (listener.WaitForEvent(NULL, event_sp))
3261 {
3262 if (event_sp)
3263 {
3264 Broadcaster *broadcaster = event_sp->GetBroadcaster();
3265 if (broadcaster)
3266 {
3267 uint32_t event_type = event_sp->GetType();
3268 ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
3269 if (broadcaster_class == broadcaster_class_process)
3270 {
3271 HandleProcessEvent (event_sp);
3272 }
3273 else if (broadcaster_class == broadcaster_class_target)
3274 {
3275 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
3276 {
3277 HandleBreakpointEvent (event_sp);
3278 }
3279 }
3280 else if (broadcaster_class == broadcaster_class_thread)
3281 {
3282 HandleThreadEvent (event_sp);
3283 }
3284 else if (broadcaster == m_command_interpreter_ap.get())
3285 {
3286 if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
3287 {
3288 done = true;
3289 }
3290 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
3291 {
3292 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3293 if (data && data[0])
3294 {
3295 StreamFileSP error_sp (GetErrorFile());
3296 if (error_sp)
3297 {
3298 HideTopIOHandler();
3299 error_sp->PutCString(data);
3300 error_sp->Flush();
3301 RefreshTopIOHandler();
3302 }
3303 }
3304 }
3305 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
3306 {
3307 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3308 if (data && data[0])
3309 {
3310 StreamFileSP output_sp (GetOutputFile());
3311 if (output_sp)
3312 {
3313 HideTopIOHandler();
3314 output_sp->PutCString(data);
3315 output_sp->Flush();
3316 RefreshTopIOHandler();
3317 }
3318 }
3319 }
3320 }
3321 }
3322
3323 if (m_forward_listener_sp)
3324 m_forward_listener_sp->AddEvent(event_sp);
3325 }
3326 }
3327 }
3328}
3329
3330lldb::thread_result_t
3331Debugger::EventHandlerThread (lldb::thread_arg_t arg)
3332{
3333 ((Debugger *)arg)->DefaultEventHandler();
3334 return NULL;
3335}
3336
3337bool
3338Debugger::StartEventHandlerThread()
3339{
3340 if (!IS_VALID_LLDB_HOST_THREAD(m_event_handler_thread))
3341 m_event_handler_thread = Host::ThreadCreate("lldb.debugger.event-handler", EventHandlerThread, this, NULL);
3342 return IS_VALID_LLDB_HOST_THREAD(m_event_handler_thread);
3343}
3344
3345void
3346Debugger::StopEventHandlerThread()
3347{
3348 if (IS_VALID_LLDB_HOST_THREAD(m_event_handler_thread))
3349 {
3350 GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
3351 Host::ThreadJoin(m_event_handler_thread, NULL, NULL);
3352 m_event_handler_thread = LLDB_INVALID_HOST_THREAD;
3353 }
3354}
3355
3356
3357lldb::thread_result_t
3358Debugger::IOHandlerThread (lldb::thread_arg_t arg)
3359{
3360 Debugger *debugger = (Debugger *)arg;
3361 debugger->ExecuteIOHanders();
3362 debugger->StopEventHandlerThread();
3363 return NULL;
3364}
3365
3366bool
3367Debugger::StartIOHandlerThread()
3368{
3369 if (!IS_VALID_LLDB_HOST_THREAD(m_io_handler_thread))
3370 m_io_handler_thread = Host::ThreadCreate("lldb.debugger.io-handler", IOHandlerThread, this, NULL);
3371 return IS_VALID_LLDB_HOST_THREAD(m_io_handler_thread);
3372}
3373
3374void
3375Debugger::StopIOHandlerThread()
3376{
3377 if (IS_VALID_LLDB_HOST_THREAD(m_io_handler_thread))
3378 {
3379 if (m_input_file_sp)
3380 m_input_file_sp->GetFile().Close();
3381 Host::ThreadJoin(m_io_handler_thread, NULL, NULL);
3382 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
3383 }
3384}
3385
3386