1 //===-- FormatEntity.cpp ----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ADT/StringRef.h"
12 #include "lldb/Core/FormatEntity.h"
14 #include "lldb/Core/Address.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Language.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/Stream.h"
19 #include "lldb/Core/StreamString.h"
20 #include "lldb/Core/ValueObject.h"
21 #include "lldb/Core/ValueObjectVariable.h"
22 #include "lldb/DataFormatters/DataVisualization.h"
23 #include "lldb/DataFormatters/FormatManager.h"
24 #include "lldb/Expression/ClangExpressionVariable.h"
25 #include "lldb/Host/FileSpec.h"
26 #include "lldb/Interpreter/CommandInterpreter.h"
27 #include "lldb/Symbol/Block.h"
28 #include "lldb/Symbol/CompileUnit.h"
29 #include "lldb/Symbol/Function.h"
30 #include "lldb/Symbol/LineEntry.h"
31 #include "lldb/Symbol/Symbol.h"
32 #include "lldb/Symbol/VariableList.h"
33 #include "lldb/Target/ExecutionContext.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/RegisterContext.h"
36 #include "lldb/Target/SectionLoadList.h"
37 #include "lldb/Target/StackFrame.h"
38 #include "lldb/Target/StopInfo.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Utility/AnsiTerminal.h"
44 using namespace lldb_private;
55 #define ENTRY(n,t,f) { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, 0,0,NULL, false}
56 #define ENTRY_VALUE(n,t,f,v) { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, v,0,NULL, false}
57 #define ENTRY_CHILDREN(n,t,f,c) { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, 0,llvm::array_lengthof(c),c, false}
58 #define ENTRY_CHILDREN_KEEP_SEP(n,t,f,c) { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, 0,llvm::array_lengthof(c),c, true}
59 #define ENTRY_STRING(n,s) { n, s, FormatEntity::Entry::Type::InsertString, FormatEntity::Entry::FormatType::None, 0,0, NULL, false}
60 static FormatEntity::Entry::Definition g_string_entry[] =
62 ENTRY("*", ParentString, None)
65 static FormatEntity::Entry::Definition g_addr_entries[] =
67 ENTRY ("load", AddressLoad , UInt64),
68 ENTRY ("file", AddressFile , UInt64),
69 ENTRY ("load", AddressLoadOrFile, UInt64),
72 static FormatEntity::Entry::Definition g_file_child_entries[] =
74 ENTRY_VALUE("basename", ParentNumber, CString, FileKind::Basename),
75 ENTRY_VALUE("dirname", ParentNumber, CString, FileKind::Dirname),
76 ENTRY_VALUE("fullpath", ParentNumber, CString, FileKind::Fullpath)
79 static FormatEntity::Entry::Definition g_frame_child_entries[] =
82 ENTRY ("index", FrameIndex , UInt32),
83 ENTRY ("pc" , FrameRegisterPC , UInt64),
84 ENTRY ("fp" , FrameRegisterFP , UInt64),
85 ENTRY ("sp" , FrameRegisterSP , UInt64),
86 ENTRY ("flags", FrameRegisterFlags, UInt64),
87 ENTRY_CHILDREN ("reg", FrameRegisterByName, UInt64, g_string_entry),
90 static FormatEntity::Entry::Definition g_function_child_entries[] =
92 ENTRY ("id" , FunctionID , UInt64),
93 ENTRY ("name" , FunctionName , CString),
94 ENTRY ("name-without-args" , FunctionNameNoArgs , CString),
95 ENTRY ("name-with-args" , FunctionNameWithArgs , CString),
96 ENTRY ("addr-offset" , FunctionAddrOffset , UInt64),
97 ENTRY ("concrete-only-addr-offset-no-padding", FunctionAddrOffsetConcrete, UInt64),
98 ENTRY ("line-offset" , FunctionLineOffset , UInt64),
99 ENTRY ("pc-offset" , FunctionPCOffset , UInt64),
100 ENTRY ("initial-function" , FunctionInitial , None),
101 ENTRY ("changed" , FunctionChanged , None)
104 static FormatEntity::Entry::Definition g_line_child_entries[] =
106 ENTRY_CHILDREN("file", LineEntryFile , None , g_file_child_entries),
107 ENTRY("number" , LineEntryLineNumber , UInt32),
108 ENTRY("start-addr" , LineEntryStartAddress, UInt64),
109 ENTRY("end-addr" , LineEntryEndAddress , UInt64),
112 static FormatEntity::Entry::Definition g_module_child_entries[] =
114 ENTRY_CHILDREN("file", ModuleFile, None, g_file_child_entries),
117 static FormatEntity::Entry::Definition g_process_child_entries[] =
119 ENTRY ( "id" , ProcessID , UInt64 ),
120 ENTRY_VALUE ( "name" , ProcessFile , CString , FileKind::Basename),
121 ENTRY_CHILDREN ( "file" , ProcessFile , None , g_file_child_entries),
124 static FormatEntity::Entry::Definition g_svar_child_entries[] =
126 ENTRY ( "*" , ParentString , None)
129 static FormatEntity::Entry::Definition g_var_child_entries[] =
131 ENTRY ( "*" , ParentString , None)
134 static FormatEntity::Entry::Definition g_thread_child_entries[] =
136 ENTRY ( "id" , ThreadID , UInt64 ),
137 ENTRY ( "protocol_id" , ThreadProtocolID , UInt64 ),
138 ENTRY ( "index" , ThreadIndexID , UInt32 ),
139 ENTRY_CHILDREN ( "info" , ThreadInfo , None , g_string_entry),
140 ENTRY ( "queue" , ThreadQueue , CString ),
141 ENTRY ( "name" , ThreadName , CString ),
142 ENTRY ( "stop-reason" , ThreadStopReason , CString ),
143 ENTRY ( "return-value" , ThreadReturnValue , CString ),
144 ENTRY ( "completed-expression", ThreadCompletedExpression , CString ),
147 static FormatEntity::Entry::Definition g_target_child_entries[] =
149 ENTRY ( "arch" , TargetArch , CString ),
152 #define _TO_STR2(_val) #_val
153 #define _TO_STR(_val) _TO_STR2(_val)
155 static FormatEntity::Entry::Definition g_ansi_fg_entries[] =
157 ENTRY_STRING ("black" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLACK) ANSI_ESC_END),
158 ENTRY_STRING ("red" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_RED) ANSI_ESC_END),
159 ENTRY_STRING ("green" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_GREEN) ANSI_ESC_END),
160 ENTRY_STRING ("yellow" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_YELLOW) ANSI_ESC_END),
161 ENTRY_STRING ("blue" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLUE) ANSI_ESC_END),
162 ENTRY_STRING ("purple" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_PURPLE) ANSI_ESC_END),
163 ENTRY_STRING ("cyan" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_CYAN) ANSI_ESC_END),
164 ENTRY_STRING ("white" , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_WHITE) ANSI_ESC_END),
167 static FormatEntity::Entry::Definition g_ansi_bg_entries[] =
169 ENTRY_STRING ("black" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLACK) ANSI_ESC_END),
170 ENTRY_STRING ("red" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_RED) ANSI_ESC_END),
171 ENTRY_STRING ("green" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_GREEN) ANSI_ESC_END),
172 ENTRY_STRING ("yellow" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_YELLOW) ANSI_ESC_END),
173 ENTRY_STRING ("blue" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLUE) ANSI_ESC_END),
174 ENTRY_STRING ("purple" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_PURPLE) ANSI_ESC_END),
175 ENTRY_STRING ("cyan" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_CYAN) ANSI_ESC_END),
176 ENTRY_STRING ("white" , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_WHITE) ANSI_ESC_END),
179 static FormatEntity::Entry::Definition g_ansi_entries[] =
181 ENTRY_CHILDREN ( "fg" , Invalid , None , g_ansi_fg_entries),
182 ENTRY_CHILDREN ( "bg" , Invalid , None , g_ansi_bg_entries),
183 ENTRY_STRING ( "normal" , ANSI_ESC_START _TO_STR(ANSI_CTRL_NORMAL) ANSI_ESC_END),
184 ENTRY_STRING ( "bold" , ANSI_ESC_START _TO_STR(ANSI_CTRL_BOLD) ANSI_ESC_END),
185 ENTRY_STRING ( "faint" , ANSI_ESC_START _TO_STR(ANSI_CTRL_FAINT) ANSI_ESC_END),
186 ENTRY_STRING ( "italic" , ANSI_ESC_START _TO_STR(ANSI_CTRL_ITALIC) ANSI_ESC_END),
187 ENTRY_STRING ( "underline" , ANSI_ESC_START _TO_STR(ANSI_CTRL_UNDERLINE) ANSI_ESC_END),
188 ENTRY_STRING ( "slow-blink" , ANSI_ESC_START _TO_STR(ANSI_CTRL_SLOW_BLINK) ANSI_ESC_END),
189 ENTRY_STRING ( "fast-blink" , ANSI_ESC_START _TO_STR(ANSI_CTRL_FAST_BLINK) ANSI_ESC_END),
190 ENTRY_STRING ( "negative" , ANSI_ESC_START _TO_STR(ANSI_CTRL_IMAGE_NEGATIVE) ANSI_ESC_END),
191 ENTRY_STRING ( "conceal" , ANSI_ESC_START _TO_STR(ANSI_CTRL_CONCEAL) ANSI_ESC_END),
192 ENTRY_STRING ( "crossed-out" , ANSI_ESC_START _TO_STR(ANSI_CTRL_CROSSED_OUT) ANSI_ESC_END),
196 static FormatEntity::Entry::Definition g_script_child_entries[] =
198 ENTRY ( "frame" , ScriptFrame , None),
199 ENTRY ( "process" , ScriptProcess , None),
200 ENTRY ( "target" , ScriptTarget , None),
201 ENTRY ( "thread" , ScriptThread , None),
202 ENTRY ( "var" , ScriptVariable , None),
203 ENTRY ( "svar" , ScriptVariableSynthetic , None),
204 ENTRY ( "thread" , ScriptThread , None),
207 static FormatEntity::Entry::Definition g_top_level_entries[] =
209 ENTRY_CHILDREN ("addr" , AddressLoadOrFile , UInt64 , g_addr_entries),
210 ENTRY ("addr-file-or-load" , AddressLoadOrFile , UInt64 ),
211 ENTRY_CHILDREN ("ansi" , Invalid , None , g_ansi_entries),
212 ENTRY ("current-pc-arrow" , CurrentPCArrow , CString ),
213 ENTRY_CHILDREN ("file" , File , CString , g_file_child_entries),
214 ENTRY ("language" , Lang , CString),
215 ENTRY_CHILDREN ("frame" , Invalid , None , g_frame_child_entries),
216 ENTRY_CHILDREN ("function" , Invalid , None , g_function_child_entries),
217 ENTRY_CHILDREN ("line" , Invalid , None , g_line_child_entries),
218 ENTRY_CHILDREN ("module" , Invalid , None , g_module_child_entries),
219 ENTRY_CHILDREN ("process" , Invalid , None , g_process_child_entries),
220 ENTRY_CHILDREN ("script" , Invalid , None , g_script_child_entries),
221 ENTRY_CHILDREN_KEEP_SEP ("svar" , VariableSynthetic , None , g_svar_child_entries),
222 ENTRY_CHILDREN ("thread" , Invalid , None , g_thread_child_entries),
223 ENTRY_CHILDREN ("target" , Invalid , None , g_target_child_entries),
224 ENTRY_CHILDREN_KEEP_SEP ("var" , Variable , None , g_var_child_entries),
227 static FormatEntity::Entry::Definition g_root = ENTRY_CHILDREN ("<root>", Root, None, g_top_level_entries);
230 FormatEntity::Entry::Entry (llvm::StringRef s) :
231 string (s.data(), s.size()),
236 fmt (lldb::eFormatDefault),
242 FormatEntity::Entry::Entry (char ch) :
248 fmt (lldb::eFormatDefault),
255 FormatEntity::Entry::AppendChar (char ch)
257 if (children.empty() || children.back().type != Entry::Type::String)
258 children.push_back(Entry(ch));
260 children.back().string.append(1, ch);
264 FormatEntity::Entry::AppendText (const llvm::StringRef &s)
266 if (children.empty() || children.back().type != Entry::Type::String)
267 children.push_back(Entry(s));
269 children.back().string.append(s.data(), s.size());
273 FormatEntity::Entry::AppendText (const char *cstr)
275 return AppendText (llvm::StringRef(cstr));
280 FormatEntity::Parse (const llvm::StringRef &format_str, Entry &entry)
283 entry.type = Entry::Type::Root;
284 llvm::StringRef modifiable_format (format_str);
285 return ParseInternal (modifiable_format, entry, 0);
288 #define ENUM_TO_CSTR(eee) case FormatEntity::Entry::Type::eee: return #eee
291 FormatEntity::Entry::TypeToCString (Type t)
295 ENUM_TO_CSTR(Invalid);
296 ENUM_TO_CSTR(ParentNumber);
297 ENUM_TO_CSTR(ParentString);
298 ENUM_TO_CSTR(InsertString);
300 ENUM_TO_CSTR(String);
302 ENUM_TO_CSTR(Variable);
303 ENUM_TO_CSTR(VariableSynthetic);
304 ENUM_TO_CSTR(ScriptVariable);
305 ENUM_TO_CSTR(ScriptVariableSynthetic);
306 ENUM_TO_CSTR(AddressLoad);
307 ENUM_TO_CSTR(AddressFile);
308 ENUM_TO_CSTR(AddressLoadOrFile);
309 ENUM_TO_CSTR(ProcessID);
310 ENUM_TO_CSTR(ProcessFile);
311 ENUM_TO_CSTR(ScriptProcess);
312 ENUM_TO_CSTR(ThreadID);
313 ENUM_TO_CSTR(ThreadProtocolID);
314 ENUM_TO_CSTR(ThreadIndexID);
315 ENUM_TO_CSTR(ThreadName);
316 ENUM_TO_CSTR(ThreadQueue);
317 ENUM_TO_CSTR(ThreadStopReason);
318 ENUM_TO_CSTR(ThreadReturnValue);
319 ENUM_TO_CSTR(ThreadCompletedExpression);
320 ENUM_TO_CSTR(ScriptThread);
321 ENUM_TO_CSTR(ThreadInfo);
322 ENUM_TO_CSTR(TargetArch);
323 ENUM_TO_CSTR(ScriptTarget);
324 ENUM_TO_CSTR(ModuleFile);
327 ENUM_TO_CSTR(FrameIndex);
328 ENUM_TO_CSTR(FrameRegisterPC);
329 ENUM_TO_CSTR(FrameRegisterSP);
330 ENUM_TO_CSTR(FrameRegisterFP);
331 ENUM_TO_CSTR(FrameRegisterFlags);
332 ENUM_TO_CSTR(FrameRegisterByName);
333 ENUM_TO_CSTR(ScriptFrame);
334 ENUM_TO_CSTR(FunctionID);
335 ENUM_TO_CSTR(FunctionDidChange);
336 ENUM_TO_CSTR(FunctionInitialFunction);
337 ENUM_TO_CSTR(FunctionName);
338 ENUM_TO_CSTR(FunctionNameWithArgs);
339 ENUM_TO_CSTR(FunctionNameNoArgs);
340 ENUM_TO_CSTR(FunctionAddrOffset);
341 ENUM_TO_CSTR(FunctionAddrOffsetConcrete);
342 ENUM_TO_CSTR(FunctionLineOffset);
343 ENUM_TO_CSTR(FunctionPCOffset);
344 ENUM_TO_CSTR(FunctionInitial);
345 ENUM_TO_CSTR(FunctionChanged);
346 ENUM_TO_CSTR(LineEntryFile);
347 ENUM_TO_CSTR(LineEntryLineNumber);
348 ENUM_TO_CSTR(LineEntryStartAddress);
349 ENUM_TO_CSTR(LineEntryEndAddress);
350 ENUM_TO_CSTR(CurrentPCArrow);
358 FormatEntity::Entry::Dump (Stream &s, int depth) const
360 s.Printf ("%*.*s%-20s: ", depth * 2, depth * 2, "", TypeToCString(type));
361 if (fmt != eFormatDefault)
362 s.Printf ("lldb-format = %s, ", FormatManager::GetFormatAsCString (fmt));
364 s.Printf ("string = \"%s\"", string.c_str());
365 if (!printf_format.empty())
366 s.Printf ("printf_format = \"%s\"", printf_format.c_str());
368 s.Printf ("number = %" PRIu64 " (0x%" PRIx64 "), ", number, number);
370 s.Printf ("deref = true, ");
372 for (const auto &child : children)
374 child.Dump(s, depth + 1);
379 template <typename T>
380 static bool RunScriptFormatKeyword(Stream &s,
381 const SymbolContext *sc,
382 const ExecutionContext *exe_ctx,
384 const char *script_function_name)
386 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
390 ScriptInterpreter *script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
391 if (script_interpreter)
394 std::string script_output;
396 if (script_interpreter->RunScriptFormatKeyword(script_function_name, t, script_output, error) && error.Success())
398 s.Printf("%s", script_output.c_str());
403 s.Printf("<error: %s>",error.AsCString());
411 DumpAddress (Stream &s,
412 const SymbolContext *sc,
413 const ExecutionContext *exe_ctx,
415 bool print_file_addr_or_load_addr)
417 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
418 addr_t vaddr = LLDB_INVALID_ADDRESS;
419 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
420 vaddr = addr.GetLoadAddress (target);
421 if (vaddr == LLDB_INVALID_ADDRESS)
422 vaddr = addr.GetFileAddress ();
424 if (vaddr != LLDB_INVALID_ADDRESS)
427 if (exe_ctx && target)
429 addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
433 if (print_file_addr_or_load_addr)
435 ExecutionContextScope *exe_scope = NULL;
437 exe_scope = exe_ctx->GetBestExecutionContextScope();
438 addr.Dump (&s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress, 0);
442 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
450 DumpAddressOffsetFromFunction (Stream &s,
451 const SymbolContext *sc,
452 const ExecutionContext *exe_ctx,
453 const Address &format_addr,
456 bool print_zero_offsets)
458 if (format_addr.IsValid())
466 func_addr = sc->function->GetAddressRange().GetBaseAddress();
467 if (sc->block && !concrete_only)
469 // Check to make sure we aren't in an inline
470 // function. If we are, use the inline block
471 // range that contains "format_addr" since
472 // blocks can be discontiguous.
473 Block *inline_block = sc->block->GetContainingInlinedBlock ();
474 AddressRange inline_range;
475 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
476 func_addr = inline_range.GetBaseAddress();
479 else if (sc->symbol && sc->symbol->ValueIsAddress())
480 func_addr = sc->symbol->GetAddressRef();
483 if (func_addr.IsValid())
485 const char *addr_offset_padding = no_padding ? "" : " ";
487 if (func_addr.GetSection() == format_addr.GetSection())
489 addr_t func_file_addr = func_addr.GetFileAddress();
490 addr_t addr_file_addr = format_addr.GetFileAddress();
491 if (addr_file_addr > func_file_addr
492 || (addr_file_addr == func_file_addr && print_zero_offsets))
494 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_file_addr - func_file_addr);
496 else if (addr_file_addr < func_file_addr)
498 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_file_addr - addr_file_addr);
504 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
507 addr_t func_load_addr = func_addr.GetLoadAddress (target);
508 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
509 if (addr_load_addr > func_load_addr
510 || (addr_load_addr == func_load_addr && print_zero_offsets))
512 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_load_addr - func_load_addr);
514 else if (addr_load_addr < func_load_addr)
516 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_load_addr - addr_load_addr);
527 ScanBracketedRange (llvm::StringRef subpath,
528 size_t& close_bracket_index,
529 const char*& var_name_final_if_array_range,
530 int64_t& index_lower,
531 int64_t& index_higher)
533 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
534 close_bracket_index = llvm::StringRef::npos;
535 const size_t open_bracket_index = subpath.find('[');
536 if (open_bracket_index == llvm::StringRef::npos)
539 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
543 close_bracket_index = subpath.find(']', open_bracket_index + 1);
545 if (close_bracket_index == llvm::StringRef::npos)
548 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
553 var_name_final_if_array_range = subpath.data() + open_bracket_index;
555 if (close_bracket_index - open_bracket_index == 1)
558 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
563 const size_t separator_index = subpath.find('-', open_bracket_index + 1);
565 if (separator_index == llvm::StringRef::npos)
567 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
568 index_lower = ::strtoul (index_lower_cstr, NULL, 0);
569 index_higher = index_lower;
571 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", index_lower);
575 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
576 const char *index_higher_cstr = subpath.data() + separator_index + 1;
577 index_lower = ::strtoul (index_lower_cstr, NULL, 0);
578 index_higher = ::strtoul (index_higher_cstr, NULL, 0);
580 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", index_lower, index_higher);
582 if (index_lower > index_higher && index_higher > 0)
585 log->Printf("[ScanBracketedRange] swapping indices");
586 const int64_t temp = index_lower;
587 index_lower = index_higher;
596 DumpFile (Stream &s, const FileSpec &file, FileKind file_kind)
600 case FileKind::FileError:
603 case FileKind::Basename:
604 if (file.GetFilename())
606 s << file.GetFilename();
611 case FileKind::Dirname:
612 if (file.GetDirectory())
614 s << file.GetDirectory();
619 case FileKind::Fullpath:
631 DumpRegister (Stream &s,
633 RegisterKind reg_kind,
640 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
644 const uint32_t lldb_reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
645 if (lldb_reg_num != LLDB_INVALID_REGNUM)
647 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex (lldb_reg_num);
650 RegisterValue reg_value;
651 if (reg_ctx->ReadRegister (reg_info, reg_value))
653 reg_value.Dump(&s, reg_info, false, false, format);
665 ExpandIndexedExpression (ValueObject* valobj,
670 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
671 const char* ptr_deref_format = "[%d]";
672 std::string ptr_deref_buffer(10,0);
673 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
675 log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
676 const char* first_unparsed;
677 ValueObject::GetValueForExpressionPathOptions options;
678 ValueObject::ExpressionPathEndResultType final_value_type;
679 ValueObject::ExpressionPathScanEndReason reason_to_stop;
680 ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
681 ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
690 log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
691 " final_value_type %d",
692 first_unparsed, reason_to_stop, final_value_type);
697 log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
698 " final_value_type %d",
699 first_unparsed, reason_to_stop, final_value_type);
705 ConvertValueObjectStyleToChar(ValueObject::ValueObjectRepresentationStyle style)
709 case ValueObject::eValueObjectRepresentationStyleLanguageSpecific: return '@';
710 case ValueObject::eValueObjectRepresentationStyleValue: return 'V';
711 case ValueObject::eValueObjectRepresentationStyleLocation: return 'L';
712 case ValueObject::eValueObjectRepresentationStyleSummary: return 'S';
713 case ValueObject::eValueObjectRepresentationStyleChildrenCount: return '#';
714 case ValueObject::eValueObjectRepresentationStyleType: return 'T';
715 case ValueObject::eValueObjectRepresentationStyleName: return 'N';
716 case ValueObject::eValueObjectRepresentationStyleExpressionPath: return '>';
722 DumpValue (Stream &s,
723 const SymbolContext *sc,
724 const ExecutionContext *exe_ctx,
725 const FormatEntity::Entry &entry,
731 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
732 Format custom_format = eFormatInvalid;
733 ValueObject::ValueObjectRepresentationStyle val_obj_display = entry.string.empty() ? ValueObject::eValueObjectRepresentationStyleValue : ValueObject::eValueObjectRepresentationStyleSummary;
735 bool do_deref_pointer = entry.deref;
736 bool is_script = false;
739 case FormatEntity::Entry::Type::ScriptVariable:
743 case FormatEntity::Entry::Type::Variable:
744 custom_format = entry.fmt;
745 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
748 case FormatEntity::Entry::Type::ScriptVariableSynthetic:
751 case FormatEntity::Entry::Type::VariableSynthetic:
752 custom_format = entry.fmt;
753 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
754 if (!valobj->IsSynthetic())
756 valobj = valobj->GetSyntheticValue().get();
757 if (valobj == nullptr)
769 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
770 ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
771 ValueObject::GetValueForExpressionPathOptions options;
772 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().SetSyntheticChildrenTraversal(ValueObject::GetValueForExpressionPathOptions::SyntheticChildrenTraversal::Both);
773 ValueObject* target = NULL;
774 const char* var_name_final_if_array_range = NULL;
775 size_t close_bracket_index = llvm::StringRef::npos;
776 int64_t index_lower = -1;
777 int64_t index_higher = -1;
778 bool is_array_range = false;
779 const char* first_unparsed;
780 bool was_plain_var = false;
781 bool was_var_format = false;
782 bool was_var_indexed = false;
783 ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
784 ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
788 return RunScriptFormatKeyword (s, sc, exe_ctx, valobj, entry.string.c_str());
791 llvm::StringRef subpath (entry.string);
792 // simplest case ${var}, just print valobj's value
793 if (entry.string.empty())
795 if (entry.printf_format.empty() && entry.fmt == eFormatDefault && entry.number == ValueObject::eValueObjectRepresentationStyleValue)
796 was_plain_var = true;
798 was_var_format = true;
801 else // this is ${var.something} or multiple .something nested
803 if (entry.string[0] == '[')
804 was_var_indexed = true;
805 ScanBracketedRange (subpath,
807 var_name_final_if_array_range,
813 const std::string &expr_path = entry.string;
816 log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
818 target = valobj->GetValueForExpressionPath(expr_path.c_str(),
828 log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
829 " final_value_type %d",
830 first_unparsed, reason_to_stop, final_value_type);
836 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
837 " final_value_type %d",
838 first_unparsed, reason_to_stop, final_value_type);
839 target = target->GetQualifiedRepresentationIfAvailable(target->GetDynamicValueType(), true).get();
844 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
845 final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
847 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
849 if (do_deref_pointer && !is_array_range)
851 // I have not deref-ed yet, let's do it
852 // this happens when we are not going through GetValueForVariableExpressionPath
853 // to get to the target ValueObject
855 target = target->Dereference(error).get();
859 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
862 do_deref_pointer = false;
868 log->Printf("[Debugger::FormatPrompt] could not calculate target for prompt expression");
872 // we do not want to use the summary for a bitfield of type T:n
873 // if we were originally dealing with just a T - that would get
874 // us into an endless recursion
875 if (target->IsBitfield() && was_var_indexed)
877 // TODO: check for a (T:n)-specific summary - we should still obey that
878 StreamString bitfield_name;
879 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
880 lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
881 if (val_obj_display == ValueObject::eValueObjectRepresentationStyleSummary && !DataVisualization::GetSummaryForType(type_sp))
882 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
885 // TODO use flags for these
886 const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
887 bool is_array = (type_info_flags & eTypeIsArray) != 0;
888 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
889 bool is_aggregate = target->GetClangType().IsAggregateType();
891 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
893 StreamString str_temp;
895 log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
897 if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
899 // try to use the special cases
900 bool success = target->DumpPrintableRepresentation(str_temp,
904 log->Printf("[Debugger::FormatPrompt] special cases did%s match", success ? "" : "n't");
908 s << str_temp.GetData();
913 if (was_plain_var) // if ${var}
915 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
917 else if (is_pointer) // if pointer, value is the address stored
919 target->DumpPrintableRepresentation (s,
922 ValueObject::ePrintableRepresentationSpecialCasesDisable);
928 // if directly trying to print ${var}, and this is an aggregate, display a nice
929 // type @ location message
930 if (is_aggregate && was_plain_var)
932 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
936 // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
937 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
939 s << "<invalid use of aggregate type>";
946 log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
947 return target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
952 log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
953 if (!is_array && !is_pointer)
956 log->Printf("[Debugger::FormatPrompt] handle as array");
957 StreamString special_directions_stream;
958 llvm::StringRef special_directions;
959 if (close_bracket_index != llvm::StringRef::npos && subpath.size() > close_bracket_index)
961 ConstString additional_data (subpath.drop_front(close_bracket_index+1));
962 special_directions_stream.Printf("${%svar%s",
963 do_deref_pointer ? "*" : "",
964 additional_data.GetCString());
966 if (entry.fmt != eFormatDefault)
968 const char format_char = FormatManager::GetFormatAsFormatChar(entry.fmt);
969 if (format_char != '\0')
970 special_directions_stream.Printf("%%%c", format_char);
973 const char *format_cstr = FormatManager::GetFormatAsCString(entry.fmt);
974 special_directions_stream.Printf("%%%s", format_cstr);
977 else if (entry.number != 0)
979 const char style_char = ConvertValueObjectStyleToChar ((ValueObject::ValueObjectRepresentationStyle)entry.number);
981 special_directions_stream.Printf("%%%c", style_char);
983 special_directions_stream.PutChar('}');
984 special_directions = llvm::StringRef(special_directions_stream.GetString());
987 // let us display items index_lower thru index_higher of this array
990 if (index_higher < 0)
991 index_higher = valobj->GetNumChildren() - 1;
993 uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
996 for (int64_t index = index_lower;index<=index_higher; ++index)
998 ValueObject* item = ExpandIndexedExpression (target,
1000 exe_ctx->GetFramePtr(),
1006 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index);
1011 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions.data() ? special_directions.data() : "");
1014 if (special_directions.empty())
1016 success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1020 success &= FormatEntity::FormatStringRef(special_directions, s, sc, exe_ctx, NULL, item, false, false);
1023 if (--max_num_children == 0)
1025 s.PutCString(", ...");
1029 if (index < index_higher)
1039 DumpRegister (Stream &s,
1041 const char *reg_name,
1047 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
1051 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
1054 RegisterValue reg_value;
1055 if (reg_ctx->ReadRegister (reg_info, reg_value))
1057 reg_value.Dump(&s, reg_info, false, false, format);
1067 FormatThreadExtendedInfoRecurse(const FormatEntity::Entry &entry,
1068 const StructuredData::ObjectSP &thread_info_dictionary,
1069 const SymbolContext *sc,
1070 const ExecutionContext *exe_ctx,
1073 llvm::StringRef path(entry.string);
1075 StructuredData::ObjectSP value = thread_info_dictionary->GetObjectForDotSeparatedPath (path);
1079 if (value->GetType() == StructuredData::Type::eTypeInteger)
1081 const char *token_format = "0x%4.4" PRIx64;
1082 if (!entry.printf_format.empty())
1083 token_format = entry.printf_format.c_str();
1084 s.Printf(token_format, value->GetAsInteger()->GetValue());
1087 else if (value->GetType() == StructuredData::Type::eTypeFloat)
1089 s.Printf ("%f", value->GetAsFloat()->GetValue());
1092 else if (value->GetType() == StructuredData::Type::eTypeString)
1094 s.Printf("%s", value->GetAsString()->GetValue().c_str());
1097 else if (value->GetType() == StructuredData::Type::eTypeArray)
1099 if (value->GetAsArray()->GetSize() > 0)
1101 s.Printf ("%zu", value->GetAsArray()->GetSize());
1105 else if (value->GetType() == StructuredData::Type::eTypeDictionary)
1107 s.Printf ("%zu", value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1117 IsToken(const char *var_name_begin, const char *var)
1119 return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1123 FormatEntity::FormatStringRef (const llvm::StringRef &format_str,
1125 const SymbolContext *sc,
1126 const ExecutionContext *exe_ctx,
1127 const Address *addr,
1128 ValueObject* valobj,
1129 bool function_changed,
1130 bool initial_function)
1132 if (!format_str.empty())
1134 FormatEntity::Entry root;
1135 Error error = FormatEntity::Parse(format_str, root);
1136 if (error.Success())
1138 return FormatEntity::Format (root,
1152 FormatEntity::FormatCString (const char *format,
1154 const SymbolContext *sc,
1155 const ExecutionContext *exe_ctx,
1156 const Address *addr,
1157 ValueObject* valobj,
1158 bool function_changed,
1159 bool initial_function)
1161 if (format && format[0])
1163 FormatEntity::Entry root;
1164 llvm::StringRef format_str(format);
1165 Error error = FormatEntity::Parse(format_str, root);
1166 if (error.Success())
1168 return FormatEntity::Format (root,
1182 FormatEntity::Format (const Entry &entry,
1184 const SymbolContext *sc,
1185 const ExecutionContext *exe_ctx,
1186 const Address *addr,
1187 ValueObject* valobj,
1188 bool function_changed,
1189 bool initial_function)
1193 case Entry::Type::Invalid:
1194 case Entry::Type::ParentNumber: // Only used for FormatEntity::Entry::Definition encoding
1195 case Entry::Type::ParentString: // Only used for FormatEntity::Entry::Definition encoding
1196 case Entry::Type::InsertString: // Only used for FormatEntity::Entry::Definition encoding
1199 case Entry::Type::Root:
1200 for (const auto &child : entry.children)
1209 initial_function) == false)
1211 return false; // If any item of root fails, then the formatting fails
1214 return true; // Only return true if all items succeeded
1216 case Entry::Type::String:
1217 s.PutCString(entry.string.c_str());
1220 case Entry::Type::Scope:
1222 StreamString scope_stream;
1223 bool success = false;
1224 for (const auto &child : entry.children)
1226 success = Format (child, scope_stream, sc, exe_ctx, addr, valobj, function_changed, initial_function);
1230 // Only if all items in a scope succeed, then do we
1231 // print the output into the main stream
1233 s.Write(scope_stream.GetString().data(), scope_stream.GetString().size());
1235 return true; // Scopes always successfully print themselves
1237 case Entry::Type::Variable:
1238 case Entry::Type::VariableSynthetic:
1239 case Entry::Type::ScriptVariable:
1240 case Entry::Type::ScriptVariableSynthetic:
1241 if (DumpValue(s, sc, exe_ctx, entry, valobj))
1245 case Entry::Type::AddressFile:
1246 case Entry::Type::AddressLoad:
1247 case Entry::Type::AddressLoadOrFile:
1248 if (addr && addr->IsValid() && DumpAddress(s, sc, exe_ctx, *addr, entry.type == Entry::Type::AddressLoadOrFile))
1252 case Entry::Type::ProcessID:
1255 Process *process = exe_ctx->GetProcessPtr();
1258 const char *format = "%" PRIu64;
1259 if (!entry.printf_format.empty())
1260 format = entry.printf_format.c_str();
1261 s.Printf(format, process->GetID());
1267 case Entry::Type::ProcessFile:
1270 Process *process = exe_ctx->GetProcessPtr();
1273 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1276 if (DumpFile(s, exe_module->GetFileSpec(), (FileKind)entry.number))
1283 case Entry::Type::ScriptProcess:
1286 Process *process = exe_ctx->GetProcessPtr();
1288 return RunScriptFormatKeyword (s, sc, exe_ctx, process, entry.string.c_str());
1293 case Entry::Type::ThreadID:
1296 Thread *thread = exe_ctx->GetThreadPtr();
1299 const char *format = "0x%4.4" PRIx64;
1300 if (!entry.printf_format.empty())
1302 // Watch for the special "tid" format...
1303 if (entry.printf_format == "tid")
1305 Target &target = thread->GetProcess()->GetTarget();
1306 ArchSpec arch (target.GetArchitecture ());
1307 llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1308 if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1310 format = "%" PRIu64;
1315 format = entry.printf_format.c_str();
1318 s.Printf(format, thread->GetID());
1324 case Entry::Type::ThreadProtocolID:
1327 Thread *thread = exe_ctx->GetThreadPtr();
1330 const char *format = "0x%4.4" PRIx64;
1331 if (!entry.printf_format.empty())
1332 format = entry.printf_format.c_str();
1333 s.Printf(format, thread->GetProtocolID());
1339 case Entry::Type::ThreadIndexID:
1342 Thread *thread = exe_ctx->GetThreadPtr();
1345 const char *format = "%" PRIu32;
1346 if (!entry.printf_format.empty())
1347 format = entry.printf_format.c_str();
1348 s.Printf(format, thread->GetIndexID());
1354 case Entry::Type::ThreadName:
1357 Thread *thread = exe_ctx->GetThreadPtr();
1360 const char *cstr = thread->GetName();
1361 if (cstr && cstr[0])
1370 case Entry::Type::ThreadQueue:
1373 Thread *thread = exe_ctx->GetThreadPtr();
1376 const char *cstr = thread->GetQueueName();
1377 if (cstr && cstr[0])
1386 case Entry::Type::ThreadStopReason:
1389 Thread *thread = exe_ctx->GetThreadPtr();
1392 StopInfoSP stop_info_sp = thread->GetStopInfo ();
1393 if (stop_info_sp && stop_info_sp->IsValid())
1395 const char *cstr = stop_info_sp->GetDescription();
1396 if (cstr && cstr[0])
1406 case Entry::Type::ThreadReturnValue:
1409 Thread *thread = exe_ctx->GetThreadPtr();
1412 StopInfoSP stop_info_sp = thread->GetStopInfo ();
1413 if (stop_info_sp && stop_info_sp->IsValid())
1415 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
1416 if (return_valobj_sp)
1418 return_valobj_sp->Dump(s);
1426 case Entry::Type::ThreadCompletedExpression:
1429 Thread *thread = exe_ctx->GetThreadPtr();
1432 StopInfoSP stop_info_sp = thread->GetStopInfo ();
1433 if (stop_info_sp && stop_info_sp->IsValid())
1435 ClangExpressionVariableSP expression_var_sp = StopInfo::GetExpressionVariable (stop_info_sp);
1436 if (expression_var_sp && expression_var_sp->GetValueObject())
1438 expression_var_sp->GetValueObject()->Dump(s);
1446 case Entry::Type::ScriptThread:
1449 Thread *thread = exe_ctx->GetThreadPtr();
1451 return RunScriptFormatKeyword (s, sc, exe_ctx, thread, entry.string.c_str());
1455 case Entry::Type::ThreadInfo:
1458 Thread *thread = exe_ctx->GetThreadPtr();
1461 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
1462 if (object_sp && object_sp->GetType() == StructuredData::Type::eTypeDictionary)
1464 if (FormatThreadExtendedInfoRecurse (entry, object_sp, sc, exe_ctx, s))
1471 case Entry::Type::TargetArch:
1474 Target *target = exe_ctx->GetTargetPtr();
1477 const ArchSpec &arch = target->GetArchitecture ();
1480 s.PutCString (arch.GetArchitectureName());
1487 case Entry::Type::ScriptTarget:
1490 Target *target = exe_ctx->GetTargetPtr();
1492 return RunScriptFormatKeyword (s, sc, exe_ctx, target, entry.string.c_str());
1496 case Entry::Type::ModuleFile:
1499 Module *module = sc->module_sp.get();
1502 if (DumpFile(s, module->GetFileSpec(), (FileKind)entry.number))
1508 case Entry::Type::File:
1511 CompileUnit *cu = sc->comp_unit;
1514 // CompileUnit is a FileSpec
1515 if (DumpFile(s, *cu, (FileKind)entry.number))
1521 case Entry::Type::Lang:
1524 CompileUnit *cu = sc->comp_unit;
1527 Language lang(cu->GetLanguage());
1528 const char *lang_name = lang.AsCString();
1531 s.PutCString(lang_name);
1538 case Entry::Type::FrameIndex:
1541 StackFrame *frame = exe_ctx->GetFramePtr();
1544 const char *format = "%" PRIu32;
1545 if (!entry.printf_format.empty())
1546 format = entry.printf_format.c_str();
1547 s.Printf(format, frame->GetFrameIndex());
1553 case Entry::Type::FrameRegisterPC:
1556 StackFrame *frame = exe_ctx->GetFramePtr();
1559 const Address &pc_addr = frame->GetFrameCodeAddress();
1560 if (pc_addr.IsValid())
1562 if (DumpAddress(s, sc, exe_ctx, pc_addr, false))
1569 case Entry::Type::FrameRegisterSP:
1572 StackFrame *frame = exe_ctx->GetFramePtr();
1575 if (DumpRegister (s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, (lldb::Format)entry.number))
1581 case Entry::Type::FrameRegisterFP:
1584 StackFrame *frame = exe_ctx->GetFramePtr();
1587 if (DumpRegister (s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, (lldb::Format)entry.number))
1593 case Entry::Type::FrameRegisterFlags:
1596 StackFrame *frame = exe_ctx->GetFramePtr();
1599 if (DumpRegister (s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS, (lldb::Format)entry.number))
1606 case Entry::Type::FrameRegisterByName:
1609 StackFrame *frame = exe_ctx->GetFramePtr();
1612 if (DumpRegister (s, frame, entry.string.c_str(), (lldb::Format)entry.number))
1618 case Entry::Type::ScriptFrame:
1621 StackFrame *frame = exe_ctx->GetFramePtr();
1623 return RunScriptFormatKeyword (s, sc, exe_ctx, frame, entry.string.c_str());
1627 case Entry::Type::FunctionID:
1632 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
1635 else if (sc->symbol)
1637 s.Printf("symbol[%u]", sc->symbol->GetID());
1643 case Entry::Type::FunctionDidChange:
1644 return function_changed;
1646 case Entry::Type::FunctionInitialFunction:
1647 return initial_function;
1649 case Entry::Type::FunctionName:
1651 const char *name = NULL;
1653 name = sc->function->GetName().AsCString (NULL);
1654 else if (sc->symbol)
1655 name = sc->symbol->GetName().AsCString (NULL);
1662 Block *inline_block = sc->block->GetContainingInlinedBlock ();
1665 const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
1668 s.PutCString(" [inlined] ");
1669 inline_info->GetName(sc->function->GetLanguage()).Dump(&s);
1678 case Entry::Type::FunctionNameNoArgs:
1682 name = sc->function->GetNameNoArguments();
1683 else if (sc->symbol)
1684 name = sc->symbol->GetNameNoArguments();
1687 s.PutCString(name.GetCString());
1693 case Entry::Type::FunctionNameWithArgs:
1695 // Print the function name with arguments in it
1698 ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
1699 const char *cstr = sc->function->GetName().AsCString (NULL);
1702 const InlineFunctionInfo *inline_info = NULL;
1703 VariableListSP variable_list_sp;
1704 bool get_function_vars = true;
1707 Block *inline_block = sc->block->GetContainingInlinedBlock ();
1711 get_function_vars = false;
1712 inline_info = sc->block->GetInlinedFunctionInfo();
1714 variable_list_sp = inline_block->GetBlockVariableList (true);
1718 if (get_function_vars)
1720 variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
1725 s.PutCString (cstr);
1726 s.PutCString (" [inlined] ");
1727 cstr = inline_info->GetName(sc->function->GetLanguage()).GetCString();
1731 if (variable_list_sp)
1732 variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
1733 if (args.GetSize() > 0)
1735 const char *open_paren = strchr (cstr, '(');
1736 const char *close_paren = nullptr;
1737 const char *generic = strchr(cstr, '<');
1738 // if before the arguments list begins there is a template sign
1739 // then scan to the end of the generic args before you try to find
1740 // the arguments list
1741 if (generic && open_paren && generic < open_paren)
1743 int generic_depth = 1;
1746 *generic && generic_depth > 0;
1749 if (*generic == '<')
1751 if (*generic == '>')
1755 open_paren = strchr(generic, '(');
1757 open_paren = nullptr;
1761 if (IsToken (open_paren, "(anonymous namespace)"))
1763 open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
1765 close_paren = strchr (open_paren, ')');
1768 close_paren = strchr (open_paren, ')');
1772 s.Write(cstr, open_paren - cstr + 1);
1775 s.PutCString (cstr);
1778 const size_t num_args = args.GetSize();
1779 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
1783 VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
1784 ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
1785 const char *var_representation = nullptr;
1786 const char *var_name = var_value_sp->GetName().GetCString();
1787 if (var_value_sp->GetClangType().IsAggregateType() &&
1788 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp.get()))
1790 static StringSummaryFormat format(TypeSummaryImpl::Flags()
1791 .SetHideItemNames(false)
1792 .SetShowMembersOneLiner(true),
1794 format.FormatObject(var_value_sp.get(), buffer, TypeSummaryOptions());
1795 var_representation = buffer.c_str();
1798 var_representation = var_value_sp->GetValueAsCString();
1800 s.PutCString (", ");
1801 if (var_value_sp->GetError().Success())
1803 if (var_representation)
1804 s.Printf ("%s=%s", var_name, var_representation);
1806 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
1809 s.Printf ("%s=<unavailable>", var_name);
1813 s.PutCString (close_paren);
1825 else if (sc->symbol)
1827 const char *cstr = sc->symbol->GetName().AsCString (NULL);
1837 case Entry::Type::FunctionAddrOffset:
1840 if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, *addr, false, false, false))
1845 case Entry::Type::FunctionAddrOffsetConcrete:
1848 if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, *addr, true, true, true))
1853 case Entry::Type::FunctionLineOffset:
1854 if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, sc->line_entry.range.GetBaseAddress(), false, false, false))
1858 case Entry::Type::FunctionPCOffset:
1861 StackFrame *frame = exe_ctx->GetFramePtr();
1864 if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, frame->GetFrameCodeAddress(), false, false, false))
1870 case Entry::Type::FunctionChanged:
1871 return function_changed == true;
1873 case Entry::Type::FunctionInitial:
1874 return initial_function == true;
1876 case Entry::Type::LineEntryFile:
1877 if (sc && sc->line_entry.IsValid())
1879 Module *module = sc->module_sp.get();
1882 if (DumpFile(s, sc->line_entry.file, (FileKind)entry.number))
1888 case Entry::Type::LineEntryLineNumber:
1889 if (sc && sc->line_entry.IsValid())
1891 const char *format = "%" PRIu32;
1892 if (!entry.printf_format.empty())
1893 format = entry.printf_format.c_str();
1894 s.Printf(format, sc->line_entry.line);
1899 case Entry::Type::LineEntryStartAddress:
1900 case Entry::Type::LineEntryEndAddress:
1901 if (sc && sc->line_entry.range.GetBaseAddress().IsValid())
1903 Address addr = sc->line_entry.range.GetBaseAddress();
1905 if (entry.type == Entry::Type::LineEntryEndAddress)
1906 addr.Slide(sc->line_entry.range.GetByteSize());
1907 if (DumpAddress(s, sc, exe_ctx, addr, false))
1912 case Entry::Type::CurrentPCArrow:
1913 if (addr && exe_ctx && exe_ctx->GetFramePtr())
1915 RegisterContextSP reg_ctx = exe_ctx->GetFramePtr()->GetRegisterContextSP();
1918 addr_t pc_loadaddr = reg_ctx->GetPC();
1919 if (pc_loadaddr != LLDB_INVALID_ADDRESS)
1922 pc.SetLoadAddress (pc_loadaddr, exe_ctx->GetTargetPtr());
1939 DumpCommaSeparatedChildEntryNames (Stream &s, const FormatEntity::Entry::Definition *parent)
1941 if (parent->children)
1943 const size_t n = parent->num_children;
1944 for (size_t i=0; i<n; ++i)
1948 s.Printf ("\"%s\"", parent->children[i].name);
1957 ParseEntry (const llvm::StringRef &format_str,
1958 const FormatEntity::Entry::Definition *parent,
1959 FormatEntity::Entry &entry)
1963 const size_t sep_pos = format_str.find_first_of(".[:");
1964 const char sep_char = (sep_pos == llvm::StringRef::npos) ? '\0' : format_str[sep_pos];
1965 llvm::StringRef key = format_str.substr(0, sep_pos);
1967 const size_t n = parent->num_children;
1968 for (size_t i=0; i<n; ++i)
1970 const FormatEntity::Entry::Definition *entry_def = parent->children + i;
1971 if (key.equals(entry_def->name) || entry_def->name[0] == '*')
1973 llvm::StringRef value;
1975 value = format_str.substr(sep_pos + (entry_def->keep_separator ? 0 : 1));
1976 switch (entry_def->type)
1978 case FormatEntity::Entry::Type::ParentString:
1979 entry.string = std::move(format_str.str());
1980 return error; // Success
1982 case FormatEntity::Entry::Type::ParentNumber:
1983 entry.number = entry_def->data;
1984 return error; // Success
1986 case FormatEntity::Entry::Type::InsertString:
1987 entry.type = entry_def->type;
1988 entry.string = entry_def->string;
1989 return error; // Success
1992 entry.type = entry_def->type;
1998 if (entry_def->type == FormatEntity::Entry::Type::Invalid)
2000 if (entry_def->children)
2002 StreamString error_strm;
2003 error_strm.Printf("'%s' can't be specified on its own, you must access one of its children: ", entry_def->name);
2004 DumpCommaSeparatedChildEntryNames (error_strm, entry_def);
2005 error.SetErrorStringWithFormat("%s", error_strm.GetString().c_str());
2007 else if (sep_char == ':')
2009 // Any value whose separator is a with a ':' means this value has a string argument
2010 // that needs to be stored in the entry (like "${script.var:}").
2011 // In this case the string value is the empty string which is ok.
2015 error.SetErrorStringWithFormat("%s", "invalid entry definitions");
2021 if (entry_def->children)
2023 error = ParseEntry (value, entry_def, entry);
2025 else if (sep_char == ':')
2027 // Any value whose separator is a with a ':' means this value has a string argument
2028 // that needs to be stored in the entry (like "${script.var:modulename.function}")
2029 entry.string = std::move(value.str());
2033 error.SetErrorStringWithFormat("'%s' followed by '%s' but it has no children",
2035 value.str().c_str());
2041 StreamString error_strm;
2042 if (parent->type == FormatEntity::Entry::Type::Root)
2043 error_strm.Printf("invalid top level item '%s'. Valid top level items are: ", key.str().c_str());
2045 error_strm.Printf("invalid member '%s' in '%s'. Valid members are: ", key.str().c_str(), parent->name);
2046 DumpCommaSeparatedChildEntryNames (error_strm, parent);
2047 error.SetErrorStringWithFormat("%s", error_strm.GetString().c_str());
2052 static const FormatEntity::Entry::Definition *
2053 FindEntry (const llvm::StringRef &format_str, const FormatEntity::Entry::Definition *parent, llvm::StringRef &remainder)
2057 std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.');
2058 const size_t n = parent->num_children;
2059 for (size_t i=0; i<n; ++i)
2061 const FormatEntity::Entry::Definition *entry_def = parent->children + i;
2062 if (p.first.equals(entry_def->name) || entry_def->name[0] == '*')
2064 if (p.second.empty())
2066 if (format_str.back() == '.')
2067 remainder = format_str.drop_front(format_str.size() - 1);
2069 remainder = llvm::StringRef(); // Exact match
2074 if (entry_def->children)
2076 return FindEntry (p.second, entry_def, remainder);
2080 remainder = p.second;
2086 remainder = format_str;
2091 FormatEntity::ParseInternal (llvm::StringRef &format, Entry &parent_entry, uint32_t depth)
2094 while (!format.empty() && error.Success())
2096 const size_t non_special_chars = format.find_first_of("${}\\");
2098 if (non_special_chars == llvm::StringRef::npos)
2100 // No special characters, just string bytes so add them and we are done
2101 parent_entry.AppendText(format);
2105 if (non_special_chars > 0)
2107 // We have a special character, so add all characters before these as a plain string
2108 parent_entry.AppendText(format.substr(0,non_special_chars));
2109 format = format.drop_front(non_special_chars);
2119 format = format.drop_front(); // Skip the '{'
2120 Entry scope_entry(Entry::Type::Scope);
2121 error = FormatEntity::ParseInternal (format, scope_entry, depth+1);
2124 parent_entry.AppendEntry(std::move(scope_entry));
2130 error.SetErrorString("unmatched '}' character");
2132 format = format.drop_front(); // Skip the '}' as we are at the end of the scope
2137 format = format.drop_front(); // Skip the '\' character
2140 error.SetErrorString("'\\' character was not followed by another character");
2144 const char desens_char = format[0];
2145 format = format.drop_front(); // Skip the desensitized char character
2146 switch (desens_char)
2148 case 'a': parent_entry.AppendChar('\a'); break;
2149 case 'b': parent_entry.AppendChar('\b'); break;
2150 case 'f': parent_entry.AppendChar('\f'); break;
2151 case 'n': parent_entry.AppendChar('\n'); break;
2152 case 'r': parent_entry.AppendChar('\r'); break;
2153 case 't': parent_entry.AppendChar('\t'); break;
2154 case 'v': parent_entry.AppendChar('\v'); break;
2155 case '\'': parent_entry.AppendChar('\''); break;
2156 case '\\': parent_entry.AppendChar('\\'); break;
2158 // 1 to 3 octal chars
2160 // Make a string that can hold onto the initial zero char,
2161 // up to 3 octal digits, and a terminating NULL.
2162 char oct_str[5] = { 0, 0, 0, 0, 0 };
2165 for (i=0; (format[i] >= '0' && format[i] <= '7') && i<4; ++i)
2166 oct_str[i] = format[i];
2168 // We don't want to consume the last octal character since
2169 // the main for loop will do this for us, so we advance p by
2170 // one less than i (even if i is zero)
2171 format = format.drop_front(i);
2172 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2173 if (octal_value <= UINT8_MAX)
2175 parent_entry.AppendChar((char)octal_value);
2179 error.SetErrorString("octal number is larger than a single byte");
2186 // hex number in the format
2187 if (isxdigit(format[0]))
2189 // Make a string that can hold onto two hex chars plus a
2191 char hex_str[3] = { 0,0,0 };
2192 hex_str[0] = format[0];
2194 format = format.drop_front();
2196 if (isxdigit(format[0]))
2198 hex_str[1] = format[0];
2199 format = format.drop_front();
2202 unsigned long hex_value = strtoul (hex_str, NULL, 16);
2203 if (hex_value <= UINT8_MAX)
2205 parent_entry.AppendChar((char)hex_value);
2209 error.SetErrorString("hex number is larger than a single byte");
2215 parent_entry.AppendChar(desens_char);
2220 // Just desensitize any other character by just printing what
2221 // came after the '\'
2222 parent_entry.AppendChar(desens_char);
2229 if (format.size() == 1)
2231 // '$' at the end of a format string, just print the '$'
2232 parent_entry.AppendText("$");
2236 format = format.drop_front(); // Skip the '$'
2238 if (format[0] == '{')
2240 format = format.drop_front(); // Skip the '{'
2242 llvm::StringRef variable, variable_format;
2243 error = FormatEntity::ExtractVariableInfo (format, variable, variable_format);
2246 bool verify_is_thread_id = false;
2248 if (!variable_format.empty())
2250 entry.printf_format = std::move(variable_format.str());
2252 // If the format contains a '%' we are going to assume this is
2253 // a printf style format. So if you want to format your thread ID
2254 // using "0x%llx" you can use:
2255 // ${thread.id%0x%llx}
2257 // If there is no '%' in the format, then it is assumed to be a
2258 // LLDB format name, or one of the extended formats specified in
2259 // the switch statement below.
2261 if (entry.printf_format.find('%') == std::string::npos)
2263 bool clear_printf = false;
2265 if (FormatManager::GetFormatFromCString(entry.printf_format.c_str(),
2269 // We have an LLDB format, so clear the printf format
2270 clear_printf = true;
2272 else if (entry.printf_format.size() == 1)
2274 switch (entry.printf_format[0])
2276 case '@': // if this is an @ sign, print ObjC description
2277 entry.number = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
2278 clear_printf = true;
2280 case 'V': // if this is a V, print the value using the default format
2281 entry.number = ValueObject::eValueObjectRepresentationStyleValue;
2282 clear_printf = true;
2284 case 'L': // if this is an L, print the location of the value
2285 entry.number = ValueObject::eValueObjectRepresentationStyleLocation;
2286 clear_printf = true;
2288 case 'S': // if this is an S, print the summary after all
2289 entry.number = ValueObject::eValueObjectRepresentationStyleSummary;
2290 clear_printf = true;
2292 case '#': // if this is a '#', print the number of children
2293 entry.number = ValueObject::eValueObjectRepresentationStyleChildrenCount;
2294 clear_printf = true;
2296 case 'T': // if this is a 'T', print the type
2297 entry.number = ValueObject::eValueObjectRepresentationStyleType;
2298 clear_printf = true;
2300 case 'N': // if this is a 'N', print the name
2301 entry.number = ValueObject::eValueObjectRepresentationStyleName;
2302 clear_printf = true;
2304 case '>': // if this is a '>', print the expression path
2305 entry.number = ValueObject::eValueObjectRepresentationStyleExpressionPath;
2306 clear_printf = true;
2309 error.SetErrorStringWithFormat("invalid format: '%s'", entry.printf_format.c_str());
2313 else if (FormatManager::GetFormatFromCString(entry.printf_format.c_str(),
2317 clear_printf = true;
2319 else if (entry.printf_format == "tid")
2321 verify_is_thread_id = true;
2325 error.SetErrorStringWithFormat("invalid format: '%s'", entry.printf_format.c_str());
2329 // Our format string turned out to not be a printf style format
2330 // so lets clear the string
2332 entry.printf_format.clear();
2336 // Check for dereferences
2337 if (variable[0] == '*')
2340 variable = variable.drop_front();
2343 error = ParseEntry (variable, &g_root, entry);
2347 if (verify_is_thread_id)
2349 if (entry.type != Entry::Type::ThreadID &&
2350 entry.type != Entry::Type::ThreadProtocolID)
2352 error.SetErrorString("the 'tid' format can only be used on ${thread.id} and ${thread.protocol_id}");
2358 case Entry::Type::Variable:
2359 case Entry::Type::VariableSynthetic:
2360 if (entry.number == 0)
2362 if (entry.string.empty())
2363 entry.number = ValueObject::eValueObjectRepresentationStyleValue;
2365 entry.number = ValueObject::eValueObjectRepresentationStyleSummary;
2369 // Make sure someone didn't try to dereference anything but ${var} or ${svar}
2372 error.SetErrorStringWithFormat("${%s} can't be dereferenced, only ${var} and ${svar} can.", variable.str().c_str());
2376 // Check if this entry just wants to insert a constant string
2377 // value into the parent_entry, if so, insert the string with
2378 // AppendText, else append the entry to the parent_entry.
2379 if (entry.type == Entry::Type::InsertString)
2380 parent_entry.AppendText(entry.string.c_str());
2382 parent_entry.AppendEntry(std::move(entry));
2393 FormatEntity::ExtractVariableInfo (llvm::StringRef &format_str, llvm::StringRef &variable_name, llvm::StringRef &variable_format)
2396 variable_name = llvm::StringRef();
2397 variable_format = llvm::StringRef();
2399 const size_t paren_pos = format_str.find_first_of('}');
2400 if (paren_pos != llvm::StringRef::npos)
2402 const size_t percent_pos = format_str.find_first_of('%');
2403 if (percent_pos < paren_pos)
2405 if (percent_pos > 0)
2407 if (percent_pos > 1)
2408 variable_name = format_str.substr(0, percent_pos);
2409 variable_format = format_str.substr(percent_pos + 1, paren_pos - (percent_pos + 1));
2414 variable_name = format_str.substr(0, paren_pos);
2416 // Strip off elements and the formatting and the trailing '}'
2417 format_str = format_str.substr(paren_pos + 1);
2421 error.SetErrorStringWithFormat("missing terminating '}' character for '${%s'", format_str.str().c_str());
2427 FormatEntity::FormatFileSpec (const FileSpec &file_spec, Stream &s, llvm::StringRef variable_name, llvm::StringRef variable_format)
2429 if (variable_name.empty() || variable_name.equals(".fullpath"))
2434 else if (variable_name.equals(".basename"))
2436 s.PutCString(file_spec.GetFilename().AsCString(""));
2439 else if (variable_name.equals(".dirname"))
2441 s.PutCString(file_spec.GetFilename().AsCString(""));
2448 MakeMatch (const llvm::StringRef &prefix, const char *suffix)
2450 std::string match(prefix.str());
2451 match.append(suffix);
2452 return std::move(match);
2456 AddMatches (const FormatEntity::Entry::Definition *def,
2457 const llvm::StringRef &prefix,
2458 const llvm::StringRef &match_prefix,
2459 StringList &matches)
2461 const size_t n = def->num_children;
2464 for (size_t i=0; i<n; ++i)
2466 std::string match = std::move(prefix.str());
2467 if (match_prefix.empty())
2468 matches.AppendString(MakeMatch (prefix, def->children[i].name));
2469 else if (strncmp(def->children[i].name, match_prefix.data(), match_prefix.size()) == 0)
2470 matches.AppendString(MakeMatch (prefix, def->children[i].name + match_prefix.size()));
2475 FormatEntity::AutoComplete (const char *s,
2476 int match_start_point,
2477 int max_return_elements,
2478 bool &word_complete,
2479 StringList &matches)
2481 word_complete = false;
2482 llvm::StringRef str(s + match_start_point);
2485 const size_t dollar_pos = str.rfind('$');
2486 if (dollar_pos != llvm::StringRef::npos)
2488 // Hitting TAB after $ at the end of the string add a "{"
2489 if (dollar_pos == str.size() - 1)
2491 std::string match = std::move(str.str());
2493 matches.AppendString(std::move(match));
2495 else if (str[dollar_pos + 1] == '{')
2497 const size_t close_pos = str.find('}', dollar_pos + 2);
2498 if (close_pos == llvm::StringRef::npos)
2500 const size_t format_pos = str.find('%', dollar_pos + 2);
2501 if (format_pos == llvm::StringRef::npos)
2503 llvm::StringRef partial_variable (str.substr(dollar_pos + 2));
2504 if (partial_variable.empty())
2506 // Suggest all top level entites as we are just past "${"
2507 AddMatches(&g_root, str, llvm::StringRef(), matches);
2511 // We have a partially specified variable, find it
2512 llvm::StringRef remainder;
2513 const FormatEntity::Entry::Definition* entry_def = FindEntry (partial_variable, &g_root, remainder);
2516 const size_t n = entry_def->num_children;
2518 if (remainder.empty())
2523 // "${thread.info" <TAB>
2524 matches.AppendString(std::move(MakeMatch (str, ".")));
2528 // "${thread.id" <TAB>
2529 matches.AppendString(std::move(MakeMatch (str, "}")));
2530 word_complete = true;
2533 else if (remainder.equals("."))
2535 // "${thread." <TAB>
2536 AddMatches(entry_def, str, llvm::StringRef(), matches);
2540 // We have a partial match
2542 AddMatches(entry_def, str, remainder, matches);
2550 return matches.GetSize();