1 //===-- FormatEntity.cpp ----------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/FormatEntity.h"
11 #include "lldb/Core/Address.h"
12 #include "lldb/Core/AddressRange.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/DumpRegisterValue.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ValueObject.h"
17 #include "lldb/Core/ValueObjectVariable.h"
18 #include "lldb/DataFormatters/DataVisualization.h"
19 #include "lldb/DataFormatters/FormatClasses.h"
20 #include "lldb/DataFormatters/FormatManager.h"
21 #include "lldb/DataFormatters/TypeSummary.h"
22 #include "lldb/Expression/ExpressionVariable.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Symbol/Block.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/CompilerType.h"
27 #include "lldb/Symbol/Function.h"
28 #include "lldb/Symbol/LineEntry.h"
29 #include "lldb/Symbol/Symbol.h"
30 #include "lldb/Symbol/SymbolContext.h"
31 #include "lldb/Symbol/VariableList.h"
32 #include "lldb/Target/ExecutionContext.h"
33 #include "lldb/Target/ExecutionContextScope.h"
34 #include "lldb/Target/Language.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/RegisterContext.h"
37 #include "lldb/Target/SectionLoadList.h"
38 #include "lldb/Target/StackFrame.h"
39 #include "lldb/Target/StopInfo.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Target/Thread.h"
42 #include "lldb/Utility/AnsiTerminal.h"
43 #include "lldb/Utility/ArchSpec.h"
44 #include "lldb/Utility/ConstString.h"
45 #include "lldb/Utility/FileSpec.h"
46 #include "lldb/Utility/Log.h"
47 #include "lldb/Utility/Logging.h"
48 #include "lldb/Utility/RegisterValue.h"
49 #include "lldb/Utility/SharingPtr.h"
50 #include "lldb/Utility/Stream.h"
51 #include "lldb/Utility/StreamString.h"
52 #include "lldb/Utility/StringList.h"
53 #include "lldb/Utility/StructuredData.h"
54 #include "lldb/lldb-defines.h"
55 #include "lldb/lldb-forward.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/ADT/Triple.h"
59 #include "llvm/Support/Compiler.h"
67 #include <type_traits>
70 namespace lldb_private {
71 class ScriptInterpreter;
73 namespace lldb_private {
78 using namespace lldb_private;
80 enum FileKind { FileError = 0, Basename, Dirname, Fullpath };
83 { n, nullptr, FormatEntity::Entry::Type::t, 0, 0, nullptr, false }
84 #define ENTRY_VALUE(n, t, v) \
85 { n, nullptr, FormatEntity::Entry::Type::t, v, 0, nullptr, false }
86 #define ENTRY_CHILDREN(n, t, c) \
88 n, nullptr, FormatEntity::Entry::Type::t, 0, \
89 static_cast<uint32_t>(llvm::array_lengthof(c)), c, false \
91 #define ENTRY_CHILDREN_KEEP_SEP(n, t, c) \
93 n, nullptr, FormatEntity::Entry::Type::t, 0, \
94 static_cast<uint32_t>(llvm::array_lengthof(c)), c, true \
96 #define ENTRY_STRING(n, s) \
97 { n, s, FormatEntity::Entry::Type::EscapeCode, 0, 0, nullptr, false }
98 static FormatEntity::Entry::Definition g_string_entry[] = {
99 ENTRY("*", ParentString)};
101 static FormatEntity::Entry::Definition g_addr_entries[] = {
102 ENTRY("load", AddressLoad),
103 ENTRY("file", AddressFile),
104 ENTRY("load", AddressLoadOrFile),
107 static FormatEntity::Entry::Definition g_file_child_entries[] = {
108 ENTRY_VALUE("basename", ParentNumber, FileKind::Basename),
109 ENTRY_VALUE("dirname", ParentNumber, FileKind::Dirname),
110 ENTRY_VALUE("fullpath", ParentNumber, FileKind::Fullpath)};
112 static FormatEntity::Entry::Definition g_frame_child_entries[] = {
113 ENTRY("index", FrameIndex),
114 ENTRY("pc", FrameRegisterPC),
115 ENTRY("fp", FrameRegisterFP),
116 ENTRY("sp", FrameRegisterSP),
117 ENTRY("flags", FrameRegisterFlags),
118 ENTRY("no-debug", FrameNoDebug),
119 ENTRY_CHILDREN("reg", FrameRegisterByName, g_string_entry),
120 ENTRY("is-artificial", FrameIsArtificial),
123 static FormatEntity::Entry::Definition g_function_child_entries[] = {
124 ENTRY("id", FunctionID),
125 ENTRY("name", FunctionName),
126 ENTRY("name-without-args", FunctionNameNoArgs),
127 ENTRY("name-with-args", FunctionNameWithArgs),
128 ENTRY("addr-offset", FunctionAddrOffset),
129 ENTRY("concrete-only-addr-offset-no-padding", FunctionAddrOffsetConcrete),
130 ENTRY("line-offset", FunctionLineOffset),
131 ENTRY("pc-offset", FunctionPCOffset),
132 ENTRY("initial-function", FunctionInitial),
133 ENTRY("changed", FunctionChanged),
134 ENTRY("is-optimized", FunctionIsOptimized)};
136 static FormatEntity::Entry::Definition g_line_child_entries[] = {
137 ENTRY_CHILDREN("file", LineEntryFile, g_file_child_entries),
138 ENTRY("number", LineEntryLineNumber),
139 ENTRY("column", LineEntryColumn),
140 ENTRY("start-addr", LineEntryStartAddress),
141 ENTRY("end-addr", LineEntryEndAddress),
144 static FormatEntity::Entry::Definition g_module_child_entries[] = {
145 ENTRY_CHILDREN("file", ModuleFile, g_file_child_entries),
148 static FormatEntity::Entry::Definition g_process_child_entries[] = {
149 ENTRY("id", ProcessID),
150 ENTRY_VALUE("name", ProcessFile, FileKind::Basename),
151 ENTRY_CHILDREN("file", ProcessFile, g_file_child_entries),
154 static FormatEntity::Entry::Definition g_svar_child_entries[] = {
155 ENTRY("*", ParentString)};
157 static FormatEntity::Entry::Definition g_var_child_entries[] = {
158 ENTRY("*", ParentString)};
160 static FormatEntity::Entry::Definition g_thread_child_entries[] = {
161 ENTRY("id", ThreadID),
162 ENTRY("protocol_id", ThreadProtocolID),
163 ENTRY("index", ThreadIndexID),
164 ENTRY_CHILDREN("info", ThreadInfo, g_string_entry),
165 ENTRY("queue", ThreadQueue),
166 ENTRY("name", ThreadName),
167 ENTRY("stop-reason", ThreadStopReason),
168 ENTRY("return-value", ThreadReturnValue),
169 ENTRY("completed-expression", ThreadCompletedExpression),
172 static FormatEntity::Entry::Definition g_target_child_entries[] = {
173 ENTRY("arch", TargetArch),
176 #define _TO_STR2(_val) #_val
177 #define _TO_STR(_val) _TO_STR2(_val)
179 static FormatEntity::Entry::Definition g_ansi_fg_entries[] = {
180 ENTRY_STRING("black",
181 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLACK) ANSI_ESC_END),
182 ENTRY_STRING("red", ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_RED) ANSI_ESC_END),
183 ENTRY_STRING("green",
184 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_GREEN) ANSI_ESC_END),
185 ENTRY_STRING("yellow",
186 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_YELLOW) ANSI_ESC_END),
188 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLUE) ANSI_ESC_END),
189 ENTRY_STRING("purple",
190 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_PURPLE) ANSI_ESC_END),
192 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_CYAN) ANSI_ESC_END),
193 ENTRY_STRING("white",
194 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_WHITE) ANSI_ESC_END),
197 static FormatEntity::Entry::Definition g_ansi_bg_entries[] = {
198 ENTRY_STRING("black",
199 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLACK) ANSI_ESC_END),
200 ENTRY_STRING("red", ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_RED) ANSI_ESC_END),
201 ENTRY_STRING("green",
202 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_GREEN) ANSI_ESC_END),
203 ENTRY_STRING("yellow",
204 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_YELLOW) ANSI_ESC_END),
206 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLUE) ANSI_ESC_END),
207 ENTRY_STRING("purple",
208 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_PURPLE) ANSI_ESC_END),
210 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_CYAN) ANSI_ESC_END),
211 ENTRY_STRING("white",
212 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_WHITE) ANSI_ESC_END),
215 static FormatEntity::Entry::Definition g_ansi_entries[] = {
216 ENTRY_CHILDREN("fg", Invalid, g_ansi_fg_entries),
217 ENTRY_CHILDREN("bg", Invalid, g_ansi_bg_entries),
218 ENTRY_STRING("normal",
219 ANSI_ESC_START _TO_STR(ANSI_CTRL_NORMAL) ANSI_ESC_END),
220 ENTRY_STRING("bold", ANSI_ESC_START _TO_STR(ANSI_CTRL_BOLD) ANSI_ESC_END),
221 ENTRY_STRING("faint", ANSI_ESC_START _TO_STR(ANSI_CTRL_FAINT) ANSI_ESC_END),
222 ENTRY_STRING("italic",
223 ANSI_ESC_START _TO_STR(ANSI_CTRL_ITALIC) ANSI_ESC_END),
224 ENTRY_STRING("underline",
225 ANSI_ESC_START _TO_STR(ANSI_CTRL_UNDERLINE) ANSI_ESC_END),
226 ENTRY_STRING("slow-blink",
227 ANSI_ESC_START _TO_STR(ANSI_CTRL_SLOW_BLINK) ANSI_ESC_END),
228 ENTRY_STRING("fast-blink",
229 ANSI_ESC_START _TO_STR(ANSI_CTRL_FAST_BLINK) ANSI_ESC_END),
230 ENTRY_STRING("negative",
231 ANSI_ESC_START _TO_STR(ANSI_CTRL_IMAGE_NEGATIVE) ANSI_ESC_END),
232 ENTRY_STRING("conceal",
233 ANSI_ESC_START _TO_STR(ANSI_CTRL_CONCEAL) ANSI_ESC_END),
234 ENTRY_STRING("crossed-out",
235 ANSI_ESC_START _TO_STR(ANSI_CTRL_CROSSED_OUT) ANSI_ESC_END),
238 static FormatEntity::Entry::Definition g_script_child_entries[] = {
239 ENTRY("frame", ScriptFrame), ENTRY("process", ScriptProcess),
240 ENTRY("target", ScriptTarget), ENTRY("thread", ScriptThread),
241 ENTRY("var", ScriptVariable), ENTRY("svar", ScriptVariableSynthetic),
242 ENTRY("thread", ScriptThread),
245 static FormatEntity::Entry::Definition g_top_level_entries[] = {
246 ENTRY_CHILDREN("addr", AddressLoadOrFile, g_addr_entries),
247 ENTRY("addr-file-or-load", AddressLoadOrFile),
248 ENTRY_CHILDREN("ansi", Invalid, g_ansi_entries),
249 ENTRY("current-pc-arrow", CurrentPCArrow),
250 ENTRY_CHILDREN("file", File, g_file_child_entries),
251 ENTRY("language", Lang),
252 ENTRY_CHILDREN("frame", Invalid, g_frame_child_entries),
253 ENTRY_CHILDREN("function", Invalid, g_function_child_entries),
254 ENTRY_CHILDREN("line", Invalid, g_line_child_entries),
255 ENTRY_CHILDREN("module", Invalid, g_module_child_entries),
256 ENTRY_CHILDREN("process", Invalid, g_process_child_entries),
257 ENTRY_CHILDREN("script", Invalid, g_script_child_entries),
258 ENTRY_CHILDREN_KEEP_SEP("svar", VariableSynthetic, g_svar_child_entries),
259 ENTRY_CHILDREN("thread", Invalid, g_thread_child_entries),
260 ENTRY_CHILDREN("target", Invalid, g_target_child_entries),
261 ENTRY_CHILDREN_KEEP_SEP("var", Variable, g_var_child_entries),
264 static FormatEntity::Entry::Definition g_root =
265 ENTRY_CHILDREN("<root>", Root, g_top_level_entries);
267 FormatEntity::Entry::Entry(llvm::StringRef s)
268 : string(s.data(), s.size()), printf_format(), children(),
269 definition(nullptr), type(Type::String), fmt(lldb::eFormatDefault),
270 number(0), deref(false) {}
272 FormatEntity::Entry::Entry(char ch)
273 : string(1, ch), printf_format(), children(), definition(nullptr),
274 type(Type::String), fmt(lldb::eFormatDefault), number(0), deref(false) {}
276 void FormatEntity::Entry::AppendChar(char ch) {
277 if (children.empty() || children.back().type != Entry::Type::String)
278 children.push_back(Entry(ch));
280 children.back().string.append(1, ch);
283 void FormatEntity::Entry::AppendText(const llvm::StringRef &s) {
284 if (children.empty() || children.back().type != Entry::Type::String)
285 children.push_back(Entry(s));
287 children.back().string.append(s.data(), s.size());
290 void FormatEntity::Entry::AppendText(const char *cstr) {
291 return AppendText(llvm::StringRef(cstr));
294 Status FormatEntity::Parse(const llvm::StringRef &format_str, Entry &entry) {
296 entry.type = Entry::Type::Root;
297 llvm::StringRef modifiable_format(format_str);
298 return ParseInternal(modifiable_format, entry, 0);
301 #define ENUM_TO_CSTR(eee) \
302 case FormatEntity::Entry::Type::eee: \
305 const char *FormatEntity::Entry::TypeToCString(Type t) {
307 ENUM_TO_CSTR(Invalid);
308 ENUM_TO_CSTR(ParentNumber);
309 ENUM_TO_CSTR(ParentString);
310 ENUM_TO_CSTR(EscapeCode);
312 ENUM_TO_CSTR(String);
314 ENUM_TO_CSTR(Variable);
315 ENUM_TO_CSTR(VariableSynthetic);
316 ENUM_TO_CSTR(ScriptVariable);
317 ENUM_TO_CSTR(ScriptVariableSynthetic);
318 ENUM_TO_CSTR(AddressLoad);
319 ENUM_TO_CSTR(AddressFile);
320 ENUM_TO_CSTR(AddressLoadOrFile);
321 ENUM_TO_CSTR(ProcessID);
322 ENUM_TO_CSTR(ProcessFile);
323 ENUM_TO_CSTR(ScriptProcess);
324 ENUM_TO_CSTR(ThreadID);
325 ENUM_TO_CSTR(ThreadProtocolID);
326 ENUM_TO_CSTR(ThreadIndexID);
327 ENUM_TO_CSTR(ThreadName);
328 ENUM_TO_CSTR(ThreadQueue);
329 ENUM_TO_CSTR(ThreadStopReason);
330 ENUM_TO_CSTR(ThreadReturnValue);
331 ENUM_TO_CSTR(ThreadCompletedExpression);
332 ENUM_TO_CSTR(ScriptThread);
333 ENUM_TO_CSTR(ThreadInfo);
334 ENUM_TO_CSTR(TargetArch);
335 ENUM_TO_CSTR(ScriptTarget);
336 ENUM_TO_CSTR(ModuleFile);
339 ENUM_TO_CSTR(FrameIndex);
340 ENUM_TO_CSTR(FrameNoDebug);
341 ENUM_TO_CSTR(FrameRegisterPC);
342 ENUM_TO_CSTR(FrameRegisterSP);
343 ENUM_TO_CSTR(FrameRegisterFP);
344 ENUM_TO_CSTR(FrameRegisterFlags);
345 ENUM_TO_CSTR(FrameRegisterByName);
346 ENUM_TO_CSTR(FrameIsArtificial);
347 ENUM_TO_CSTR(ScriptFrame);
348 ENUM_TO_CSTR(FunctionID);
349 ENUM_TO_CSTR(FunctionDidChange);
350 ENUM_TO_CSTR(FunctionInitialFunction);
351 ENUM_TO_CSTR(FunctionName);
352 ENUM_TO_CSTR(FunctionNameWithArgs);
353 ENUM_TO_CSTR(FunctionNameNoArgs);
354 ENUM_TO_CSTR(FunctionAddrOffset);
355 ENUM_TO_CSTR(FunctionAddrOffsetConcrete);
356 ENUM_TO_CSTR(FunctionLineOffset);
357 ENUM_TO_CSTR(FunctionPCOffset);
358 ENUM_TO_CSTR(FunctionInitial);
359 ENUM_TO_CSTR(FunctionChanged);
360 ENUM_TO_CSTR(FunctionIsOptimized);
361 ENUM_TO_CSTR(LineEntryFile);
362 ENUM_TO_CSTR(LineEntryLineNumber);
363 ENUM_TO_CSTR(LineEntryColumn);
364 ENUM_TO_CSTR(LineEntryStartAddress);
365 ENUM_TO_CSTR(LineEntryEndAddress);
366 ENUM_TO_CSTR(CurrentPCArrow);
373 void FormatEntity::Entry::Dump(Stream &s, int depth) const {
374 s.Printf("%*.*s%-20s: ", depth * 2, depth * 2, "", TypeToCString(type));
375 if (fmt != eFormatDefault)
376 s.Printf("lldb-format = %s, ", FormatManager::GetFormatAsCString(fmt));
378 s.Printf("string = \"%s\"", string.c_str());
379 if (!printf_format.empty())
380 s.Printf("printf_format = \"%s\"", printf_format.c_str());
382 s.Printf("number = %" PRIu64 " (0x%" PRIx64 "), ", number, number);
384 s.Printf("deref = true, ");
386 for (const auto &child : children) {
387 child.Dump(s, depth + 1);
391 template <typename T>
392 static bool RunScriptFormatKeyword(Stream &s, const SymbolContext *sc,
393 const ExecutionContext *exe_ctx, T t,
394 const char *script_function_name) {
395 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
398 ScriptInterpreter *script_interpreter =
399 target->GetDebugger().GetScriptInterpreter();
400 if (script_interpreter) {
402 std::string script_output;
404 if (script_interpreter->RunScriptFormatKeyword(script_function_name, t,
405 script_output, error) &&
407 s.Printf("%s", script_output.c_str());
410 s.Printf("<error: %s>", error.AsCString());
417 static bool DumpAddress(Stream &s, const SymbolContext *sc,
418 const ExecutionContext *exe_ctx, const Address &addr,
419 bool print_file_addr_or_load_addr) {
420 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
421 addr_t vaddr = LLDB_INVALID_ADDRESS;
422 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
423 vaddr = addr.GetLoadAddress(target);
424 if (vaddr == LLDB_INVALID_ADDRESS)
425 vaddr = addr.GetFileAddress();
427 if (vaddr != LLDB_INVALID_ADDRESS) {
429 if (exe_ctx && target) {
430 addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
434 if (print_file_addr_or_load_addr) {
435 ExecutionContextScope *exe_scope = nullptr;
437 exe_scope = exe_ctx->GetBestExecutionContextScope();
438 addr.Dump(&s, exe_scope, Address::DumpStyleLoadAddress,
439 Address::DumpStyleModuleWithFileAddress, 0);
441 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
448 static bool DumpAddressOffsetFromFunction(Stream &s, const SymbolContext *sc,
449 const ExecutionContext *exe_ctx,
450 const Address &format_addr,
451 bool concrete_only, bool no_padding,
452 bool print_zero_offsets) {
453 if (format_addr.IsValid()) {
458 func_addr = sc->function->GetAddressRange().GetBaseAddress();
459 if (sc->block && !concrete_only) {
460 // Check to make sure we aren't in an inline function. If we are, use
461 // the inline block range that contains "format_addr" since blocks
462 // can be discontiguous.
463 Block *inline_block = sc->block->GetContainingInlinedBlock();
464 AddressRange inline_range;
465 if (inline_block && inline_block->GetRangeContainingAddress(
466 format_addr, inline_range))
467 func_addr = inline_range.GetBaseAddress();
469 } else if (sc->symbol && sc->symbol->ValueIsAddress())
470 func_addr = sc->symbol->GetAddressRef();
473 if (func_addr.IsValid()) {
474 const char *addr_offset_padding = no_padding ? "" : " ";
476 if (func_addr.GetSection() == format_addr.GetSection()) {
477 addr_t func_file_addr = func_addr.GetFileAddress();
478 addr_t addr_file_addr = format_addr.GetFileAddress();
479 if (addr_file_addr > func_file_addr ||
480 (addr_file_addr == func_file_addr && print_zero_offsets)) {
481 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding,
482 addr_file_addr - func_file_addr);
483 } else if (addr_file_addr < func_file_addr) {
484 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding,
485 func_file_addr - addr_file_addr);
489 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
491 addr_t func_load_addr = func_addr.GetLoadAddress(target);
492 addr_t addr_load_addr = format_addr.GetLoadAddress(target);
493 if (addr_load_addr > func_load_addr ||
494 (addr_load_addr == func_load_addr && print_zero_offsets)) {
495 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding,
496 addr_load_addr - func_load_addr);
497 } else if (addr_load_addr < func_load_addr) {
498 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding,
499 func_load_addr - addr_load_addr);
509 static bool ScanBracketedRange(llvm::StringRef subpath,
510 size_t &close_bracket_index,
511 const char *&var_name_final_if_array_range,
512 int64_t &index_lower, int64_t &index_higher) {
513 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
514 close_bracket_index = llvm::StringRef::npos;
515 const size_t open_bracket_index = subpath.find('[');
516 if (open_bracket_index == llvm::StringRef::npos) {
518 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
522 close_bracket_index = subpath.find(']', open_bracket_index + 1);
524 if (close_bracket_index == llvm::StringRef::npos) {
526 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
529 var_name_final_if_array_range = subpath.data() + open_bracket_index;
531 if (close_bracket_index - open_bracket_index == 1) {
534 "[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
537 const size_t separator_index = subpath.find('-', open_bracket_index + 1);
539 if (separator_index == llvm::StringRef::npos) {
540 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
541 index_lower = ::strtoul(index_lower_cstr, nullptr, 0);
542 index_higher = index_lower;
544 log->Printf("[ScanBracketedRange] [%" PRId64
545 "] detected, high index is same",
548 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
549 const char *index_higher_cstr = subpath.data() + separator_index + 1;
550 index_lower = ::strtoul(index_lower_cstr, nullptr, 0);
551 index_higher = ::strtoul(index_higher_cstr, nullptr, 0);
553 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected",
554 index_lower, index_higher);
556 if (index_lower > index_higher && index_higher > 0) {
558 log->Printf("[ScanBracketedRange] swapping indices");
559 const int64_t temp = index_lower;
560 index_lower = index_higher;
568 static bool DumpFile(Stream &s, const FileSpec &file, FileKind file_kind) {
570 case FileKind::FileError:
573 case FileKind::Basename:
574 if (file.GetFilename()) {
575 s << file.GetFilename();
580 case FileKind::Dirname:
581 if (file.GetDirectory()) {
582 s << file.GetDirectory();
587 case FileKind::Fullpath:
597 static bool DumpRegister(Stream &s, StackFrame *frame, RegisterKind reg_kind,
598 uint32_t reg_num, Format format)
602 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
605 const uint32_t lldb_reg_num =
606 reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
607 if (lldb_reg_num != LLDB_INVALID_REGNUM) {
608 const RegisterInfo *reg_info =
609 reg_ctx->GetRegisterInfoAtIndex(lldb_reg_num);
611 RegisterValue reg_value;
612 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
613 DumpRegisterValue(reg_value, &s, reg_info, false, false, format);
623 static ValueObjectSP ExpandIndexedExpression(ValueObject *valobj, size_t index,
625 bool deref_pointer) {
626 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
627 const char *ptr_deref_format = "[%d]";
628 std::string ptr_deref_buffer(10, 0);
629 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
631 log->Printf("[ExpandIndexedExpression] name to deref: %s",
632 ptr_deref_buffer.c_str());
633 ValueObject::GetValueForExpressionPathOptions options;
634 ValueObject::ExpressionPathEndResultType final_value_type;
635 ValueObject::ExpressionPathScanEndReason reason_to_stop;
636 ValueObject::ExpressionPathAftermath what_next =
637 (deref_pointer ? ValueObject::eExpressionPathAftermathDereference
638 : ValueObject::eExpressionPathAftermathNothing);
639 ValueObjectSP item = valobj->GetValueForExpressionPath(
640 ptr_deref_buffer.c_str(), &reason_to_stop, &final_value_type, options,
644 log->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
645 " final_value_type %d",
646 reason_to_stop, final_value_type);
649 log->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
650 " final_value_type %d",
651 reason_to_stop, final_value_type);
656 static char ConvertValueObjectStyleToChar(
657 ValueObject::ValueObjectRepresentationStyle style) {
659 case ValueObject::eValueObjectRepresentationStyleLanguageSpecific:
661 case ValueObject::eValueObjectRepresentationStyleValue:
663 case ValueObject::eValueObjectRepresentationStyleLocation:
665 case ValueObject::eValueObjectRepresentationStyleSummary:
667 case ValueObject::eValueObjectRepresentationStyleChildrenCount:
669 case ValueObject::eValueObjectRepresentationStyleType:
671 case ValueObject::eValueObjectRepresentationStyleName:
673 case ValueObject::eValueObjectRepresentationStyleExpressionPath:
679 static bool DumpValue(Stream &s, const SymbolContext *sc,
680 const ExecutionContext *exe_ctx,
681 const FormatEntity::Entry &entry, ValueObject *valobj) {
682 if (valobj == nullptr)
685 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
686 Format custom_format = eFormatInvalid;
687 ValueObject::ValueObjectRepresentationStyle val_obj_display =
689 ? ValueObject::eValueObjectRepresentationStyleValue
690 : ValueObject::eValueObjectRepresentationStyleSummary;
692 bool do_deref_pointer = entry.deref;
693 bool is_script = false;
694 switch (entry.type) {
695 case FormatEntity::Entry::Type::ScriptVariable:
699 case FormatEntity::Entry::Type::Variable:
700 custom_format = entry.fmt;
701 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
704 case FormatEntity::Entry::Type::ScriptVariableSynthetic:
707 case FormatEntity::Entry::Type::VariableSynthetic:
708 custom_format = entry.fmt;
709 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
710 if (!valobj->IsSynthetic()) {
711 valobj = valobj->GetSyntheticValue().get();
712 if (valobj == nullptr)
721 if (valobj == nullptr)
724 ValueObject::ExpressionPathAftermath what_next =
725 (do_deref_pointer ? ValueObject::eExpressionPathAftermathDereference
726 : ValueObject::eExpressionPathAftermathNothing);
727 ValueObject::GetValueForExpressionPathOptions options;
728 options.DontCheckDotVsArrowSyntax()
729 .DoAllowBitfieldSyntax()
730 .DoAllowFragileIVar()
731 .SetSyntheticChildrenTraversal(
732 ValueObject::GetValueForExpressionPathOptions::
733 SyntheticChildrenTraversal::Both);
734 ValueObject *target = nullptr;
735 const char *var_name_final_if_array_range = nullptr;
736 size_t close_bracket_index = llvm::StringRef::npos;
737 int64_t index_lower = -1;
738 int64_t index_higher = -1;
739 bool is_array_range = false;
740 bool was_plain_var = false;
741 bool was_var_format = false;
742 bool was_var_indexed = false;
743 ValueObject::ExpressionPathScanEndReason reason_to_stop =
744 ValueObject::eExpressionPathScanEndReasonEndOfString;
745 ValueObject::ExpressionPathEndResultType final_value_type =
746 ValueObject::eExpressionPathEndResultTypePlain;
749 return RunScriptFormatKeyword(s, sc, exe_ctx, valobj, entry.string.c_str());
752 llvm::StringRef subpath(entry.string);
753 // simplest case ${var}, just print valobj's value
754 if (entry.string.empty()) {
755 if (entry.printf_format.empty() && entry.fmt == eFormatDefault &&
756 entry.number == ValueObject::eValueObjectRepresentationStyleValue)
757 was_plain_var = true;
759 was_var_format = true;
761 } else // this is ${var.something} or multiple .something nested
763 if (entry.string[0] == '[')
764 was_var_indexed = true;
765 ScanBracketedRange(subpath, close_bracket_index,
766 var_name_final_if_array_range, index_lower,
771 const std::string &expr_path = entry.string;
774 log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",
779 ->GetValueForExpressionPath(expr_path.c_str(), &reason_to_stop,
780 &final_value_type, options, &what_next)
785 log->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
786 " final_value_type %d",
787 reason_to_stop, final_value_type);
791 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
792 " final_value_type %d",
793 reason_to_stop, final_value_type);
795 ->GetQualifiedRepresentationIfAvailable(
796 target->GetDynamicValueType(), true)
803 ValueObject::eExpressionPathEndResultTypeBoundedRange ||
805 ValueObject::eExpressionPathEndResultTypeUnboundedRange);
808 (what_next == ValueObject::eExpressionPathAftermathDereference);
810 if (do_deref_pointer && !is_array_range) {
811 // I have not deref-ed yet, let's do it
812 // this happens when we are not going through
813 // GetValueForVariableExpressionPath to get to the target ValueObject
815 target = target->Dereference(error).get();
818 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n",
819 error.AsCString("unknown"));
822 do_deref_pointer = false;
827 log->Printf("[Debugger::FormatPrompt] could not calculate target for "
828 "prompt expression");
832 // we do not want to use the summary for a bitfield of type T:n if we were
833 // originally dealing with just a T - that would get us into an endless
835 if (target->IsBitfield() && was_var_indexed) {
836 // TODO: check for a (T:n)-specific summary - we should still obey that
837 StreamString bitfield_name;
838 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
839 target->GetBitfieldBitSize());
840 auto type_sp = std::make_shared<TypeNameSpecifierImpl>(
841 bitfield_name.GetString(), false);
842 if (val_obj_display ==
843 ValueObject::eValueObjectRepresentationStyleSummary &&
844 !DataVisualization::GetSummaryForType(type_sp))
845 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
848 // TODO use flags for these
849 const uint32_t type_info_flags =
850 target->GetCompilerType().GetTypeInfo(nullptr);
851 bool is_array = (type_info_flags & eTypeIsArray) != 0;
852 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
853 bool is_aggregate = target->GetCompilerType().IsAggregateType();
855 if ((is_array || is_pointer) && (!is_array_range) &&
857 ValueObject::eValueObjectRepresentationStyleValue) // this should be
862 StreamString str_temp;
865 "[Debugger::FormatPrompt] I am into array || pointer && !range");
867 if (target->HasSpecialPrintableRepresentation(val_obj_display,
869 // try to use the special cases
870 bool success = target->DumpPrintableRepresentation(
871 str_temp, val_obj_display, custom_format);
873 log->Printf("[Debugger::FormatPrompt] special cases did%s match",
874 success ? "" : "n't");
878 s << str_temp.GetString();
881 if (was_plain_var) // if ${var}
883 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
884 } else if (is_pointer) // if pointer, value is the address stored
886 target->DumpPrintableRepresentation(
887 s, val_obj_display, custom_format,
888 ValueObject::PrintableRepresentationSpecialCases::eDisable);
894 // if directly trying to print ${var}, and this is an aggregate, display a
895 // nice type @ location message
896 if (is_aggregate && was_plain_var) {
897 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
901 // if directly trying to print ${var%V}, and this is an aggregate, do not let
906 ValueObject::eValueObjectRepresentationStyleValue))) {
907 s << "<invalid use of aggregate type>";
911 if (!is_array_range) {
913 log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
914 return target->DumpPrintableRepresentation(s, val_obj_display,
918 log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
919 if (!is_array && !is_pointer)
922 log->Printf("[Debugger::FormatPrompt] handle as array");
923 StreamString special_directions_stream;
924 llvm::StringRef special_directions;
925 if (close_bracket_index != llvm::StringRef::npos &&
926 subpath.size() > close_bracket_index) {
927 ConstString additional_data(subpath.drop_front(close_bracket_index + 1));
928 special_directions_stream.Printf("${%svar%s", do_deref_pointer ? "*" : "",
929 additional_data.GetCString());
931 if (entry.fmt != eFormatDefault) {
932 const char format_char =
933 FormatManager::GetFormatAsFormatChar(entry.fmt);
934 if (format_char != '\0')
935 special_directions_stream.Printf("%%%c", format_char);
937 const char *format_cstr =
938 FormatManager::GetFormatAsCString(entry.fmt);
939 special_directions_stream.Printf("%%%s", format_cstr);
941 } else if (entry.number != 0) {
942 const char style_char = ConvertValueObjectStyleToChar(
943 (ValueObject::ValueObjectRepresentationStyle)entry.number);
945 special_directions_stream.Printf("%%%c", style_char);
947 special_directions_stream.PutChar('}');
949 llvm::StringRef(special_directions_stream.GetString());
952 // let us display items index_lower thru index_higher of this array
955 if (index_higher < 0)
956 index_higher = valobj->GetNumChildren() - 1;
958 uint32_t max_num_children =
959 target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
962 for (int64_t index = index_lower; index <= index_higher; ++index) {
964 ExpandIndexedExpression(target, index, exe_ctx->GetFramePtr(), false)
969 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
975 "[Debugger::FormatPrompt] special_directions for child item: %s",
976 special_directions.data() ? special_directions.data() : "");
979 if (special_directions.empty()) {
980 success &= item->DumpPrintableRepresentation(s, val_obj_display,
983 success &= FormatEntity::FormatStringRef(
984 special_directions, s, sc, exe_ctx, nullptr, item, false, false);
987 if (--max_num_children == 0) {
988 s.PutCString(", ...");
992 if (index < index_higher)
1000 static bool DumpRegister(Stream &s, StackFrame *frame, const char *reg_name,
1003 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
1006 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
1008 RegisterValue reg_value;
1009 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
1010 DumpRegisterValue(reg_value, &s, reg_info, false, false, format);
1019 static bool FormatThreadExtendedInfoRecurse(
1020 const FormatEntity::Entry &entry,
1021 const StructuredData::ObjectSP &thread_info_dictionary,
1022 const SymbolContext *sc, const ExecutionContext *exe_ctx, Stream &s) {
1023 llvm::StringRef path(entry.string);
1025 StructuredData::ObjectSP value =
1026 thread_info_dictionary->GetObjectForDotSeparatedPath(path);
1029 if (value->GetType() == eStructuredDataTypeInteger) {
1030 const char *token_format = "0x%4.4" PRIx64;
1031 if (!entry.printf_format.empty())
1032 token_format = entry.printf_format.c_str();
1033 s.Printf(token_format, value->GetAsInteger()->GetValue());
1035 } else if (value->GetType() == eStructuredDataTypeFloat) {
1036 s.Printf("%f", value->GetAsFloat()->GetValue());
1038 } else if (value->GetType() == eStructuredDataTypeString) {
1039 s.Format("{0}", value->GetAsString()->GetValue());
1041 } else if (value->GetType() == eStructuredDataTypeArray) {
1042 if (value->GetAsArray()->GetSize() > 0) {
1043 s.Printf("%zu", value->GetAsArray()->GetSize());
1046 } else if (value->GetType() == eStructuredDataTypeDictionary) {
1048 value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1056 static inline bool IsToken(const char *var_name_begin, const char *var) {
1057 return (::strncmp(var_name_begin, var, strlen(var)) == 0);
1060 bool FormatEntity::FormatStringRef(const llvm::StringRef &format_str, Stream &s,
1061 const SymbolContext *sc,
1062 const ExecutionContext *exe_ctx,
1063 const Address *addr, ValueObject *valobj,
1064 bool function_changed,
1065 bool initial_function) {
1066 if (!format_str.empty()) {
1067 FormatEntity::Entry root;
1068 Status error = FormatEntity::Parse(format_str, root);
1069 if (error.Success()) {
1070 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj,
1071 function_changed, initial_function);
1077 bool FormatEntity::FormatCString(const char *format, Stream &s,
1078 const SymbolContext *sc,
1079 const ExecutionContext *exe_ctx,
1080 const Address *addr, ValueObject *valobj,
1081 bool function_changed, bool initial_function) {
1082 if (format && format[0]) {
1083 FormatEntity::Entry root;
1084 llvm::StringRef format_str(format);
1085 Status error = FormatEntity::Parse(format_str, root);
1086 if (error.Success()) {
1087 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj,
1088 function_changed, initial_function);
1094 bool FormatEntity::Format(const Entry &entry, Stream &s,
1095 const SymbolContext *sc,
1096 const ExecutionContext *exe_ctx, const Address *addr,
1097 ValueObject *valobj, bool function_changed,
1098 bool initial_function) {
1099 switch (entry.type) {
1100 case Entry::Type::Invalid:
1101 case Entry::Type::ParentNumber: // Only used for
1102 // FormatEntity::Entry::Definition encoding
1103 case Entry::Type::ParentString: // Only used for
1104 // FormatEntity::Entry::Definition encoding
1106 case Entry::Type::EscapeCode:
1108 if (Target *target = exe_ctx->GetTargetPtr()) {
1109 Debugger &debugger = target->GetDebugger();
1110 if (debugger.GetUseColor()) {
1111 s.PutCString(entry.string);
1115 // Always return true, so colors being disabled is transparent.
1118 case Entry::Type::Root:
1119 for (const auto &child : entry.children) {
1120 if (!Format(child, s, sc, exe_ctx, addr, valobj, function_changed,
1121 initial_function)) {
1122 return false; // If any item of root fails, then the formatting fails
1125 return true; // Only return true if all items succeeded
1127 case Entry::Type::String:
1128 s.PutCString(entry.string);
1131 case Entry::Type::Scope: {
1132 StreamString scope_stream;
1133 bool success = false;
1134 for (const auto &child : entry.children) {
1135 success = Format(child, scope_stream, sc, exe_ctx, addr, valobj,
1136 function_changed, initial_function);
1140 // Only if all items in a scope succeed, then do we print the output into
1143 s.Write(scope_stream.GetString().data(), scope_stream.GetString().size());
1145 return true; // Scopes always successfully print themselves
1147 case Entry::Type::Variable:
1148 case Entry::Type::VariableSynthetic:
1149 case Entry::Type::ScriptVariable:
1150 case Entry::Type::ScriptVariableSynthetic:
1151 return DumpValue(s, sc, exe_ctx, entry, valobj);
1153 case Entry::Type::AddressFile:
1154 case Entry::Type::AddressLoad:
1155 case Entry::Type::AddressLoadOrFile:
1156 return (addr != nullptr && addr->IsValid() &&
1157 DumpAddress(s, sc, exe_ctx, *addr,
1158 entry.type == Entry::Type::AddressLoadOrFile));
1160 case Entry::Type::ProcessID:
1162 Process *process = exe_ctx->GetProcessPtr();
1164 const char *format = "%" PRIu64;
1165 if (!entry.printf_format.empty())
1166 format = entry.printf_format.c_str();
1167 s.Printf(format, process->GetID());
1173 case Entry::Type::ProcessFile:
1175 Process *process = exe_ctx->GetProcessPtr();
1177 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1179 if (DumpFile(s, exe_module->GetFileSpec(), (FileKind)entry.number))
1186 case Entry::Type::ScriptProcess:
1188 Process *process = exe_ctx->GetProcessPtr();
1190 return RunScriptFormatKeyword(s, sc, exe_ctx, process,
1191 entry.string.c_str());
1195 case Entry::Type::ThreadID:
1197 Thread *thread = exe_ctx->GetThreadPtr();
1199 const char *format = "0x%4.4" PRIx64;
1200 if (!entry.printf_format.empty()) {
1201 // Watch for the special "tid" format...
1202 if (entry.printf_format == "tid") {
1203 // TODO(zturner): Rather than hardcoding this to be platform
1204 // specific, it should be controlled by a setting and the default
1205 // value of the setting can be different depending on the platform.
1206 Target &target = thread->GetProcess()->GetTarget();
1207 ArchSpec arch(target.GetArchitecture());
1208 llvm::Triple::OSType ostype = arch.IsValid()
1209 ? arch.GetTriple().getOS()
1210 : llvm::Triple::UnknownOS;
1211 if ((ostype == llvm::Triple::FreeBSD) ||
1212 (ostype == llvm::Triple::Linux) ||
1213 (ostype == llvm::Triple::NetBSD)) {
1214 format = "%" PRIu64;
1217 format = entry.printf_format.c_str();
1220 s.Printf(format, thread->GetID());
1226 case Entry::Type::ThreadProtocolID:
1228 Thread *thread = exe_ctx->GetThreadPtr();
1230 const char *format = "0x%4.4" PRIx64;
1231 if (!entry.printf_format.empty())
1232 format = entry.printf_format.c_str();
1233 s.Printf(format, thread->GetProtocolID());
1239 case Entry::Type::ThreadIndexID:
1241 Thread *thread = exe_ctx->GetThreadPtr();
1243 const char *format = "%" PRIu32;
1244 if (!entry.printf_format.empty())
1245 format = entry.printf_format.c_str();
1246 s.Printf(format, thread->GetIndexID());
1252 case Entry::Type::ThreadName:
1254 Thread *thread = exe_ctx->GetThreadPtr();
1256 const char *cstr = thread->GetName();
1257 if (cstr && cstr[0]) {
1265 case Entry::Type::ThreadQueue:
1267 Thread *thread = exe_ctx->GetThreadPtr();
1269 const char *cstr = thread->GetQueueName();
1270 if (cstr && cstr[0]) {
1278 case Entry::Type::ThreadStopReason:
1280 Thread *thread = exe_ctx->GetThreadPtr();
1282 StopInfoSP stop_info_sp = thread->GetStopInfo();
1283 if (stop_info_sp && stop_info_sp->IsValid()) {
1284 const char *cstr = stop_info_sp->GetDescription();
1285 if (cstr && cstr[0]) {
1294 case Entry::Type::ThreadReturnValue:
1296 Thread *thread = exe_ctx->GetThreadPtr();
1298 StopInfoSP stop_info_sp = thread->GetStopInfo();
1299 if (stop_info_sp && stop_info_sp->IsValid()) {
1300 ValueObjectSP return_valobj_sp =
1301 StopInfo::GetReturnValueObject(stop_info_sp);
1302 if (return_valobj_sp) {
1303 return_valobj_sp->Dump(s);
1311 case Entry::Type::ThreadCompletedExpression:
1313 Thread *thread = exe_ctx->GetThreadPtr();
1315 StopInfoSP stop_info_sp = thread->GetStopInfo();
1316 if (stop_info_sp && stop_info_sp->IsValid()) {
1317 ExpressionVariableSP expression_var_sp =
1318 StopInfo::GetExpressionVariable(stop_info_sp);
1319 if (expression_var_sp && expression_var_sp->GetValueObject()) {
1320 expression_var_sp->GetValueObject()->Dump(s);
1328 case Entry::Type::ScriptThread:
1330 Thread *thread = exe_ctx->GetThreadPtr();
1332 return RunScriptFormatKeyword(s, sc, exe_ctx, thread,
1333 entry.string.c_str());
1337 case Entry::Type::ThreadInfo:
1339 Thread *thread = exe_ctx->GetThreadPtr();
1341 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
1343 object_sp->GetType() == eStructuredDataTypeDictionary) {
1344 if (FormatThreadExtendedInfoRecurse(entry, object_sp, sc, exe_ctx, s))
1351 case Entry::Type::TargetArch:
1353 Target *target = exe_ctx->GetTargetPtr();
1355 const ArchSpec &arch = target->GetArchitecture();
1356 if (arch.IsValid()) {
1357 s.PutCString(arch.GetArchitectureName());
1364 case Entry::Type::ScriptTarget:
1366 Target *target = exe_ctx->GetTargetPtr();
1368 return RunScriptFormatKeyword(s, sc, exe_ctx, target,
1369 entry.string.c_str());
1373 case Entry::Type::ModuleFile:
1375 Module *module = sc->module_sp.get();
1377 if (DumpFile(s, module->GetFileSpec(), (FileKind)entry.number))
1383 case Entry::Type::File:
1385 CompileUnit *cu = sc->comp_unit;
1387 // CompileUnit is a FileSpec
1388 if (DumpFile(s, *cu, (FileKind)entry.number))
1394 case Entry::Type::Lang:
1396 CompileUnit *cu = sc->comp_unit;
1398 const char *lang_name =
1399 Language::GetNameForLanguageType(cu->GetLanguage());
1401 s.PutCString(lang_name);
1408 case Entry::Type::FrameIndex:
1410 StackFrame *frame = exe_ctx->GetFramePtr();
1412 const char *format = "%" PRIu32;
1413 if (!entry.printf_format.empty())
1414 format = entry.printf_format.c_str();
1415 s.Printf(format, frame->GetFrameIndex());
1421 case Entry::Type::FrameRegisterPC:
1423 StackFrame *frame = exe_ctx->GetFramePtr();
1425 const Address &pc_addr = frame->GetFrameCodeAddress();
1426 if (pc_addr.IsValid()) {
1427 if (DumpAddress(s, sc, exe_ctx, pc_addr, false))
1434 case Entry::Type::FrameRegisterSP:
1436 StackFrame *frame = exe_ctx->GetFramePtr();
1438 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP,
1439 (lldb::Format)entry.number))
1445 case Entry::Type::FrameRegisterFP:
1447 StackFrame *frame = exe_ctx->GetFramePtr();
1449 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP,
1450 (lldb::Format)entry.number))
1456 case Entry::Type::FrameRegisterFlags:
1458 StackFrame *frame = exe_ctx->GetFramePtr();
1460 if (DumpRegister(s, frame, eRegisterKindGeneric,
1461 LLDB_REGNUM_GENERIC_FLAGS, (lldb::Format)entry.number))
1467 case Entry::Type::FrameNoDebug:
1469 StackFrame *frame = exe_ctx->GetFramePtr();
1471 return !frame->HasDebugInformation();
1476 case Entry::Type::FrameRegisterByName:
1478 StackFrame *frame = exe_ctx->GetFramePtr();
1480 if (DumpRegister(s, frame, entry.string.c_str(),
1481 (lldb::Format)entry.number))
1487 case Entry::Type::FrameIsArtificial: {
1489 if (StackFrame *frame = exe_ctx->GetFramePtr())
1490 return frame->IsArtificial();
1494 case Entry::Type::ScriptFrame:
1496 StackFrame *frame = exe_ctx->GetFramePtr();
1498 return RunScriptFormatKeyword(s, sc, exe_ctx, frame,
1499 entry.string.c_str());
1503 case Entry::Type::FunctionID:
1506 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
1508 } else if (sc->symbol) {
1509 s.Printf("symbol[%u]", sc->symbol->GetID());
1515 case Entry::Type::FunctionDidChange:
1516 return function_changed;
1518 case Entry::Type::FunctionInitialFunction:
1519 return initial_function;
1521 case Entry::Type::FunctionName: {
1522 Language *language_plugin = nullptr;
1523 bool language_plugin_handled = false;
1526 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1527 else if (sc->symbol)
1528 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1529 if (language_plugin) {
1530 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1531 sc, exe_ctx, Language::FunctionNameRepresentation::eName, ss);
1533 if (language_plugin_handled) {
1534 s << ss.GetString();
1537 const char *name = nullptr;
1539 name = sc->function->GetName().AsCString(nullptr);
1540 else if (sc->symbol)
1541 name = sc->symbol->GetName().AsCString(nullptr);
1546 Block *inline_block = sc->block->GetContainingInlinedBlock();
1548 const InlineFunctionInfo *inline_info =
1549 sc->block->GetInlinedFunctionInfo();
1551 s.PutCString(" [inlined] ");
1552 inline_info->GetName(sc->function->GetLanguage()).Dump(&s);
1562 case Entry::Type::FunctionNameNoArgs: {
1563 Language *language_plugin = nullptr;
1564 bool language_plugin_handled = false;
1567 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1568 else if (sc->symbol)
1569 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1570 if (language_plugin) {
1571 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1572 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithNoArgs,
1575 if (language_plugin_handled) {
1576 s << ss.GetString();
1581 name = sc->function->GetNameNoArguments();
1582 else if (sc->symbol)
1583 name = sc->symbol->GetNameNoArguments();
1585 s.PutCString(name.GetCString());
1592 case Entry::Type::FunctionNameWithArgs: {
1593 Language *language_plugin = nullptr;
1594 bool language_plugin_handled = false;
1597 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1598 else if (sc->symbol)
1599 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1600 if (language_plugin) {
1601 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1602 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithArgs, ss);
1604 if (language_plugin_handled) {
1605 s << ss.GetString();
1608 // Print the function name with arguments in it
1610 ExecutionContextScope *exe_scope =
1611 exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
1612 const char *cstr = sc->function->GetName().AsCString(nullptr);
1614 const InlineFunctionInfo *inline_info = nullptr;
1615 VariableListSP variable_list_sp;
1616 bool get_function_vars = true;
1618 Block *inline_block = sc->block->GetContainingInlinedBlock();
1621 get_function_vars = false;
1622 inline_info = sc->block->GetInlinedFunctionInfo();
1624 variable_list_sp = inline_block->GetBlockVariableList(true);
1628 if (get_function_vars) {
1630 sc->function->GetBlock(true).GetBlockVariableList(true);
1635 s.PutCString(" [inlined] ");
1637 inline_info->GetName(sc->function->GetLanguage()).GetCString();
1641 if (variable_list_sp)
1642 variable_list_sp->AppendVariablesWithScope(
1643 eValueTypeVariableArgument, args);
1644 if (args.GetSize() > 0) {
1645 const char *open_paren = strchr(cstr, '(');
1646 const char *close_paren = nullptr;
1647 const char *generic = strchr(cstr, '<');
1648 // if before the arguments list begins there is a template sign
1649 // then scan to the end of the generic args before you try to find
1650 // the arguments list
1651 if (generic && open_paren && generic < open_paren) {
1652 int generic_depth = 1;
1654 for (; *generic && generic_depth > 0; generic++) {
1655 if (*generic == '<')
1657 if (*generic == '>')
1661 open_paren = strchr(generic, '(');
1663 open_paren = nullptr;
1666 if (IsToken(open_paren, "(anonymous namespace)")) {
1668 strchr(open_paren + strlen("(anonymous namespace)"), '(');
1670 close_paren = strchr(open_paren, ')');
1672 close_paren = strchr(open_paren, ')');
1676 s.Write(cstr, open_paren - cstr + 1);
1681 const size_t num_args = args.GetSize();
1682 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx) {
1685 VariableSP var_sp(args.GetVariableAtIndex(arg_idx));
1686 ValueObjectSP var_value_sp(
1687 ValueObjectVariable::Create(exe_scope, var_sp));
1689 llvm::StringRef var_representation;
1690 const char *var_name = var_value_sp->GetName().GetCString();
1691 if (var_value_sp->GetCompilerType().IsValid()) {
1692 if (var_value_sp && exe_scope->CalculateTarget())
1694 var_value_sp->GetQualifiedRepresentationIfAvailable(
1695 exe_scope->CalculateTarget()
1696 ->TargetProperties::GetPreferDynamicValue(),
1697 exe_scope->CalculateTarget()
1698 ->TargetProperties::GetEnableSyntheticValue());
1699 if (var_value_sp->GetCompilerType().IsAggregateType() &&
1700 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp)) {
1701 static StringSummaryFormat format(
1702 TypeSummaryImpl::Flags()
1703 .SetHideItemNames(false)
1704 .SetShowMembersOneLiner(true),
1706 format.FormatObject(var_value_sp.get(), buffer,
1707 TypeSummaryOptions());
1708 var_representation = buffer;
1710 var_value_sp->DumpPrintableRepresentation(
1712 ValueObject::ValueObjectRepresentationStyle::
1713 eValueObjectRepresentationStyleSummary,
1715 ValueObject::PrintableRepresentationSpecialCases::eAllow,
1719 if (!ss.GetString().empty())
1720 var_representation = ss.GetString();
1723 if (var_value_sp->GetError().Success()) {
1724 if (!var_representation.empty())
1725 s.Printf("%s=%s", var_name, var_representation.str().c_str());
1727 s.Printf("%s=%s at %s", var_name,
1728 var_value_sp->GetTypeName().GetCString(),
1729 var_value_sp->GetLocationAsCString());
1731 s.Printf("%s=<unavailable>", var_name);
1735 s.PutCString(close_paren);
1744 } else if (sc->symbol) {
1745 const char *cstr = sc->symbol->GetName().AsCString(nullptr);
1755 case Entry::Type::FunctionAddrOffset:
1757 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, false, false,
1763 case Entry::Type::FunctionAddrOffsetConcrete:
1765 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, true, true,
1771 case Entry::Type::FunctionLineOffset:
1772 return (DumpAddressOffsetFromFunction(s, sc, exe_ctx,
1773 sc->line_entry.range.GetBaseAddress(),
1774 false, false, false));
1776 case Entry::Type::FunctionPCOffset:
1778 StackFrame *frame = exe_ctx->GetFramePtr();
1780 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx,
1781 frame->GetFrameCodeAddress(), false,
1788 case Entry::Type::FunctionChanged:
1789 return function_changed;
1791 case Entry::Type::FunctionIsOptimized: {
1792 bool is_optimized = false;
1793 if (sc->function && sc->function->GetIsOptimized()) {
1794 is_optimized = true;
1796 return is_optimized;
1799 case Entry::Type::FunctionInitial:
1800 return initial_function;
1802 case Entry::Type::LineEntryFile:
1803 if (sc && sc->line_entry.IsValid()) {
1804 Module *module = sc->module_sp.get();
1806 if (DumpFile(s, sc->line_entry.file, (FileKind)entry.number))
1812 case Entry::Type::LineEntryLineNumber:
1813 if (sc && sc->line_entry.IsValid()) {
1814 const char *format = "%" PRIu32;
1815 if (!entry.printf_format.empty())
1816 format = entry.printf_format.c_str();
1817 s.Printf(format, sc->line_entry.line);
1822 case Entry::Type::LineEntryColumn:
1823 if (sc && sc->line_entry.IsValid() && sc->line_entry.column) {
1824 const char *format = "%" PRIu32;
1825 if (!entry.printf_format.empty())
1826 format = entry.printf_format.c_str();
1827 s.Printf(format, sc->line_entry.column);
1832 case Entry::Type::LineEntryStartAddress:
1833 case Entry::Type::LineEntryEndAddress:
1834 if (sc && sc->line_entry.range.GetBaseAddress().IsValid()) {
1835 Address addr = sc->line_entry.range.GetBaseAddress();
1837 if (entry.type == Entry::Type::LineEntryEndAddress)
1838 addr.Slide(sc->line_entry.range.GetByteSize());
1839 if (DumpAddress(s, sc, exe_ctx, addr, false))
1844 case Entry::Type::CurrentPCArrow:
1845 if (addr && exe_ctx && exe_ctx->GetFramePtr()) {
1846 RegisterContextSP reg_ctx =
1847 exe_ctx->GetFramePtr()->GetRegisterContextSP();
1849 addr_t pc_loadaddr = reg_ctx->GetPC();
1850 if (pc_loadaddr != LLDB_INVALID_ADDRESS) {
1852 pc.SetLoadAddress(pc_loadaddr, exe_ctx->GetTargetPtr());
1867 static bool DumpCommaSeparatedChildEntryNames(
1868 Stream &s, const FormatEntity::Entry::Definition *parent) {
1869 if (parent->children) {
1870 const size_t n = parent->num_children;
1871 for (size_t i = 0; i < n; ++i) {
1874 s.Printf("\"%s\"", parent->children[i].name);
1881 static Status ParseEntry(const llvm::StringRef &format_str,
1882 const FormatEntity::Entry::Definition *parent,
1883 FormatEntity::Entry &entry) {
1886 const size_t sep_pos = format_str.find_first_of(".[:");
1887 const char sep_char =
1888 (sep_pos == llvm::StringRef::npos) ? '\0' : format_str[sep_pos];
1889 llvm::StringRef key = format_str.substr(0, sep_pos);
1891 const size_t n = parent->num_children;
1892 for (size_t i = 0; i < n; ++i) {
1893 const FormatEntity::Entry::Definition *entry_def = parent->children + i;
1894 if (key.equals(entry_def->name) || entry_def->name[0] == '*') {
1895 llvm::StringRef value;
1898 format_str.substr(sep_pos + (entry_def->keep_separator ? 0 : 1));
1899 switch (entry_def->type) {
1900 case FormatEntity::Entry::Type::ParentString:
1901 entry.string = format_str.str();
1902 return error; // Success
1904 case FormatEntity::Entry::Type::ParentNumber:
1905 entry.number = entry_def->data;
1906 return error; // Success
1908 case FormatEntity::Entry::Type::EscapeCode:
1909 entry.type = entry_def->type;
1910 entry.string = entry_def->string;
1911 return error; // Success
1914 entry.type = entry_def->type;
1918 if (value.empty()) {
1919 if (entry_def->type == FormatEntity::Entry::Type::Invalid) {
1920 if (entry_def->children) {
1921 StreamString error_strm;
1922 error_strm.Printf("'%s' can't be specified on its own, you must "
1923 "access one of its children: ",
1925 DumpCommaSeparatedChildEntryNames(error_strm, entry_def);
1926 error.SetErrorStringWithFormat("%s", error_strm.GetData());
1927 } else if (sep_char == ':') {
1928 // Any value whose separator is a with a ':' means this value has a
1929 // string argument that needs to be stored in the entry (like
1930 // "${script.var:}"). In this case the string value is the empty
1931 // string which is ok.
1933 error.SetErrorStringWithFormat("%s", "invalid entry definitions");
1937 if (entry_def->children) {
1938 error = ParseEntry(value, entry_def, entry);
1939 } else if (sep_char == ':') {
1940 // Any value whose separator is a with a ':' means this value has a
1941 // string argument that needs to be stored in the entry (like
1942 // "${script.var:modulename.function}")
1943 entry.string = value.str();
1945 error.SetErrorStringWithFormat(
1946 "'%s' followed by '%s' but it has no children", key.str().c_str(),
1947 value.str().c_str());
1953 StreamString error_strm;
1954 if (parent->type == FormatEntity::Entry::Type::Root)
1956 "invalid top level item '%s'. Valid top level items are: ",
1959 error_strm.Printf("invalid member '%s' in '%s'. Valid members are: ",
1960 key.str().c_str(), parent->name);
1961 DumpCommaSeparatedChildEntryNames(error_strm, parent);
1962 error.SetErrorStringWithFormat("%s", error_strm.GetData());
1966 static const FormatEntity::Entry::Definition *
1967 FindEntry(const llvm::StringRef &format_str,
1968 const FormatEntity::Entry::Definition *parent,
1969 llvm::StringRef &remainder) {
1972 std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.');
1973 const size_t n = parent->num_children;
1974 for (size_t i = 0; i < n; ++i) {
1975 const FormatEntity::Entry::Definition *entry_def = parent->children + i;
1976 if (p.first.equals(entry_def->name) || entry_def->name[0] == '*') {
1977 if (p.second.empty()) {
1978 if (format_str.back() == '.')
1979 remainder = format_str.drop_front(format_str.size() - 1);
1981 remainder = llvm::StringRef(); // Exact match
1984 if (entry_def->children) {
1985 return FindEntry(p.second, entry_def, remainder);
1987 remainder = p.second;
1993 remainder = format_str;
1997 Status FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry,
2000 while (!format.empty() && error.Success()) {
2001 const size_t non_special_chars = format.find_first_of("${}\\");
2003 if (non_special_chars == llvm::StringRef::npos) {
2004 // No special characters, just string bytes so add them and we are done
2005 parent_entry.AppendText(format);
2009 if (non_special_chars > 0) {
2010 // We have a special character, so add all characters before these as a
2012 parent_entry.AppendText(format.substr(0, non_special_chars));
2013 format = format.drop_front(non_special_chars);
2016 switch (format[0]) {
2021 format = format.drop_front(); // Skip the '{'
2022 Entry scope_entry(Entry::Type::Scope);
2023 error = FormatEntity::ParseInternal(format, scope_entry, depth + 1);
2026 parent_entry.AppendEntry(std::move(scope_entry));
2031 error.SetErrorString("unmatched '}' character");
2035 .drop_front(); // Skip the '}' as we are at the end of the scope
2039 format = format.drop_front(); // Skip the '\' character
2040 if (format.empty()) {
2041 error.SetErrorString(
2042 "'\\' character was not followed by another character");
2046 const char desens_char = format[0];
2047 format = format.drop_front(); // Skip the desensitized char character
2048 switch (desens_char) {
2050 parent_entry.AppendChar('\a');
2053 parent_entry.AppendChar('\b');
2056 parent_entry.AppendChar('\f');
2059 parent_entry.AppendChar('\n');
2062 parent_entry.AppendChar('\r');
2065 parent_entry.AppendChar('\t');
2068 parent_entry.AppendChar('\v');
2071 parent_entry.AppendChar('\'');
2074 parent_entry.AppendChar('\\');
2077 // 1 to 3 octal chars
2079 // Make a string that can hold onto the initial zero char, up to 3
2080 // octal digits, and a terminating NULL.
2081 char oct_str[5] = {0, 0, 0, 0, 0};
2084 for (i = 0; (format[i] >= '0' && format[i] <= '7') && i < 4; ++i)
2085 oct_str[i] = format[i];
2087 // We don't want to consume the last octal character since the main
2088 // for loop will do this for us, so we advance p by one less than i
2089 // (even if i is zero)
2090 format = format.drop_front(i);
2091 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
2092 if (octal_value <= UINT8_MAX) {
2093 parent_entry.AppendChar((char)octal_value);
2095 error.SetErrorString("octal number is larger than a single byte");
2102 // hex number in the format
2103 if (isxdigit(format[0])) {
2104 // Make a string that can hold onto two hex chars plus a
2106 char hex_str[3] = {0, 0, 0};
2107 hex_str[0] = format[0];
2109 format = format.drop_front();
2111 if (isxdigit(format[0])) {
2112 hex_str[1] = format[0];
2113 format = format.drop_front();
2116 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
2117 if (hex_value <= UINT8_MAX) {
2118 parent_entry.AppendChar((char)hex_value);
2120 error.SetErrorString("hex number is larger than a single byte");
2124 parent_entry.AppendChar(desens_char);
2129 // Just desensitize any other character by just printing what came
2131 parent_entry.AppendChar(desens_char);
2137 if (format.size() == 1) {
2138 // '$' at the end of a format string, just print the '$'
2139 parent_entry.AppendText("$");
2141 format = format.drop_front(); // Skip the '$'
2143 if (format[0] == '{') {
2144 format = format.drop_front(); // Skip the '{'
2146 llvm::StringRef variable, variable_format;
2147 error = FormatEntity::ExtractVariableInfo(format, variable,
2151 bool verify_is_thread_id = false;
2153 if (!variable_format.empty()) {
2154 entry.printf_format = variable_format.str();
2156 // If the format contains a '%' we are going to assume this is a
2157 // printf style format. So if you want to format your thread ID
2158 // using "0x%llx" you can use: ${thread.id%0x%llx}
2160 // If there is no '%' in the format, then it is assumed to be a
2161 // LLDB format name, or one of the extended formats specified in
2162 // the switch statement below.
2164 if (entry.printf_format.find('%') == std::string::npos) {
2165 bool clear_printf = false;
2167 if (FormatManager::GetFormatFromCString(
2168 entry.printf_format.c_str(), false, entry.fmt)) {
2169 // We have an LLDB format, so clear the printf format
2170 clear_printf = true;
2171 } else if (entry.printf_format.size() == 1) {
2172 switch (entry.printf_format[0]) {
2173 case '@': // if this is an @ sign, print ObjC description
2174 entry.number = ValueObject::
2175 eValueObjectRepresentationStyleLanguageSpecific;
2176 clear_printf = true;
2178 case 'V': // if this is a V, print the value using the default
2181 ValueObject::eValueObjectRepresentationStyleValue;
2182 clear_printf = true;
2184 case 'L': // if this is an L, print the location of the value
2186 ValueObject::eValueObjectRepresentationStyleLocation;
2187 clear_printf = true;
2189 case 'S': // if this is an S, print the summary after all
2191 ValueObject::eValueObjectRepresentationStyleSummary;
2192 clear_printf = true;
2194 case '#': // if this is a '#', print the number of children
2196 ValueObject::eValueObjectRepresentationStyleChildrenCount;
2197 clear_printf = true;
2199 case 'T': // if this is a 'T', print the type
2201 ValueObject::eValueObjectRepresentationStyleType;
2202 clear_printf = true;
2204 case 'N': // if this is a 'N', print the name
2206 ValueObject::eValueObjectRepresentationStyleName;
2207 clear_printf = true;
2209 case '>': // if this is a '>', print the expression path
2210 entry.number = ValueObject::
2211 eValueObjectRepresentationStyleExpressionPath;
2212 clear_printf = true;
2215 error.SetErrorStringWithFormat("invalid format: '%s'",
2216 entry.printf_format.c_str());
2219 } else if (FormatManager::GetFormatFromCString(
2220 entry.printf_format.c_str(), true, entry.fmt)) {
2221 clear_printf = true;
2222 } else if (entry.printf_format == "tid") {
2223 verify_is_thread_id = true;
2225 error.SetErrorStringWithFormat("invalid format: '%s'",
2226 entry.printf_format.c_str());
2230 // Our format string turned out to not be a printf style format
2231 // so lets clear the string
2233 entry.printf_format.clear();
2237 // Check for dereferences
2238 if (variable[0] == '*') {
2240 variable = variable.drop_front();
2243 error = ParseEntry(variable, &g_root, entry);
2247 if (verify_is_thread_id) {
2248 if (entry.type != Entry::Type::ThreadID &&
2249 entry.type != Entry::Type::ThreadProtocolID) {
2250 error.SetErrorString("the 'tid' format can only be used on "
2251 "${thread.id} and ${thread.protocol_id}");
2255 switch (entry.type) {
2256 case Entry::Type::Variable:
2257 case Entry::Type::VariableSynthetic:
2258 if (entry.number == 0) {
2259 if (entry.string.empty())
2261 ValueObject::eValueObjectRepresentationStyleValue;
2264 ValueObject::eValueObjectRepresentationStyleSummary;
2268 // Make sure someone didn't try to dereference anything but ${var}
2271 error.SetErrorStringWithFormat(
2272 "${%s} can't be dereferenced, only ${var} and ${svar} can.",
2273 variable.str().c_str());
2277 parent_entry.AppendEntry(std::move(entry));
2286 Status FormatEntity::ExtractVariableInfo(llvm::StringRef &format_str,
2287 llvm::StringRef &variable_name,
2288 llvm::StringRef &variable_format) {
2290 variable_name = llvm::StringRef();
2291 variable_format = llvm::StringRef();
2293 const size_t paren_pos = format_str.find('}');
2294 if (paren_pos != llvm::StringRef::npos) {
2295 const size_t percent_pos = format_str.find('%');
2296 if (percent_pos < paren_pos) {
2297 if (percent_pos > 0) {
2298 if (percent_pos > 1)
2299 variable_name = format_str.substr(0, percent_pos);
2301 format_str.substr(percent_pos + 1, paren_pos - (percent_pos + 1));
2304 variable_name = format_str.substr(0, paren_pos);
2306 // Strip off elements and the formatting and the trailing '}'
2307 format_str = format_str.substr(paren_pos + 1);
2309 error.SetErrorStringWithFormat(
2310 "missing terminating '}' character for '${%s'",
2311 format_str.str().c_str());
2316 bool FormatEntity::FormatFileSpec(const FileSpec &file_spec, Stream &s,
2317 llvm::StringRef variable_name,
2318 llvm::StringRef variable_format) {
2319 if (variable_name.empty() || variable_name.equals(".fullpath")) {
2322 } else if (variable_name.equals(".basename")) {
2323 s.PutCString(file_spec.GetFilename().AsCString(""));
2325 } else if (variable_name.equals(".dirname")) {
2326 s.PutCString(file_spec.GetFilename().AsCString(""));
2332 static std::string MakeMatch(const llvm::StringRef &prefix,
2333 const char *suffix) {
2334 std::string match(prefix.str());
2335 match.append(suffix);
2339 static void AddMatches(const FormatEntity::Entry::Definition *def,
2340 const llvm::StringRef &prefix,
2341 const llvm::StringRef &match_prefix,
2342 StringList &matches) {
2343 const size_t n = def->num_children;
2345 for (size_t i = 0; i < n; ++i) {
2346 std::string match = prefix.str();
2347 if (match_prefix.empty())
2348 matches.AppendString(MakeMatch(prefix, def->children[i].name));
2349 else if (strncmp(def->children[i].name, match_prefix.data(),
2350 match_prefix.size()) == 0)
2351 matches.AppendString(
2352 MakeMatch(prefix, def->children[i].name + match_prefix.size()));
2357 size_t FormatEntity::AutoComplete(CompletionRequest &request) {
2358 llvm::StringRef str = request.GetCursorArgumentPrefix().str();
2360 request.SetWordComplete(false);
2361 str = str.drop_front(request.GetMatchStartPoint());
2363 const size_t dollar_pos = str.rfind('$');
2364 if (dollar_pos == llvm::StringRef::npos)
2367 // Hitting TAB after $ at the end of the string add a "{"
2368 if (dollar_pos == str.size() - 1) {
2369 std::string match = str.str();
2371 request.AddCompletion(match);
2375 if (str[dollar_pos + 1] != '{')
2378 const size_t close_pos = str.find('}', dollar_pos + 2);
2379 if (close_pos != llvm::StringRef::npos)
2382 const size_t format_pos = str.find('%', dollar_pos + 2);
2383 if (format_pos != llvm::StringRef::npos)
2386 llvm::StringRef partial_variable(str.substr(dollar_pos + 2));
2387 if (partial_variable.empty()) {
2388 // Suggest all top level entites as we are just past "${"
2389 StringList new_matches;
2390 AddMatches(&g_root, str, llvm::StringRef(), new_matches);
2391 request.AddCompletions(new_matches);
2392 return request.GetNumberOfMatches();
2395 // We have a partially specified variable, find it
2396 llvm::StringRef remainder;
2397 const FormatEntity::Entry::Definition *entry_def =
2398 FindEntry(partial_variable, &g_root, remainder);
2402 const size_t n = entry_def->num_children;
2404 if (remainder.empty()) {
2407 // "${thread.info" <TAB>
2408 request.AddCompletion(MakeMatch(str, "."));
2410 // "${thread.id" <TAB>
2411 request.AddCompletion(MakeMatch(str, "}"));
2412 request.SetWordComplete(true);
2414 } else if (remainder.equals(".")) {
2415 // "${thread." <TAB>
2416 StringList new_matches;
2417 AddMatches(entry_def, str, llvm::StringRef(), new_matches);
2418 request.AddCompletions(new_matches);
2420 // We have a partial match
2422 StringList new_matches;
2423 AddMatches(entry_def, str, remainder, new_matches);
2424 request.AddCompletions(new_matches);
2426 return request.GetNumberOfMatches();