Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Core/FormatEntity.cpp
Warning:line 962, column 20
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name FormatEntity.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Core -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Core -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Core/FormatEntity.cpp
1//===-- FormatEntity.cpp --------------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Core/FormatEntity.h"
10
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/CompletionRequest.h"
45#include "lldb/Utility/ConstString.h"
46#include "lldb/Utility/FileSpec.h"
47#include "lldb/Utility/LLDBLog.h"
48#include "lldb/Utility/Log.h"
49#include "lldb/Utility/RegisterValue.h"
50#include "lldb/Utility/Status.h"
51#include "lldb/Utility/Stream.h"
52#include "lldb/Utility/StreamString.h"
53#include "lldb/Utility/StringList.h"
54#include "lldb/Utility/StructuredData.h"
55#include "lldb/lldb-defines.h"
56#include "lldb/lldb-forward.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/Triple.h"
60#include "llvm/Support/Compiler.h"
61
62#include <cctype>
63#include <cinttypes>
64#include <cstdio>
65#include <cstdlib>
66#include <cstring>
67#include <memory>
68#include <type_traits>
69#include <utility>
70
71namespace lldb_private {
72class ScriptInterpreter;
73}
74namespace lldb_private {
75struct RegisterInfo;
76}
77
78using namespace lldb;
79using namespace lldb_private;
80
81using Definition = lldb_private::FormatEntity::Entry::Definition;
82using Entry = FormatEntity::Entry;
83using EntryType = FormatEntity::Entry::Type;
84
85enum FileKind { FileError = 0, Basename, Dirname, Fullpath };
86
87constexpr Definition g_string_entry[] = {
88 Definition("*", EntryType::ParentString)};
89
90constexpr Definition g_addr_entries[] = {
91 Definition("load", EntryType::AddressLoad),
92 Definition("file", EntryType::AddressFile)};
93
94constexpr Definition g_file_child_entries[] = {
95 Definition("basename", EntryType::ParentNumber, FileKind::Basename),
96 Definition("dirname", EntryType::ParentNumber, FileKind::Dirname),
97 Definition("fullpath", EntryType::ParentNumber, FileKind::Fullpath)};
98
99constexpr Definition g_frame_child_entries[] = {
100 Definition("index", EntryType::FrameIndex),
101 Definition("pc", EntryType::FrameRegisterPC),
102 Definition("fp", EntryType::FrameRegisterFP),
103 Definition("sp", EntryType::FrameRegisterSP),
104 Definition("flags", EntryType::FrameRegisterFlags),
105 Definition("no-debug", EntryType::FrameNoDebug),
106 Entry::DefinitionWithChildren("reg", EntryType::FrameRegisterByName,
107 g_string_entry),
108 Definition("is-artificial", EntryType::FrameIsArtificial),
109};
110
111constexpr Definition g_function_child_entries[] = {
112 Definition("id", EntryType::FunctionID),
113 Definition("name", EntryType::FunctionName),
114 Definition("name-without-args", EntryType::FunctionNameNoArgs),
115 Definition("name-with-args", EntryType::FunctionNameWithArgs),
116 Definition("mangled-name", EntryType::FunctionMangledName),
117 Definition("addr-offset", EntryType::FunctionAddrOffset),
118 Definition("concrete-only-addr-offset-no-padding",
119 EntryType::FunctionAddrOffsetConcrete),
120 Definition("line-offset", EntryType::FunctionLineOffset),
121 Definition("pc-offset", EntryType::FunctionPCOffset),
122 Definition("initial-function", EntryType::FunctionInitial),
123 Definition("changed", EntryType::FunctionChanged),
124 Definition("is-optimized", EntryType::FunctionIsOptimized)};
125
126constexpr Definition g_line_child_entries[] = {
127 Entry::DefinitionWithChildren("file", EntryType::LineEntryFile,
128 g_file_child_entries),
129 Definition("number", EntryType::LineEntryLineNumber),
130 Definition("column", EntryType::LineEntryColumn),
131 Definition("start-addr", EntryType::LineEntryStartAddress),
132 Definition("end-addr", EntryType::LineEntryEndAddress),
133};
134
135constexpr Definition g_module_child_entries[] = {Entry::DefinitionWithChildren(
136 "file", EntryType::ModuleFile, g_file_child_entries)};
137
138constexpr Definition g_process_child_entries[] = {
139 Definition("id", EntryType::ProcessID),
140 Definition("name", EntryType::ProcessFile, FileKind::Basename),
141 Entry::DefinitionWithChildren("file", EntryType::ProcessFile,
142 g_file_child_entries)};
143
144constexpr Definition g_svar_child_entries[] = {
145 Definition("*", EntryType::ParentString)};
146
147constexpr Definition g_var_child_entries[] = {
148 Definition("*", EntryType::ParentString)};
149
150constexpr Definition g_thread_child_entries[] = {
151 Definition("id", EntryType::ThreadID),
152 Definition("protocol_id", EntryType::ThreadProtocolID),
153 Definition("index", EntryType::ThreadIndexID),
154 Entry::DefinitionWithChildren("info", EntryType::ThreadInfo,
155 g_string_entry),
156 Definition("queue", EntryType::ThreadQueue),
157 Definition("name", EntryType::ThreadName),
158 Definition("stop-reason", EntryType::ThreadStopReason),
159 Definition("stop-reason-raw", EntryType::ThreadStopReasonRaw),
160 Definition("return-value", EntryType::ThreadReturnValue),
161 Definition("completed-expression", EntryType::ThreadCompletedExpression)};
162
163constexpr Definition g_target_child_entries[] = {
164 Definition("arch", EntryType::TargetArch)};
165
166#define _TO_STR2(_val)"_val" #_val
167#define _TO_STR(_val)"_val" _TO_STR2(_val)"_val"
168
169constexpr Definition g_ansi_fg_entries[] = {
170 Definition("black",
171 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_BLACK)"30" ANSI_ESC_END"m"),
172 Definition("red", ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_RED)"31" ANSI_ESC_END"m"),
173 Definition("green",
174 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_GREEN)"32" ANSI_ESC_END"m"),
175 Definition("yellow",
176 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_YELLOW)"33" ANSI_ESC_END"m"),
177 Definition("blue", ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_BLUE)"34" ANSI_ESC_END"m"),
178 Definition("purple",
179 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_PURPLE)"35" ANSI_ESC_END"m"),
180 Definition("cyan", ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_CYAN)"36" ANSI_ESC_END"m"),
181 Definition("white",
182 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_WHITE)"37" ANSI_ESC_END"m"),
183};
184
185constexpr Definition g_ansi_bg_entries[] = {
186 Definition("black",
187 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_BLACK)"40" ANSI_ESC_END"m"),
188 Definition("red", ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_RED)"41" ANSI_ESC_END"m"),
189 Definition("green",
190 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_GREEN)"42" ANSI_ESC_END"m"),
191 Definition("yellow",
192 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_YELLOW)"43" ANSI_ESC_END"m"),
193 Definition("blue", ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_BLUE)"44" ANSI_ESC_END"m"),
194 Definition("purple",
195 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_PURPLE)"45" ANSI_ESC_END"m"),
196 Definition("cyan", ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_CYAN)"46" ANSI_ESC_END"m"),
197 Definition("white",
198 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_WHITE)"47" ANSI_ESC_END"m"),
199};
200
201constexpr Definition g_ansi_entries[] = {
202 Entry::DefinitionWithChildren("fg", EntryType::Invalid, g_ansi_fg_entries),
203 Entry::DefinitionWithChildren("bg", EntryType::Invalid, g_ansi_bg_entries),
204 Definition("normal", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_NORMAL)"0" ANSI_ESC_END"m"),
205 Definition("bold", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_BOLD)"1" ANSI_ESC_END"m"),
206 Definition("faint", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_FAINT)"2" ANSI_ESC_END"m"),
207 Definition("italic", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_ITALIC)"3" ANSI_ESC_END"m"),
208 Definition("underline",
209 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_UNDERLINE)"4" ANSI_ESC_END"m"),
210 Definition("slow-blink",
211 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_SLOW_BLINK)"5" ANSI_ESC_END"m"),
212 Definition("fast-blink",
213 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_FAST_BLINK)"6" ANSI_ESC_END"m"),
214 Definition("negative",
215 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_IMAGE_NEGATIVE)"7" ANSI_ESC_END"m"),
216 Definition("conceal",
217 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_CONCEAL)"8" ANSI_ESC_END"m"),
218 Definition("crossed-out",
219 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_CROSSED_OUT)"9" ANSI_ESC_END"m"),
220};
221
222constexpr Definition g_script_child_entries[] = {
223 Definition("frame", EntryType::ScriptFrame),
224 Definition("process", EntryType::ScriptProcess),
225 Definition("target", EntryType::ScriptTarget),
226 Definition("thread", EntryType::ScriptThread),
227 Definition("var", EntryType::ScriptVariable),
228 Definition("svar", EntryType::ScriptVariableSynthetic),
229 Definition("thread", EntryType::ScriptThread)};
230
231constexpr Definition g_top_level_entries[] = {
232 Entry::DefinitionWithChildren("addr", EntryType::AddressLoadOrFile,
233 g_addr_entries),
234 Definition("addr-file-or-load", EntryType::AddressLoadOrFile),
235 Entry::DefinitionWithChildren("ansi", EntryType::Invalid, g_ansi_entries),
236 Definition("current-pc-arrow", EntryType::CurrentPCArrow),
237 Entry::DefinitionWithChildren("file", EntryType::File,
238 g_file_child_entries),
239 Definition("language", EntryType::Lang),
240 Entry::DefinitionWithChildren("frame", EntryType::Invalid,
241 g_frame_child_entries),
242 Entry::DefinitionWithChildren("function", EntryType::Invalid,
243 g_function_child_entries),
244 Entry::DefinitionWithChildren("line", EntryType::Invalid,
245 g_line_child_entries),
246 Entry::DefinitionWithChildren("module", EntryType::Invalid,
247 g_module_child_entries),
248 Entry::DefinitionWithChildren("process", EntryType::Invalid,
249 g_process_child_entries),
250 Entry::DefinitionWithChildren("script", EntryType::Invalid,
251 g_script_child_entries),
252 Entry::DefinitionWithChildren("svar", EntryType::VariableSynthetic,
253 g_svar_child_entries, true),
254 Entry::DefinitionWithChildren("thread", EntryType::Invalid,
255 g_thread_child_entries),
256 Entry::DefinitionWithChildren("target", EntryType::Invalid,
257 g_target_child_entries),
258 Entry::DefinitionWithChildren("var", EntryType::Variable,
259 g_var_child_entries, true)};
260
261constexpr Definition g_root = Entry::DefinitionWithChildren(
262 "<root>", EntryType::Root, g_top_level_entries);
263
264FormatEntity::Entry::Entry(llvm::StringRef s)
265 : string(s.data(), s.size()), printf_format(), children(),
266 type(Type::String) {}
267
268FormatEntity::Entry::Entry(char ch)
269 : string(1, ch), printf_format(), children(), type(Type::String) {}
270
271void FormatEntity::Entry::AppendChar(char ch) {
272 if (children.empty() || children.back().type != Entry::Type::String)
273 children.push_back(Entry(ch));
274 else
275 children.back().string.append(1, ch);
276}
277
278void FormatEntity::Entry::AppendText(const llvm::StringRef &s) {
279 if (children.empty() || children.back().type != Entry::Type::String)
280 children.push_back(Entry(s));
281 else
282 children.back().string.append(s.data(), s.size());
283}
284
285void FormatEntity::Entry::AppendText(const char *cstr) {
286 return AppendText(llvm::StringRef(cstr));
287}
288
289Status FormatEntity::Parse(const llvm::StringRef &format_str, Entry &entry) {
290 entry.Clear();
291 entry.type = Entry::Type::Root;
292 llvm::StringRef modifiable_format(format_str);
293 return ParseInternal(modifiable_format, entry, 0);
294}
295
296#define ENUM_TO_CSTR(eee) \
297 case FormatEntity::Entry::Type::eee: \
298 return #eee
299
300const char *FormatEntity::Entry::TypeToCString(Type t) {
301 switch (t) {
302 ENUM_TO_CSTR(Invalid);
303 ENUM_TO_CSTR(ParentNumber);
304 ENUM_TO_CSTR(ParentString);
305 ENUM_TO_CSTR(EscapeCode);
306 ENUM_TO_CSTR(Root);
307 ENUM_TO_CSTR(String);
308 ENUM_TO_CSTR(Scope);
309 ENUM_TO_CSTR(Variable);
310 ENUM_TO_CSTR(VariableSynthetic);
311 ENUM_TO_CSTR(ScriptVariable);
312 ENUM_TO_CSTR(ScriptVariableSynthetic);
313 ENUM_TO_CSTR(AddressLoad);
314 ENUM_TO_CSTR(AddressFile);
315 ENUM_TO_CSTR(AddressLoadOrFile);
316 ENUM_TO_CSTR(ProcessID);
317 ENUM_TO_CSTR(ProcessFile);
318 ENUM_TO_CSTR(ScriptProcess);
319 ENUM_TO_CSTR(ThreadID);
320 ENUM_TO_CSTR(ThreadProtocolID);
321 ENUM_TO_CSTR(ThreadIndexID);
322 ENUM_TO_CSTR(ThreadName);
323 ENUM_TO_CSTR(ThreadQueue);
324 ENUM_TO_CSTR(ThreadStopReason);
325 ENUM_TO_CSTR(ThreadStopReasonRaw);
326 ENUM_TO_CSTR(ThreadReturnValue);
327 ENUM_TO_CSTR(ThreadCompletedExpression);
328 ENUM_TO_CSTR(ScriptThread);
329 ENUM_TO_CSTR(ThreadInfo);
330 ENUM_TO_CSTR(TargetArch);
331 ENUM_TO_CSTR(ScriptTarget);
332 ENUM_TO_CSTR(ModuleFile);
333 ENUM_TO_CSTR(File);
334 ENUM_TO_CSTR(Lang);
335 ENUM_TO_CSTR(FrameIndex);
336 ENUM_TO_CSTR(FrameNoDebug);
337 ENUM_TO_CSTR(FrameRegisterPC);
338 ENUM_TO_CSTR(FrameRegisterSP);
339 ENUM_TO_CSTR(FrameRegisterFP);
340 ENUM_TO_CSTR(FrameRegisterFlags);
341 ENUM_TO_CSTR(FrameRegisterByName);
342 ENUM_TO_CSTR(FrameIsArtificial);
343 ENUM_TO_CSTR(ScriptFrame);
344 ENUM_TO_CSTR(FunctionID);
345 ENUM_TO_CSTR(FunctionDidChange);
346 ENUM_TO_CSTR(FunctionInitialFunction);
347 ENUM_TO_CSTR(FunctionName);
348 ENUM_TO_CSTR(FunctionNameWithArgs);
349 ENUM_TO_CSTR(FunctionNameNoArgs);
350 ENUM_TO_CSTR(FunctionMangledName);
351 ENUM_TO_CSTR(FunctionAddrOffset);
352 ENUM_TO_CSTR(FunctionAddrOffsetConcrete);
353 ENUM_TO_CSTR(FunctionLineOffset);
354 ENUM_TO_CSTR(FunctionPCOffset);
355 ENUM_TO_CSTR(FunctionInitial);
356 ENUM_TO_CSTR(FunctionChanged);
357 ENUM_TO_CSTR(FunctionIsOptimized);
358 ENUM_TO_CSTR(LineEntryFile);
359 ENUM_TO_CSTR(LineEntryLineNumber);
360 ENUM_TO_CSTR(LineEntryColumn);
361 ENUM_TO_CSTR(LineEntryStartAddress);
362 ENUM_TO_CSTR(LineEntryEndAddress);
363 ENUM_TO_CSTR(CurrentPCArrow);
364 }
365 return "???";
366}
367
368#undef ENUM_TO_CSTR
369
370void FormatEntity::Entry::Dump(Stream &s, int depth) const {
371 s.Printf("%*.*s%-20s: ", depth * 2, depth * 2, "", TypeToCString(type));
372 if (fmt != eFormatDefault)
373 s.Printf("lldb-format = %s, ", FormatManager::GetFormatAsCString(fmt));
374 if (!string.empty())
375 s.Printf("string = \"%s\"", string.c_str());
376 if (!printf_format.empty())
377 s.Printf("printf_format = \"%s\"", printf_format.c_str());
378 if (number != 0)
379 s.Printf("number = %" PRIu64"l" "u" " (0x%" PRIx64"l" "x" "), ", number, number);
380 if (deref)
381 s.Printf("deref = true, ");
382 s.EOL();
383 for (const auto &child : children) {
384 child.Dump(s, depth + 1);
385 }
386}
387
388template <typename T>
389static bool RunScriptFormatKeyword(Stream &s, const SymbolContext *sc,
390 const ExecutionContext *exe_ctx, T t,
391 const char *script_function_name) {
392 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
393
394 if (target) {
395 ScriptInterpreter *script_interpreter =
396 target->GetDebugger().GetScriptInterpreter();
397 if (script_interpreter) {
398 Status error;
399 std::string script_output;
400
401 if (script_interpreter->RunScriptFormatKeyword(script_function_name, t,
402 script_output, error) &&
403 error.Success()) {
404 s.Printf("%s", script_output.c_str());
405 return true;
406 } else {
407 s.Printf("<error: %s>", error.AsCString());
408 }
409 }
410 }
411 return false;
412}
413
414static bool DumpAddressAndContent(Stream &s, const SymbolContext *sc,
415 const ExecutionContext *exe_ctx,
416 const Address &addr,
417 bool print_file_addr_or_load_addr) {
418 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
419 addr_t vaddr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
420 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
421 vaddr = addr.GetLoadAddress(target);
422 if (vaddr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
423 vaddr = addr.GetFileAddress();
424
425 if (vaddr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
426 int addr_width = 0;
427 if (exe_ctx && target) {
428 addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
429 }
430 if (addr_width == 0)
431 addr_width = 16;
432 if (print_file_addr_or_load_addr) {
433 ExecutionContextScope *exe_scope = nullptr;
434 if (exe_ctx)
435 exe_scope = exe_ctx->GetBestExecutionContextScope();
436 addr.Dump(&s, exe_scope, Address::DumpStyleLoadAddress,
437 Address::DumpStyleModuleWithFileAddress, 0);
438 } else {
439 s.Printf("0x%*.*" PRIx64"l" "x", addr_width, addr_width, vaddr);
440 }
441 return true;
442 }
443 return false;
444}
445
446static bool DumpAddressOffsetFromFunction(Stream &s, const SymbolContext *sc,
447 const ExecutionContext *exe_ctx,
448 const Address &format_addr,
449 bool concrete_only, bool no_padding,
450 bool print_zero_offsets) {
451 if (format_addr.IsValid()) {
452 Address func_addr;
453
454 if (sc) {
455 if (sc->function) {
456 func_addr = sc->function->GetAddressRange().GetBaseAddress();
457 if (sc->block && !concrete_only) {
458 // Check to make sure we aren't in an inline function. If we are, use
459 // the inline block range that contains "format_addr" since blocks
460 // can be discontiguous.
461 Block *inline_block = sc->block->GetContainingInlinedBlock();
462 AddressRange inline_range;
463 if (inline_block && inline_block->GetRangeContainingAddress(
464 format_addr, inline_range))
465 func_addr = inline_range.GetBaseAddress();
466 }
467 } else if (sc->symbol && sc->symbol->ValueIsAddress())
468 func_addr = sc->symbol->GetAddressRef();
469 }
470
471 if (func_addr.IsValid()) {
472 const char *addr_offset_padding = no_padding ? "" : " ";
473
474 if (func_addr.GetSection() == format_addr.GetSection()) {
475 addr_t func_file_addr = func_addr.GetFileAddress();
476 addr_t addr_file_addr = format_addr.GetFileAddress();
477 if (addr_file_addr > func_file_addr ||
478 (addr_file_addr == func_file_addr && print_zero_offsets)) {
479 s.Printf("%s+%s%" PRIu64"l" "u", addr_offset_padding, addr_offset_padding,
480 addr_file_addr - func_file_addr);
481 } else if (addr_file_addr < func_file_addr) {
482 s.Printf("%s-%s%" PRIu64"l" "u", addr_offset_padding, addr_offset_padding,
483 func_file_addr - addr_file_addr);
484 }
485 return true;
486 } else {
487 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
488 if (target) {
489 addr_t func_load_addr = func_addr.GetLoadAddress(target);
490 addr_t addr_load_addr = format_addr.GetLoadAddress(target);
491 if (addr_load_addr > func_load_addr ||
492 (addr_load_addr == func_load_addr && print_zero_offsets)) {
493 s.Printf("%s+%s%" PRIu64"l" "u", addr_offset_padding, addr_offset_padding,
494 addr_load_addr - func_load_addr);
495 } else if (addr_load_addr < func_load_addr) {
496 s.Printf("%s-%s%" PRIu64"l" "u", addr_offset_padding, addr_offset_padding,
497 func_load_addr - addr_load_addr);
498 }
499 return true;
500 }
501 }
502 }
503 }
504 return false;
505}
506
507static bool ScanBracketedRange(llvm::StringRef subpath,
508 size_t &close_bracket_index,
509 const char *&var_name_final_if_array_range,
510 int64_t &index_lower, int64_t &index_higher) {
511 Log *log = GetLog(LLDBLog::DataFormatters);
512 close_bracket_index = llvm::StringRef::npos;
513 const size_t open_bracket_index = subpath.find('[');
514 if (open_bracket_index == llvm::StringRef::npos) {
515 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
516 "[ScanBracketedRange] no bracketed range, skipping entirely")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
;
517 return false;
518 }
519
520 close_bracket_index = subpath.find(']', open_bracket_index + 1);
521
522 if (close_bracket_index == llvm::StringRef::npos) {
523 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
524 "[ScanBracketedRange] no bracketed range, skipping entirely")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
;
525 return false;
526 } else {
527 var_name_final_if_array_range = subpath.data() + open_bracket_index;
528
529 if (close_bracket_index - open_bracket_index == 1) {
530 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data"
); } while (0)
531 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data"
); } while (0)
532 "[ScanBracketedRange] '[]' detected.. going from 0 to end of data")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data"
); } while (0)
;
533 index_lower = 0;
534 } else {
535 const size_t separator_index = subpath.find('-', open_bracket_index + 1);
536
537 if (separator_index == llvm::StringRef::npos) {
538 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
539 index_lower = ::strtoul(index_lower_cstr, nullptr, 0);
540 index_higher = index_lower;
541 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "] detected, high index is same"
, index_lower); } while (0)
542 "[ScanBracketedRange] [%" PRId64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "] detected, high index is same"
, index_lower); } while (0)
543 "] detected, high index is same",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "] detected, high index is same"
, index_lower); } while (0)
544 index_lower)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "] detected, high index is same"
, index_lower); } while (0)
;
545 } else {
546 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
547 const char *index_higher_cstr = subpath.data() + separator_index + 1;
548 index_lower = ::strtoul(index_lower_cstr, nullptr, 0);
549 index_higher = ::strtoul(index_higher_cstr, nullptr, 0);
550 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "-%"
"l" "d" "] detected", index_lower, index_higher); } while (0
)
551 "[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "-%"
"l" "d" "] detected", index_lower, index_higher); } while (0
)
552 index_lower, index_higher)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "l" "d" "-%"
"l" "d" "] detected", index_lower, index_higher); } while (0
)
;
553 }
554 if (index_lower > index_higher && index_higher > 0) {
555 LLDB_LOGF(log, "[ScanBracketedRange] swapping indices")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] swapping indices"
); } while (0)
;
556 const int64_t temp = index_lower;
557 index_lower = index_higher;
558 index_higher = temp;
559 }
560 }
561 }
562 return true;
563}
564
565static bool DumpFile(Stream &s, const FileSpec &file, FileKind file_kind) {
566 switch (file_kind) {
567 case FileKind::FileError:
568 break;
569
570 case FileKind::Basename:
571 if (file.GetFilename()) {
572 s << file.GetFilename();
573 return true;
574 }
575 break;
576
577 case FileKind::Dirname:
578 if (file.GetDirectory()) {
579 s << file.GetDirectory();
580 return true;
581 }
582 break;
583
584 case FileKind::Fullpath:
585 if (file) {
586 s << file;
587 return true;
588 }
589 break;
590 }
591 return false;
592}
593
594static bool DumpRegister(Stream &s, StackFrame *frame, RegisterKind reg_kind,
595 uint32_t reg_num, Format format) {
596 if (frame) {
597 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
598
599 if (reg_ctx) {
600 const uint32_t lldb_reg_num =
601 reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
602 if (lldb_reg_num != LLDB_INVALID_REGNUM(4294967295U)) {
603 const RegisterInfo *reg_info =
604 reg_ctx->GetRegisterInfoAtIndex(lldb_reg_num);
605 if (reg_info) {
606 RegisterValue reg_value;
607 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
608 DumpRegisterValue(reg_value, &s, reg_info, false, false, format);
609 return true;
610 }
611 }
612 }
613 }
614 }
615 return false;
616}
617
618static ValueObjectSP ExpandIndexedExpression(ValueObject *valobj, size_t index,
619 bool deref_pointer) {
620 Log *log = GetLog(LLDBLog::DataFormatters);
621 const char *ptr_deref_format = "[%d]";
622 std::string ptr_deref_buffer(10, 0);
623 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
624 LLDB_LOGF(log, "[ExpandIndexedExpression] name to deref: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] name to deref: %s"
, ptr_deref_buffer.c_str()); } while (0)
625 ptr_deref_buffer.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] name to deref: %s"
, ptr_deref_buffer.c_str()); } while (0)
;
626 ValueObject::GetValueForExpressionPathOptions options;
627 ValueObject::ExpressionPathEndResultType final_value_type;
628 ValueObject::ExpressionPathScanEndReason reason_to_stop;
629 ValueObject::ExpressionPathAftermath what_next =
630 (deref_pointer ? ValueObject::eExpressionPathAftermathDereference
631 : ValueObject::eExpressionPathAftermathNothing);
632 ValueObjectSP item = valobj->GetValueForExpressionPath(
633 ptr_deref_buffer.c_str(), &reason_to_stop, &final_value_type, options,
634 &what_next);
635 if (!item) {
636 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
637 "[ExpandIndexedExpression] ERROR: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
638 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
639 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
640 } else {
641 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
642 "[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
643 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
644 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
645 }
646 return item;
647}
648
649static char ConvertValueObjectStyleToChar(
650 ValueObject::ValueObjectRepresentationStyle style) {
651 switch (style) {
652 case ValueObject::eValueObjectRepresentationStyleLanguageSpecific:
653 return '@';
654 case ValueObject::eValueObjectRepresentationStyleValue:
655 return 'V';
656 case ValueObject::eValueObjectRepresentationStyleLocation:
657 return 'L';
658 case ValueObject::eValueObjectRepresentationStyleSummary:
659 return 'S';
660 case ValueObject::eValueObjectRepresentationStyleChildrenCount:
661 return '#';
662 case ValueObject::eValueObjectRepresentationStyleType:
663 return 'T';
664 case ValueObject::eValueObjectRepresentationStyleName:
665 return 'N';
666 case ValueObject::eValueObjectRepresentationStyleExpressionPath:
667 return '>';
668 }
669 return '\0';
670}
671
672static bool DumpValue(Stream &s, const SymbolContext *sc,
673 const ExecutionContext *exe_ctx,
674 const FormatEntity::Entry &entry, ValueObject *valobj) {
675 if (valobj == nullptr)
1
Assuming the condition is false
2
Taking false branch
676 return false;
677
678 Log *log = GetLog(LLDBLog::DataFormatters);
679 Format custom_format = eFormatInvalid;
680 ValueObject::ValueObjectRepresentationStyle val_obj_display =
681 entry.string.empty()
3
Assuming the condition is false
4
'?' condition is false
682 ? ValueObject::eValueObjectRepresentationStyleValue
683 : ValueObject::eValueObjectRepresentationStyleSummary;
684
685 bool do_deref_pointer = entry.deref;
686 bool is_script = false;
687 switch (entry.type) {
5
Control jumps to 'case VariableSynthetic:' at line 700
688 case FormatEntity::Entry::Type::ScriptVariable:
689 is_script = true;
690 break;
691
692 case FormatEntity::Entry::Type::Variable:
693 custom_format = entry.fmt;
694 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
695 break;
696
697 case FormatEntity::Entry::Type::ScriptVariableSynthetic:
698 is_script = true;
699 [[fallthrough]];
700 case FormatEntity::Entry::Type::VariableSynthetic:
701 custom_format = entry.fmt;
702 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
703 if (!valobj->IsSynthetic()) {
6
Assuming the condition is false
7
Taking false branch
704 valobj = valobj->GetSyntheticValue().get();
705 if (valobj == nullptr)
706 return false;
707 }
708 break;
709
710 default:
711 return false;
712 }
713
714 ValueObject::ExpressionPathAftermath what_next =
715 (do_deref_pointer ? ValueObject::eExpressionPathAftermathDereference
8
Assuming 'do_deref_pointer' is false
9
'?' condition is false
716 : ValueObject::eExpressionPathAftermathNothing);
717 ValueObject::GetValueForExpressionPathOptions options;
718 options.DontCheckDotVsArrowSyntax()
719 .DoAllowBitfieldSyntax()
720 .DoAllowFragileIVar()
721 .SetSyntheticChildrenTraversal(
722 ValueObject::GetValueForExpressionPathOptions::
723 SyntheticChildrenTraversal::Both);
724 ValueObject *target = nullptr;
725 const char *var_name_final_if_array_range = nullptr;
726 size_t close_bracket_index = llvm::StringRef::npos;
727 int64_t index_lower = -1;
728 int64_t index_higher = -1;
729 bool is_array_range = false;
730 bool was_plain_var = false;
731 bool was_var_format = false;
732 bool was_var_indexed = false;
733 ValueObject::ExpressionPathScanEndReason reason_to_stop =
734 ValueObject::eExpressionPathScanEndReasonEndOfString;
735 ValueObject::ExpressionPathEndResultType final_value_type =
736 ValueObject::eExpressionPathEndResultTypePlain;
737
738 if (is_script
9.1
'is_script' is false
) {
10
Taking false branch
739 return RunScriptFormatKeyword(s, sc, exe_ctx, valobj, entry.string.c_str());
740 }
741
742 llvm::StringRef subpath(entry.string);
743 // simplest case ${var}, just print valobj's value
744 if (entry.string.empty()) {
11
Assuming the condition is false
12
Taking false branch
745 if (entry.printf_format.empty() && entry.fmt == eFormatDefault &&
746 entry.number == ValueObject::eValueObjectRepresentationStyleValue)
747 was_plain_var = true;
748 else
749 was_var_format = true;
750 target = valobj;
751 } else // this is ${var.something} or multiple .something nested
752 {
753 if (entry.string[0] == '[')
13
Assuming the condition is false
14
Taking false branch
754 was_var_indexed = true;
755 ScanBracketedRange(subpath, close_bracket_index,
756 var_name_final_if_array_range, index_lower,
757 index_higher);
758
759 Status error;
760
761 const std::string &expr_path = entry.string;
762
763 LLDB_LOGF(log, "[Debugger::FormatPrompt] symbol to expand: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] symbol to expand: %s"
, expr_path.c_str()); } while (0)
15
Taking false branch
16
Loop condition is false. Exiting loop
764 expr_path.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] symbol to expand: %s"
, expr_path.c_str()); } while (0)
;
765
766 target =
767 valobj
768 ->GetValueForExpressionPath(expr_path.c_str(), &reason_to_stop,
769 &final_value_type, options, &what_next)
770 .get();
771
772 if (!target) {
17
Assuming 'target' is non-null
18
Taking false branch
773 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
774 "[Debugger::FormatPrompt] ERROR: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
775 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
776 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
777 return false;
778 } else {
779 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
19
Taking false branch
20
Loop condition is false. Exiting loop
780 "[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
781 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
782 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
783 target = target
784 ->GetQualifiedRepresentationIfAvailable(
785 target->GetDynamicValueType(), true)
786 .get();
787 }
788 }
789
790 is_array_range =
791 (final_value_type ==
21
Assuming 'final_value_type' is equal to eExpressionPathEndResultTypeBoundedRange
792 ValueObject::eExpressionPathEndResultTypeBoundedRange ||
793 final_value_type ==
794 ValueObject::eExpressionPathEndResultTypeUnboundedRange);
795
796 do_deref_pointer =
797 (what_next == ValueObject::eExpressionPathAftermathDereference);
22
Assuming 'what_next' is not equal to eExpressionPathAftermathDereference
798
799 if (do_deref_pointer
22.1
'do_deref_pointer' is false
&& !is_array_range) {
800 // I have not deref-ed yet, let's do it
801 // this happens when we are not going through
802 // GetValueForVariableExpressionPath to get to the target ValueObject
803 Status error;
804 target = target->Dereference(error).get();
805 if (error.Fail()) {
806 LLDB_LOGF(log, "[Debugger::FormatPrompt] ERROR: %s\n",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: %s\n"
, error.AsCString("unknown")); } while (0)
807 error.AsCString("unknown"))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: %s\n"
, error.AsCString("unknown")); } while (0)
;
808 return false;
809 }
810 do_deref_pointer = false;
811 }
812
813 if (!target) {
23
Assuming 'target' is non-null
814 LLDB_LOGF(log, "[Debugger::FormatPrompt] could not calculate target for "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] could not calculate target for "
"prompt expression"); } while (0)
815 "prompt expression")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] could not calculate target for "
"prompt expression"); } while (0)
;
816 return false;
817 }
818
819 // we do not want to use the summary for a bitfield of type T:n if we were
820 // originally dealing with just a T - that would get us into an endless
821 // recursion
822 if (target->IsBitfield() && was_var_indexed) {
823 // TODO: check for a (T:n)-specific summary - we should still obey that
824 StreamString bitfield_name;
825 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
826 target->GetBitfieldBitSize());
827 auto type_sp = std::make_shared<TypeNameSpecifierImpl>(
828 bitfield_name.GetString(), lldb::eFormatterMatchExact);
829 if (val_obj_display ==
830 ValueObject::eValueObjectRepresentationStyleSummary &&
831 !DataVisualization::GetSummaryForType(type_sp))
832 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
833 }
834
835 // TODO use flags for these
836 const uint32_t type_info_flags =
837 target->GetCompilerType().GetTypeInfo(nullptr);
838 bool is_array = (type_info_flags & eTypeIsArray) != 0;
24
Assuming the condition is true
839 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
25
Assuming the condition is false
840 bool is_aggregate = target->GetCompilerType().IsAggregateType();
841
842 if ((is_array
25.1
'is_array' is true
|| is_pointer) && (!is_array_range
25.2
'is_array_range' is true
) &&
843 val_obj_display ==
844 ValueObject::eValueObjectRepresentationStyleValue) // this should be
845 // wrong, but there
846 // are some
847 // exceptions
848 {
849 StreamString str_temp;
850 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range"
); } while (0)
851 "[Debugger::FormatPrompt] I am into array || pointer && !range")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range"
); } while (0)
;
852
853 if (target->HasSpecialPrintableRepresentation(val_obj_display,
854 custom_format)) {
855 // try to use the special cases
856 bool success = target->DumpPrintableRepresentation(
857 str_temp, val_obj_display, custom_format);
858 LLDB_LOGF(log, "[Debugger::FormatPrompt] special cases did%s match",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special cases did%s match"
, success ? "" : "n't"); } while (0)
859 success ? "" : "n't")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special cases did%s match"
, success ? "" : "n't"); } while (0)
;
860
861 // should not happen
862 if (success)
863 s << str_temp.GetString();
864 return true;
865 } else {
866 if (was_plain_var) // if ${var}
867 {
868 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
869 } else if (is_pointer) // if pointer, value is the address stored
870 {
871 target->DumpPrintableRepresentation(
872 s, val_obj_display, custom_format,
873 ValueObject::PrintableRepresentationSpecialCases::eDisable);
874 }
875 return true;
876 }
877 }
878
879 // if directly trying to print ${var}, and this is an aggregate, display a
880 // nice type @ location message
881 if (is_aggregate && was_plain_var) {
26
Assuming 'is_aggregate' is false
882 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
883 return true;
884 }
885
886 // if directly trying to print ${var%V}, and this is an aggregate, do not let
887 // the user do it
888 if (is_aggregate
26.1
'is_aggregate' is false
&&
889 ((was_var_format &&
890 val_obj_display ==
891 ValueObject::eValueObjectRepresentationStyleValue))) {
892 s << "<invalid use of aggregate type>";
893 return true;
894 }
895
896 if (!is_array_range
26.2
'is_array_range' is true
) {
27
Taking false branch
897 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] dumping ordinary printable output"
); } while (0)
898 "[Debugger::FormatPrompt] dumping ordinary printable output")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] dumping ordinary printable output"
); } while (0)
;
899 return target->DumpPrintableRepresentation(s, val_obj_display,
900 custom_format);
901 } else {
902 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] checking if I can handle as array"
); } while (0)
28
Taking false branch
903 "[Debugger::FormatPrompt] checking if I can handle as array")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] checking if I can handle as array"
); } while (0)
;
904 if (!is_array
29.1
'is_array' is true
&& !is_pointer)
29
Loop condition is false. Exiting loop
905 return false;
906 LLDB_LOGF(log, "[Debugger::FormatPrompt] handle as array")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] handle as array"
); } while (0)
;
30
Taking false branch
31
Loop condition is false. Exiting loop
907 StreamString special_directions_stream;
908 llvm::StringRef special_directions;
909 if (close_bracket_index
31.1
'close_bracket_index' is not equal to 'npos'
!= llvm::StringRef::npos &&
33
Taking false branch
910 subpath.size() > close_bracket_index) {
32
Assuming the condition is false
911 ConstString additional_data(subpath.drop_front(close_bracket_index + 1));
912 special_directions_stream.Printf("${%svar%s", do_deref_pointer ? "*" : "",
913 additional_data.GetCString());
914
915 if (entry.fmt != eFormatDefault) {
916 const char format_char =
917 FormatManager::GetFormatAsFormatChar(entry.fmt);
918 if (format_char != '\0')
919 special_directions_stream.Printf("%%%c", format_char);
920 else {
921 const char *format_cstr =
922 FormatManager::GetFormatAsCString(entry.fmt);
923 special_directions_stream.Printf("%%%s", format_cstr);
924 }
925 } else if (entry.number != 0) {
926 const char style_char = ConvertValueObjectStyleToChar(
927 (ValueObject::ValueObjectRepresentationStyle)entry.number);
928 if (style_char)
929 special_directions_stream.Printf("%%%c", style_char);
930 }
931 special_directions_stream.PutChar('}');
932 special_directions =
933 llvm::StringRef(special_directions_stream.GetString());
934 }
935
936 // let us display items index_lower thru index_higher of this array
937 s.PutChar('[');
938
939 if (index_higher < 0)
34
Assuming 'index_higher' is >= 0
35
Taking false branch
940 index_higher = valobj->GetNumChildren() - 1;
941
942 uint32_t max_num_children =
943 target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
944
945 bool success = true;
946 for (int64_t index = index_lower; index <= index_higher; ++index) {
36
Assuming 'index' is <= 'index_higher'
37
Loop condition is true. Entering loop body
947 ValueObject *item = ExpandIndexedExpression(target, index, false).get();
38
Value assigned to field '_M_ptr'
39
'item' initialized here
948
949 if (!item) {
40
Assuming 'item' is null
41
Taking true branch
950 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "l" "d", index); } while (0)
42
Taking false branch
43
Loop condition is false. Exiting loop
951 "[Debugger::FormatPrompt] ERROR in getting child item at "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "l" "d", index); } while (0)
952 "index %" PRId64,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "l" "d", index); } while (0)
953 index)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "l" "d", index); } while (0)
;
954 } else {
955 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
956 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
957 "[Debugger::FormatPrompt] special_directions for child item: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
958 special_directions.data() ? special_directions.data() : "")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
;
959 }
960
961 if (special_directions.empty()) {
44
Assuming the condition is true
45
Taking true branch
962 success &= item->DumpPrintableRepresentation(s, val_obj_display,
46
Called C++ object pointer is null
963 custom_format);
964 } else {
965 success &= FormatEntity::FormatStringRef(
966 special_directions, s, sc, exe_ctx, nullptr, item, false, false);
967 }
968
969 if (--max_num_children == 0) {
970 s.PutCString(", ...");
971 break;
972 }
973
974 if (index < index_higher)
975 s.PutChar(',');
976 }
977 s.PutChar(']');
978 return success;
979 }
980}
981
982static bool DumpRegister(Stream &s, StackFrame *frame, const char *reg_name,
983 Format format) {
984 if (frame) {
985 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
986
987 if (reg_ctx) {
988 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
989 if (reg_info) {
990 RegisterValue reg_value;
991 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
992 DumpRegisterValue(reg_value, &s, reg_info, false, false, format);
993 return true;
994 }
995 }
996 }
997 }
998 return false;
999}
1000
1001static bool FormatThreadExtendedInfoRecurse(
1002 const FormatEntity::Entry &entry,
1003 const StructuredData::ObjectSP &thread_info_dictionary,
1004 const SymbolContext *sc, const ExecutionContext *exe_ctx, Stream &s) {
1005 llvm::StringRef path(entry.string);
1006
1007 StructuredData::ObjectSP value =
1008 thread_info_dictionary->GetObjectForDotSeparatedPath(path);
1009
1010 if (value) {
1011 if (value->GetType() == eStructuredDataTypeInteger) {
1012 const char *token_format = "0x%4.4" PRIx64"l" "x";
1013 if (!entry.printf_format.empty())
1014 token_format = entry.printf_format.c_str();
1015 s.Printf(token_format, value->GetAsInteger()->GetValue());
1016 return true;
1017 } else if (value->GetType() == eStructuredDataTypeFloat) {
1018 s.Printf("%f", value->GetAsFloat()->GetValue());
1019 return true;
1020 } else if (value->GetType() == eStructuredDataTypeString) {
1021 s.Format("{0}", value->GetAsString()->GetValue());
1022 return true;
1023 } else if (value->GetType() == eStructuredDataTypeArray) {
1024 if (value->GetAsArray()->GetSize() > 0) {
1025 s.Printf("%zu", value->GetAsArray()->GetSize());
1026 return true;
1027 }
1028 } else if (value->GetType() == eStructuredDataTypeDictionary) {
1029 s.Printf("%zu",
1030 value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1031 return true;
1032 }
1033 }
1034
1035 return false;
1036}
1037
1038static inline bool IsToken(const char *var_name_begin, const char *var) {
1039 return (::strncmp(var_name_begin, var, strlen(var)) == 0);
1040}
1041
1042bool FormatEntity::FormatStringRef(const llvm::StringRef &format_str, Stream &s,
1043 const SymbolContext *sc,
1044 const ExecutionContext *exe_ctx,
1045 const Address *addr, ValueObject *valobj,
1046 bool function_changed,
1047 bool initial_function) {
1048 if (!format_str.empty()) {
1049 FormatEntity::Entry root;
1050 Status error = FormatEntity::Parse(format_str, root);
1051 if (error.Success()) {
1052 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj,
1053 function_changed, initial_function);
1054 }
1055 }
1056 return false;
1057}
1058
1059bool FormatEntity::FormatCString(const char *format, Stream &s,
1060 const SymbolContext *sc,
1061 const ExecutionContext *exe_ctx,
1062 const Address *addr, ValueObject *valobj,
1063 bool function_changed, bool initial_function) {
1064 if (format && format[0]) {
1065 FormatEntity::Entry root;
1066 llvm::StringRef format_str(format);
1067 Status error = FormatEntity::Parse(format_str, root);
1068 if (error.Success()) {
1069 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj,
1070 function_changed, initial_function);
1071 }
1072 }
1073 return false;
1074}
1075
1076bool FormatEntity::Format(const Entry &entry, Stream &s,
1077 const SymbolContext *sc,
1078 const ExecutionContext *exe_ctx, const Address *addr,
1079 ValueObject *valobj, bool function_changed,
1080 bool initial_function) {
1081 switch (entry.type) {
1082 case Entry::Type::Invalid:
1083 case Entry::Type::ParentNumber: // Only used for
1084 // FormatEntity::Entry::Definition encoding
1085 case Entry::Type::ParentString: // Only used for
1086 // FormatEntity::Entry::Definition encoding
1087 return false;
1088 case Entry::Type::EscapeCode:
1089 if (exe_ctx) {
1090 if (Target *target = exe_ctx->GetTargetPtr()) {
1091 Debugger &debugger = target->GetDebugger();
1092 if (debugger.GetUseColor()) {
1093 s.PutCString(entry.string);
1094 }
1095 }
1096 }
1097 // Always return true, so colors being disabled is transparent.
1098 return true;
1099
1100 case Entry::Type::Root:
1101 for (const auto &child : entry.children) {
1102 if (!Format(child, s, sc, exe_ctx, addr, valobj, function_changed,
1103 initial_function)) {
1104 return false; // If any item of root fails, then the formatting fails
1105 }
1106 }
1107 return true; // Only return true if all items succeeded
1108
1109 case Entry::Type::String:
1110 s.PutCString(entry.string);
1111 return true;
1112
1113 case Entry::Type::Scope: {
1114 StreamString scope_stream;
1115 bool success = false;
1116 for (const auto &child : entry.children) {
1117 success = Format(child, scope_stream, sc, exe_ctx, addr, valobj,
1118 function_changed, initial_function);
1119 if (!success)
1120 break;
1121 }
1122 // Only if all items in a scope succeed, then do we print the output into
1123 // the main stream
1124 if (success)
1125 s.Write(scope_stream.GetString().data(), scope_stream.GetString().size());
1126 }
1127 return true; // Scopes always successfully print themselves
1128
1129 case Entry::Type::Variable:
1130 case Entry::Type::VariableSynthetic:
1131 case Entry::Type::ScriptVariable:
1132 case Entry::Type::ScriptVariableSynthetic:
1133 return DumpValue(s, sc, exe_ctx, entry, valobj);
1134
1135 case Entry::Type::AddressFile:
1136 case Entry::Type::AddressLoad:
1137 case Entry::Type::AddressLoadOrFile:
1138 return (
1139 addr != nullptr && addr->IsValid() &&
1140 DumpAddressAndContent(s, sc, exe_ctx, *addr,
1141 entry.type == Entry::Type::AddressLoadOrFile));
1142
1143 case Entry::Type::ProcessID:
1144 if (exe_ctx) {
1145 Process *process = exe_ctx->GetProcessPtr();
1146 if (process) {
1147 const char *format = "%" PRIu64"l" "u";
1148 if (!entry.printf_format.empty())
1149 format = entry.printf_format.c_str();
1150 s.Printf(format, process->GetID());
1151 return true;
1152 }
1153 }
1154 return false;
1155
1156 case Entry::Type::ProcessFile:
1157 if (exe_ctx) {
1158 Process *process = exe_ctx->GetProcessPtr();
1159 if (process) {
1160 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1161 if (exe_module) {
1162 if (DumpFile(s, exe_module->GetFileSpec(), (FileKind)entry.number))
1163 return true;
1164 }
1165 }
1166 }
1167 return false;
1168
1169 case Entry::Type::ScriptProcess:
1170 if (exe_ctx) {
1171 Process *process = exe_ctx->GetProcessPtr();
1172 if (process)
1173 return RunScriptFormatKeyword(s, sc, exe_ctx, process,
1174 entry.string.c_str());
1175 }
1176 return false;
1177
1178 case Entry::Type::ThreadID:
1179 if (exe_ctx) {
1180 Thread *thread = exe_ctx->GetThreadPtr();
1181 if (thread) {
1182 const char *format = "0x%4.4" PRIx64"l" "x";
1183 if (!entry.printf_format.empty()) {
1184 // Watch for the special "tid" format...
1185 if (entry.printf_format == "tid") {
1186 // TODO(zturner): Rather than hardcoding this to be platform
1187 // specific, it should be controlled by a setting and the default
1188 // value of the setting can be different depending on the platform.
1189 Target &target = thread->GetProcess()->GetTarget();
1190 ArchSpec arch(target.GetArchitecture());
1191 llvm::Triple::OSType ostype = arch.IsValid()
1192 ? arch.GetTriple().getOS()
1193 : llvm::Triple::UnknownOS;
1194 if ((ostype == llvm::Triple::FreeBSD) ||
1195 (ostype == llvm::Triple::Linux) ||
1196 (ostype == llvm::Triple::NetBSD)) {
1197 format = "%" PRIu64"l" "u";
1198 }
1199 } else {
1200 format = entry.printf_format.c_str();
1201 }
1202 }
1203 s.Printf(format, thread->GetID());
1204 return true;
1205 }
1206 }
1207 return false;
1208
1209 case Entry::Type::ThreadProtocolID:
1210 if (exe_ctx) {
1211 Thread *thread = exe_ctx->GetThreadPtr();
1212 if (thread) {
1213 const char *format = "0x%4.4" PRIx64"l" "x";
1214 if (!entry.printf_format.empty())
1215 format = entry.printf_format.c_str();
1216 s.Printf(format, thread->GetProtocolID());
1217 return true;
1218 }
1219 }
1220 return false;
1221
1222 case Entry::Type::ThreadIndexID:
1223 if (exe_ctx) {
1224 Thread *thread = exe_ctx->GetThreadPtr();
1225 if (thread) {
1226 const char *format = "%" PRIu32"u";
1227 if (!entry.printf_format.empty())
1228 format = entry.printf_format.c_str();
1229 s.Printf(format, thread->GetIndexID());
1230 return true;
1231 }
1232 }
1233 return false;
1234
1235 case Entry::Type::ThreadName:
1236 if (exe_ctx) {
1237 Thread *thread = exe_ctx->GetThreadPtr();
1238 if (thread) {
1239 const char *cstr = thread->GetName();
1240 if (cstr && cstr[0]) {
1241 s.PutCString(cstr);
1242 return true;
1243 }
1244 }
1245 }
1246 return false;
1247
1248 case Entry::Type::ThreadQueue:
1249 if (exe_ctx) {
1250 Thread *thread = exe_ctx->GetThreadPtr();
1251 if (thread) {
1252 const char *cstr = thread->GetQueueName();
1253 if (cstr && cstr[0]) {
1254 s.PutCString(cstr);
1255 return true;
1256 }
1257 }
1258 }
1259 return false;
1260
1261 case Entry::Type::ThreadStopReason:
1262 if (exe_ctx) {
1263 if (Thread *thread = exe_ctx->GetThreadPtr()) {
1264 std::string stop_description = thread->GetStopDescription();
1265 if (!stop_description.empty()) {
1266 s.PutCString(stop_description);
1267 return true;
1268 }
1269 }
1270 }
1271 return false;
1272
1273 case Entry::Type::ThreadStopReasonRaw:
1274 if (exe_ctx) {
1275 if (Thread *thread = exe_ctx->GetThreadPtr()) {
1276 std::string stop_description = thread->GetStopDescriptionRaw();
1277 if (!stop_description.empty()) {
1278 s.PutCString(stop_description);
1279 return true;
1280 }
1281 }
1282 }
1283 return false;
1284
1285 case Entry::Type::ThreadReturnValue:
1286 if (exe_ctx) {
1287 Thread *thread = exe_ctx->GetThreadPtr();
1288 if (thread) {
1289 StopInfoSP stop_info_sp = thread->GetStopInfo();
1290 if (stop_info_sp && stop_info_sp->IsValid()) {
1291 ValueObjectSP return_valobj_sp =
1292 StopInfo::GetReturnValueObject(stop_info_sp);
1293 if (return_valobj_sp) {
1294 return_valobj_sp->Dump(s);
1295 return true;
1296 }
1297 }
1298 }
1299 }
1300 return false;
1301
1302 case Entry::Type::ThreadCompletedExpression:
1303 if (exe_ctx) {
1304 Thread *thread = exe_ctx->GetThreadPtr();
1305 if (thread) {
1306 StopInfoSP stop_info_sp = thread->GetStopInfo();
1307 if (stop_info_sp && stop_info_sp->IsValid()) {
1308 ExpressionVariableSP expression_var_sp =
1309 StopInfo::GetExpressionVariable(stop_info_sp);
1310 if (expression_var_sp && expression_var_sp->GetValueObject()) {
1311 expression_var_sp->GetValueObject()->Dump(s);
1312 return true;
1313 }
1314 }
1315 }
1316 }
1317 return false;
1318
1319 case Entry::Type::ScriptThread:
1320 if (exe_ctx) {
1321 Thread *thread = exe_ctx->GetThreadPtr();
1322 if (thread)
1323 return RunScriptFormatKeyword(s, sc, exe_ctx, thread,
1324 entry.string.c_str());
1325 }
1326 return false;
1327
1328 case Entry::Type::ThreadInfo:
1329 if (exe_ctx) {
1330 Thread *thread = exe_ctx->GetThreadPtr();
1331 if (thread) {
1332 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
1333 if (object_sp &&
1334 object_sp->GetType() == eStructuredDataTypeDictionary) {
1335 if (FormatThreadExtendedInfoRecurse(entry, object_sp, sc, exe_ctx, s))
1336 return true;
1337 }
1338 }
1339 }
1340 return false;
1341
1342 case Entry::Type::TargetArch:
1343 if (exe_ctx) {
1344 Target *target = exe_ctx->GetTargetPtr();
1345 if (target) {
1346 const ArchSpec &arch = target->GetArchitecture();
1347 if (arch.IsValid()) {
1348 s.PutCString(arch.GetArchitectureName());
1349 return true;
1350 }
1351 }
1352 }
1353 return false;
1354
1355 case Entry::Type::ScriptTarget:
1356 if (exe_ctx) {
1357 Target *target = exe_ctx->GetTargetPtr();
1358 if (target)
1359 return RunScriptFormatKeyword(s, sc, exe_ctx, target,
1360 entry.string.c_str());
1361 }
1362 return false;
1363
1364 case Entry::Type::ModuleFile:
1365 if (sc) {
1366 Module *module = sc->module_sp.get();
1367 if (module) {
1368 if (DumpFile(s, module->GetFileSpec(), (FileKind)entry.number))
1369 return true;
1370 }
1371 }
1372 return false;
1373
1374 case Entry::Type::File:
1375 if (sc) {
1376 CompileUnit *cu = sc->comp_unit;
1377 if (cu) {
1378 if (DumpFile(s, cu->GetPrimaryFile(), (FileKind)entry.number))
1379 return true;
1380 }
1381 }
1382 return false;
1383
1384 case Entry::Type::Lang:
1385 if (sc) {
1386 CompileUnit *cu = sc->comp_unit;
1387 if (cu) {
1388 const char *lang_name =
1389 Language::GetNameForLanguageType(cu->GetLanguage());
1390 if (lang_name) {
1391 s.PutCString(lang_name);
1392 return true;
1393 }
1394 }
1395 }
1396 return false;
1397
1398 case Entry::Type::FrameIndex:
1399 if (exe_ctx) {
1400 StackFrame *frame = exe_ctx->GetFramePtr();
1401 if (frame) {
1402 const char *format = "%" PRIu32"u";
1403 if (!entry.printf_format.empty())
1404 format = entry.printf_format.c_str();
1405 s.Printf(format, frame->GetFrameIndex());
1406 return true;
1407 }
1408 }
1409 return false;
1410
1411 case Entry::Type::FrameRegisterPC:
1412 if (exe_ctx) {
1413 StackFrame *frame = exe_ctx->GetFramePtr();
1414 if (frame) {
1415 const Address &pc_addr = frame->GetFrameCodeAddress();
1416 if (pc_addr.IsValid()) {
1417 if (DumpAddressAndContent(s, sc, exe_ctx, pc_addr, false))
1418 return true;
1419 }
1420 }
1421 }
1422 return false;
1423
1424 case Entry::Type::FrameRegisterSP:
1425 if (exe_ctx) {
1426 StackFrame *frame = exe_ctx->GetFramePtr();
1427 if (frame) {
1428 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP1,
1429 (lldb::Format)entry.number))
1430 return true;
1431 }
1432 }
1433 return false;
1434
1435 case Entry::Type::FrameRegisterFP:
1436 if (exe_ctx) {
1437 StackFrame *frame = exe_ctx->GetFramePtr();
1438 if (frame) {
1439 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP2,
1440 (lldb::Format)entry.number))
1441 return true;
1442 }
1443 }
1444 return false;
1445
1446 case Entry::Type::FrameRegisterFlags:
1447 if (exe_ctx) {
1448 StackFrame *frame = exe_ctx->GetFramePtr();
1449 if (frame) {
1450 if (DumpRegister(s, frame, eRegisterKindGeneric,
1451 LLDB_REGNUM_GENERIC_FLAGS4, (lldb::Format)entry.number))
1452 return true;
1453 }
1454 }
1455 return false;
1456
1457 case Entry::Type::FrameNoDebug:
1458 if (exe_ctx) {
1459 StackFrame *frame = exe_ctx->GetFramePtr();
1460 if (frame) {
1461 return !frame->HasDebugInformation();
1462 }
1463 }
1464 return true;
1465
1466 case Entry::Type::FrameRegisterByName:
1467 if (exe_ctx) {
1468 StackFrame *frame = exe_ctx->GetFramePtr();
1469 if (frame) {
1470 if (DumpRegister(s, frame, entry.string.c_str(),
1471 (lldb::Format)entry.number))
1472 return true;
1473 }
1474 }
1475 return false;
1476
1477 case Entry::Type::FrameIsArtificial: {
1478 if (exe_ctx)
1479 if (StackFrame *frame = exe_ctx->GetFramePtr())
1480 return frame->IsArtificial();
1481 return false;
1482 }
1483
1484 case Entry::Type::ScriptFrame:
1485 if (exe_ctx) {
1486 StackFrame *frame = exe_ctx->GetFramePtr();
1487 if (frame)
1488 return RunScriptFormatKeyword(s, sc, exe_ctx, frame,
1489 entry.string.c_str());
1490 }
1491 return false;
1492
1493 case Entry::Type::FunctionID:
1494 if (sc) {
1495 if (sc->function) {
1496 s.Printf("function{0x%8.8" PRIx64"l" "x" "}", sc->function->GetID());
1497 return true;
1498 } else if (sc->symbol) {
1499 s.Printf("symbol[%u]", sc->symbol->GetID());
1500 return true;
1501 }
1502 }
1503 return false;
1504
1505 case Entry::Type::FunctionDidChange:
1506 return function_changed;
1507
1508 case Entry::Type::FunctionInitialFunction:
1509 return initial_function;
1510
1511 case Entry::Type::FunctionName: {
1512 if (!sc)
1513 return false;
1514
1515 Language *language_plugin = nullptr;
1516 bool language_plugin_handled = false;
1517 StreamString ss;
1518
1519 if (sc->function)
1520 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1521 else if (sc->symbol)
1522 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1523
1524 if (language_plugin)
1525 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1526 sc, exe_ctx, Language::FunctionNameRepresentation::eName, ss);
1527
1528 if (language_plugin_handled) {
1529 s << ss.GetString();
1530 return true;
1531 } else {
1532 const char *name = nullptr;
1533 if (sc->function)
1534 name = sc->function->GetName().AsCString(nullptr);
1535 else if (sc->symbol)
1536 name = sc->symbol->GetName().AsCString(nullptr);
1537
1538 if (name) {
1539 s.PutCString(name);
1540
1541 if (sc->block) {
1542 Block *inline_block = sc->block->GetContainingInlinedBlock();
1543 if (inline_block) {
1544 const InlineFunctionInfo *inline_info =
1545 sc->block->GetInlinedFunctionInfo();
1546 if (inline_info) {
1547 s.PutCString(" [inlined] ");
1548 inline_info->GetName().Dump(&s);
1549 }
1550 }
1551 }
1552 return true;
1553 }
1554 }
1555 }
1556 return false;
1557
1558 case Entry::Type::FunctionNameNoArgs: {
1559 if (!sc)
1560 return false;
1561
1562 Language *language_plugin = nullptr;
1563 bool language_plugin_handled = false;
1564 StreamString ss;
1565 if (sc->function)
1566 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1567 else if (sc->symbol)
1568 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1569
1570 if (language_plugin)
1571 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1572 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithNoArgs,
1573 ss);
1574
1575 if (language_plugin_handled) {
1576 s << ss.GetString();
1577 return true;
1578 } else {
1579 ConstString name;
1580 if (sc->function)
1581 name = sc->function->GetNameNoArguments();
1582 else if (sc->symbol)
1583 name = sc->symbol->GetNameNoArguments();
1584 if (name) {
1585 s.PutCString(name.GetCString());
1586 return true;
1587 }
1588 }
1589 }
1590 return false;
1591
1592 case Entry::Type::FunctionNameWithArgs: {
1593 if (!sc)
1594 return false;
1595
1596 Language *language_plugin = nullptr;
1597 bool language_plugin_handled = false;
1598 StreamString ss;
1599 if (sc->function)
1600 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1601 else if (sc->symbol)
1602 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1603
1604 if (language_plugin)
1605 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1606 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithArgs, ss);
1607
1608 if (language_plugin_handled) {
1609 s << ss.GetString();
1610 return true;
1611 } else {
1612 // Print the function name with arguments in it
1613 if (sc->function) {
1614 ExecutionContextScope *exe_scope =
1615 exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
1616 const char *cstr = sc->function->GetName().AsCString(nullptr);
1617 if (cstr) {
1618 const InlineFunctionInfo *inline_info = nullptr;
1619 VariableListSP variable_list_sp;
1620 bool get_function_vars = true;
1621 if (sc->block) {
1622 Block *inline_block = sc->block->GetContainingInlinedBlock();
1623
1624 if (inline_block) {
1625 get_function_vars = false;
1626 inline_info = sc->block->GetInlinedFunctionInfo();
1627 if (inline_info)
1628 variable_list_sp = inline_block->GetBlockVariableList(true);
1629 }
1630 }
1631
1632 if (get_function_vars) {
1633 variable_list_sp =
1634 sc->function->GetBlock(true).GetBlockVariableList(true);
1635 }
1636
1637 if (inline_info) {
1638 s.PutCString(cstr);
1639 s.PutCString(" [inlined] ");
1640 cstr = inline_info->GetName().GetCString();
1641 }
1642
1643 VariableList args;
1644 if (variable_list_sp)
1645 variable_list_sp->AppendVariablesWithScope(
1646 eValueTypeVariableArgument, args);
1647 if (args.GetSize() > 0) {
1648 const char *open_paren = strchr(cstr, '(');
1649 const char *close_paren = nullptr;
1650 const char *generic = strchr(cstr, '<');
1651 // if before the arguments list begins there is a template sign
1652 // then scan to the end of the generic args before you try to find
1653 // the arguments list
1654 if (generic && open_paren && generic < open_paren) {
1655 int generic_depth = 1;
1656 ++generic;
1657 for (; *generic && generic_depth > 0; generic++) {
1658 if (*generic == '<')
1659 generic_depth++;
1660 if (*generic == '>')
1661 generic_depth--;
1662 }
1663 if (*generic)
1664 open_paren = strchr(generic, '(');
1665 else
1666 open_paren = nullptr;
1667 }
1668 if (open_paren) {
1669 if (IsToken(open_paren, "(anonymous namespace)")) {
1670 open_paren =
1671 strchr(open_paren + strlen("(anonymous namespace)"), '(');
1672 if (open_paren)
1673 close_paren = strchr(open_paren, ')');
1674 } else
1675 close_paren = strchr(open_paren, ')');
1676 }
1677
1678 if (open_paren)
1679 s.Write(cstr, open_paren - cstr + 1);
1680 else {
1681 s.PutCString(cstr);
1682 s.PutChar('(');
1683 }
1684 const size_t num_args = args.GetSize();
1685 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx) {
1686 std::string buffer;
1687
1688 VariableSP var_sp(args.GetVariableAtIndex(arg_idx));
1689 ValueObjectSP var_value_sp(
1690 ValueObjectVariable::Create(exe_scope, var_sp));
1691 StreamString ss;
1692 llvm::StringRef var_representation;
1693 const char *var_name = var_value_sp->GetName().GetCString();
1694 if (var_value_sp->GetCompilerType().IsValid()) {
1695 if (exe_scope && exe_scope->CalculateTarget())
1696 var_value_sp =
1697 var_value_sp->GetQualifiedRepresentationIfAvailable(
1698 exe_scope->CalculateTarget()
1699 ->TargetProperties::GetPreferDynamicValue(),
1700 exe_scope->CalculateTarget()
1701 ->TargetProperties::GetEnableSyntheticValue());
1702 if (var_value_sp->GetCompilerType().IsAggregateType() &&
1703 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp)) {
1704 static StringSummaryFormat format(
1705 TypeSummaryImpl::Flags()
1706 .SetHideItemNames(false)
1707 .SetShowMembersOneLiner(true),
1708 "");
1709 format.FormatObject(var_value_sp.get(), buffer,
1710 TypeSummaryOptions());
1711 var_representation = buffer;
1712 } else
1713 var_value_sp->DumpPrintableRepresentation(
1714 ss,
1715 ValueObject::ValueObjectRepresentationStyle::
1716 eValueObjectRepresentationStyleSummary,
1717 eFormatDefault,
1718 ValueObject::PrintableRepresentationSpecialCases::eAllow,
1719 false);
1720 }
1721
1722 if (!ss.GetString().empty())
1723 var_representation = ss.GetString();
1724 if (arg_idx > 0)
1725 s.PutCString(", ");
1726 if (var_value_sp->GetError().Success()) {
1727 if (!var_representation.empty())
1728 s.Printf("%s=%s", var_name, var_representation.str().c_str());
1729 else
1730 s.Printf("%s=%s at %s", var_name,
1731 var_value_sp->GetTypeName().GetCString(),
1732 var_value_sp->GetLocationAsCString());
1733 } else
1734 s.Printf("%s=<unavailable>", var_name);
1735 }
1736
1737 if (close_paren)
1738 s.PutCString(close_paren);
1739 else
1740 s.PutChar(')');
1741
1742 } else {
1743 s.PutCString(cstr);
1744 }
1745 return true;
1746 }
1747 } else if (sc->symbol) {
1748 const char *cstr = sc->symbol->GetName().AsCString(nullptr);
1749 if (cstr) {
1750 s.PutCString(cstr);
1751 return true;
1752 }
1753 }
1754 }
1755 }
1756 return false;
1757
1758 case Entry::Type::FunctionMangledName: {
1759 if (!sc)
1760 return false;
1761
1762 const char *name = nullptr;
1763 if (sc->symbol)
1764 name =
1765 sc->symbol->GetMangled().GetName(Mangled::ePreferMangled).AsCString();
1766 else if (sc->function)
1767 name = sc->function->GetMangled()
1768 .GetName(Mangled::ePreferMangled)
1769 .AsCString();
1770
1771 if (!name)
1772 return false;
1773 s.PutCString(name);
1774
1775 if (sc->block && sc->block->GetContainingInlinedBlock()) {
1776 if (const InlineFunctionInfo *inline_info =
1777 sc->block->GetInlinedFunctionInfo()) {
1778 s.PutCString(" [inlined] ");
1779 inline_info->GetName().Dump(&s);
1780 }
1781 }
1782 return true;
1783 }
1784 case Entry::Type::FunctionAddrOffset:
1785 if (addr) {
1786 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, false, false,
1787 false))
1788 return true;
1789 }
1790 return false;
1791
1792 case Entry::Type::FunctionAddrOffsetConcrete:
1793 if (addr) {
1794 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, true, true,
1795 true))
1796 return true;
1797 }
1798 return false;
1799
1800 case Entry::Type::FunctionLineOffset:
1801 if (sc)
1802 return (DumpAddressOffsetFromFunction(
1803 s, sc, exe_ctx, sc->line_entry.range.GetBaseAddress(), false, false,
1804 false));
1805 return false;
1806
1807 case Entry::Type::FunctionPCOffset:
1808 if (exe_ctx) {
1809 StackFrame *frame = exe_ctx->GetFramePtr();
1810 if (frame) {
1811 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx,
1812 frame->GetFrameCodeAddress(), false,
1813 false, false))
1814 return true;
1815 }
1816 }
1817 return false;
1818
1819 case Entry::Type::FunctionChanged:
1820 return function_changed;
1821
1822 case Entry::Type::FunctionIsOptimized: {
1823 bool is_optimized = false;
1824 if (sc && sc->function && sc->function->GetIsOptimized()) {
1825 is_optimized = true;
1826 }
1827 return is_optimized;
1828 }
1829
1830 case Entry::Type::FunctionInitial:
1831 return initial_function;
1832
1833 case Entry::Type::LineEntryFile:
1834 if (sc && sc->line_entry.IsValid()) {
1835 Module *module = sc->module_sp.get();
1836 if (module) {
1837 if (DumpFile(s, sc->line_entry.file, (FileKind)entry.number))
1838 return true;
1839 }
1840 }
1841 return false;
1842
1843 case Entry::Type::LineEntryLineNumber:
1844 if (sc && sc->line_entry.IsValid()) {
1845 const char *format = "%" PRIu32"u";
1846 if (!entry.printf_format.empty())
1847 format = entry.printf_format.c_str();
1848 s.Printf(format, sc->line_entry.line);
1849 return true;
1850 }
1851 return false;
1852
1853 case Entry::Type::LineEntryColumn:
1854 if (sc && sc->line_entry.IsValid() && sc->line_entry.column) {
1855 const char *format = "%" PRIu32"u";
1856 if (!entry.printf_format.empty())
1857 format = entry.printf_format.c_str();
1858 s.Printf(format, sc->line_entry.column);
1859 return true;
1860 }
1861 return false;
1862
1863 case Entry::Type::LineEntryStartAddress:
1864 case Entry::Type::LineEntryEndAddress:
1865 if (sc && sc->line_entry.range.GetBaseAddress().IsValid()) {
1866 Address addr = sc->line_entry.range.GetBaseAddress();
1867
1868 if (entry.type == Entry::Type::LineEntryEndAddress)
1869 addr.Slide(sc->line_entry.range.GetByteSize());
1870 if (DumpAddressAndContent(s, sc, exe_ctx, addr, false))
1871 return true;
1872 }
1873 return false;
1874
1875 case Entry::Type::CurrentPCArrow:
1876 if (addr && exe_ctx && exe_ctx->GetFramePtr()) {
1877 RegisterContextSP reg_ctx =
1878 exe_ctx->GetFramePtr()->GetRegisterContextSP();
1879 if (reg_ctx) {
1880 addr_t pc_loadaddr = reg_ctx->GetPC();
1881 if (pc_loadaddr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
1882 Address pc;
1883 pc.SetLoadAddress(pc_loadaddr, exe_ctx->GetTargetPtr());
1884 if (pc == *addr) {
1885 s.Printf("-> ");
1886 return true;
1887 }
1888 }
1889 }
1890 s.Printf(" ");
1891 return true;
1892 }
1893 return false;
1894 }
1895 return false;
1896}
1897
1898static bool DumpCommaSeparatedChildEntryNames(Stream &s,
1899 const Definition *parent) {
1900 if (parent->children) {
1901 const size_t n = parent->num_children;
1902 for (size_t i = 0; i < n; ++i) {
1903 if (i > 0)
1904 s.PutCString(", ");
1905 s.Printf("\"%s\"", parent->children[i].name);
1906 }
1907 return true;
1908 }
1909 return false;
1910}
1911
1912static Status ParseEntry(const llvm::StringRef &format_str,
1913 const Definition *parent, FormatEntity::Entry &entry) {
1914 Status error;
1915
1916 const size_t sep_pos = format_str.find_first_of(".[:");
1917 const char sep_char =
1918 (sep_pos == llvm::StringRef::npos) ? '\0' : format_str[sep_pos];
1919 llvm::StringRef key = format_str.substr(0, sep_pos);
1920
1921 const size_t n = parent->num_children;
1922 for (size_t i = 0; i < n; ++i) {
1923 const Definition *entry_def = parent->children + i;
1924 if (key.equals(entry_def->name) || entry_def->name[0] == '*') {
1925 llvm::StringRef value;
1926 if (sep_char)
1927 value =
1928 format_str.substr(sep_pos + (entry_def->keep_separator ? 0 : 1));
1929 switch (entry_def->type) {
1930 case FormatEntity::Entry::Type::ParentString:
1931 entry.string = format_str.str();
1932 return error; // Success
1933
1934 case FormatEntity::Entry::Type::ParentNumber:
1935 entry.number = entry_def->data;
1936 return error; // Success
1937
1938 case FormatEntity::Entry::Type::EscapeCode:
1939 entry.type = entry_def->type;
1940 entry.string = entry_def->string;
1941 return error; // Success
1942
1943 default:
1944 entry.type = entry_def->type;
1945 break;
1946 }
1947
1948 if (value.empty()) {
1949 if (entry_def->type == FormatEntity::Entry::Type::Invalid) {
1950 if (entry_def->children) {
1951 StreamString error_strm;
1952 error_strm.Printf("'%s' can't be specified on its own, you must "
1953 "access one of its children: ",
1954 entry_def->name);
1955 DumpCommaSeparatedChildEntryNames(error_strm, entry_def);
1956 error.SetErrorStringWithFormat("%s", error_strm.GetData());
1957 } else if (sep_char == ':') {
1958 // Any value whose separator is a with a ':' means this value has a
1959 // string argument that needs to be stored in the entry (like
1960 // "${script.var:}"). In this case the string value is the empty
1961 // string which is ok.
1962 } else {
1963 error.SetErrorStringWithFormat("%s", "invalid entry definitions");
1964 }
1965 }
1966 } else {
1967 if (entry_def->children) {
1968 error = ParseEntry(value, entry_def, entry);
1969 } else if (sep_char == ':') {
1970 // Any value whose separator is a with a ':' means this value has a
1971 // string argument that needs to be stored in the entry (like
1972 // "${script.var:modulename.function}")
1973 entry.string = value.str();
1974 } else {
1975 error.SetErrorStringWithFormat(
1976 "'%s' followed by '%s' but it has no children", key.str().c_str(),
1977 value.str().c_str());
1978 }
1979 }
1980 return error;
1981 }
1982 }
1983 StreamString error_strm;
1984 if (parent->type == FormatEntity::Entry::Type::Root)
1985 error_strm.Printf(
1986 "invalid top level item '%s'. Valid top level items are: ",
1987 key.str().c_str());
1988 else
1989 error_strm.Printf("invalid member '%s' in '%s'. Valid members are: ",
1990 key.str().c_str(), parent->name);
1991 DumpCommaSeparatedChildEntryNames(error_strm, parent);
1992 error.SetErrorStringWithFormat("%s", error_strm.GetData());
1993 return error;
1994}
1995
1996static const Definition *FindEntry(const llvm::StringRef &format_str,
1997 const Definition *parent,
1998 llvm::StringRef &remainder) {
1999 Status error;
2000
2001 std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.');
2002 const size_t n = parent->num_children;
2003 for (size_t i = 0; i < n; ++i) {
2004 const Definition *entry_def = parent->children + i;
2005 if (p.first.equals(entry_def->name) || entry_def->name[0] == '*') {
2006 if (p.second.empty()) {
2007 if (format_str.back() == '.')
2008 remainder = format_str.drop_front(format_str.size() - 1);
2009 else
2010 remainder = llvm::StringRef(); // Exact match
2011 return entry_def;
2012 } else {
2013 if (entry_def->children) {
2014 return FindEntry(p.second, entry_def, remainder);
2015 } else {
2016 remainder = p.second;
2017 return entry_def;
2018 }
2019 }
2020 }
2021 }
2022 remainder = format_str;
2023 return parent;
2024}
2025
2026Status FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry,
2027 uint32_t depth) {
2028 Status error;
2029 while (!format.empty() && error.Success()) {
2030 const size_t non_special_chars = format.find_first_of("${}\\");
2031
2032 if (non_special_chars == llvm::StringRef::npos) {
2033 // No special characters, just string bytes so add them and we are done
2034 parent_entry.AppendText(format);
2035 return error;
2036 }
2037
2038 if (non_special_chars > 0) {
2039 // We have a special character, so add all characters before these as a
2040 // plain string
2041 parent_entry.AppendText(format.substr(0, non_special_chars));
2042 format = format.drop_front(non_special_chars);
2043 }
2044
2045 switch (format[0]) {
2046 case '\0':
2047 return error;
2048
2049 case '{': {
2050 format = format.drop_front(); // Skip the '{'
2051 Entry scope_entry(Entry::Type::Scope);
2052 error = FormatEntity::ParseInternal(format, scope_entry, depth + 1);
2053 if (error.Fail())
2054 return error;
2055 parent_entry.AppendEntry(std::move(scope_entry));
2056 } break;
2057
2058 case '}':
2059 if (depth == 0)
2060 error.SetErrorString("unmatched '}' character");
2061 else
2062 format =
2063 format
2064 .drop_front(); // Skip the '}' as we are at the end of the scope
2065 return error;
2066
2067 case '\\': {
2068 format = format.drop_front(); // Skip the '\' character
2069 if (format.empty()) {
2070 error.SetErrorString(
2071 "'\\' character was not followed by another character");
2072 return error;
2073 }
2074
2075 const char desens_char = format[0];
2076 format = format.drop_front(); // Skip the desensitized char character
2077 switch (desens_char) {
2078 case 'a':
2079 parent_entry.AppendChar('\a');
2080 break;
2081 case 'b':
2082 parent_entry.AppendChar('\b');
2083 break;
2084 case 'f':
2085 parent_entry.AppendChar('\f');
2086 break;
2087 case 'n':
2088 parent_entry.AppendChar('\n');
2089 break;
2090 case 'r':
2091 parent_entry.AppendChar('\r');
2092 break;
2093 case 't':
2094 parent_entry.AppendChar('\t');
2095 break;
2096 case 'v':
2097 parent_entry.AppendChar('\v');
2098 break;
2099 case '\'':
2100 parent_entry.AppendChar('\'');
2101 break;
2102 case '\\':
2103 parent_entry.AppendChar('\\');
2104 break;
2105 case '0':
2106 // 1 to 3 octal chars
2107 {
2108 // Make a string that can hold onto the initial zero char, up to 3
2109 // octal digits, and a terminating NULL.
2110 char oct_str[5] = {0, 0, 0, 0, 0};
2111
2112 int i;
2113 for (i = 0; (format[i] >= '0' && format[i] <= '7') && i < 4; ++i)
2114 oct_str[i] = format[i];
2115
2116 // We don't want to consume the last octal character since the main
2117 // for loop will do this for us, so we advance p by one less than i
2118 // (even if i is zero)
2119 format = format.drop_front(i);
2120 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
2121 if (octal_value <= UINT8_MAX(255)) {
2122 parent_entry.AppendChar((char)octal_value);
2123 } else {
2124 error.SetErrorString("octal number is larger than a single byte");
2125 return error;
2126 }
2127 }
2128 break;
2129
2130 case 'x':
2131 // hex number in the format
2132 if (isxdigit(format[0])) {
2133 // Make a string that can hold onto two hex chars plus a
2134 // NULL terminator
2135 char hex_str[3] = {0, 0, 0};
2136 hex_str[0] = format[0];
2137
2138 format = format.drop_front();
2139
2140 if (isxdigit(format[0])) {
2141 hex_str[1] = format[0];
2142 format = format.drop_front();
2143 }
2144
2145 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
2146 if (hex_value <= UINT8_MAX(255)) {
2147 parent_entry.AppendChar((char)hex_value);
2148 } else {
2149 error.SetErrorString("hex number is larger than a single byte");
2150 return error;
2151 }
2152 } else {
2153 parent_entry.AppendChar(desens_char);
2154 }
2155 break;
2156
2157 default:
2158 // Just desensitize any other character by just printing what came
2159 // after the '\'
2160 parent_entry.AppendChar(desens_char);
2161 break;
2162 }
2163 } break;
2164
2165 case '$':
2166 if (format.size() == 1) {
2167 // '$' at the end of a format string, just print the '$'
2168 parent_entry.AppendText("$");
2169 } else {
2170 format = format.drop_front(); // Skip the '$'
2171
2172 if (format[0] == '{') {
2173 format = format.drop_front(); // Skip the '{'
2174
2175 llvm::StringRef variable, variable_format;
2176 error = FormatEntity::ExtractVariableInfo(format, variable,
2177 variable_format);
2178 if (error.Fail())
2179 return error;
2180 bool verify_is_thread_id = false;
2181 Entry entry;
2182 if (!variable_format.empty()) {
2183 entry.printf_format = variable_format.str();
2184
2185 // If the format contains a '%' we are going to assume this is a
2186 // printf style format. So if you want to format your thread ID
2187 // using "0x%llx" you can use: ${thread.id%0x%llx}
2188 //
2189 // If there is no '%' in the format, then it is assumed to be a
2190 // LLDB format name, or one of the extended formats specified in
2191 // the switch statement below.
2192
2193 if (entry.printf_format.find('%') == std::string::npos) {
2194 bool clear_printf = false;
2195
2196 if (FormatManager::GetFormatFromCString(
2197 entry.printf_format.c_str(), false, entry.fmt)) {
2198 // We have an LLDB format, so clear the printf format
2199 clear_printf = true;
2200 } else if (entry.printf_format.size() == 1) {
2201 switch (entry.printf_format[0]) {
2202 case '@': // if this is an @ sign, print ObjC description
2203 entry.number = ValueObject::
2204 eValueObjectRepresentationStyleLanguageSpecific;
2205 clear_printf = true;
2206 break;
2207 case 'V': // if this is a V, print the value using the default
2208 // format
2209 entry.number =
2210 ValueObject::eValueObjectRepresentationStyleValue;
2211 clear_printf = true;
2212 break;
2213 case 'L': // if this is an L, print the location of the value
2214 entry.number =
2215 ValueObject::eValueObjectRepresentationStyleLocation;
2216 clear_printf = true;
2217 break;
2218 case 'S': // if this is an S, print the summary after all
2219 entry.number =
2220 ValueObject::eValueObjectRepresentationStyleSummary;
2221 clear_printf = true;
2222 break;
2223 case '#': // if this is a '#', print the number of children
2224 entry.number =
2225 ValueObject::eValueObjectRepresentationStyleChildrenCount;
2226 clear_printf = true;
2227 break;
2228 case 'T': // if this is a 'T', print the type
2229 entry.number =
2230 ValueObject::eValueObjectRepresentationStyleType;
2231 clear_printf = true;
2232 break;
2233 case 'N': // if this is a 'N', print the name
2234 entry.number =
2235 ValueObject::eValueObjectRepresentationStyleName;
2236 clear_printf = true;
2237 break;
2238 case '>': // if this is a '>', print the expression path
2239 entry.number = ValueObject::
2240 eValueObjectRepresentationStyleExpressionPath;
2241 clear_printf = true;
2242 break;
2243 default:
2244 error.SetErrorStringWithFormat("invalid format: '%s'",
2245 entry.printf_format.c_str());
2246 return error;
2247 }
2248 } else if (FormatManager::GetFormatFromCString(
2249 entry.printf_format.c_str(), true, entry.fmt)) {
2250 clear_printf = true;
2251 } else if (entry.printf_format == "tid") {
2252 verify_is_thread_id = true;
2253 } else {
2254 error.SetErrorStringWithFormat("invalid format: '%s'",
2255 entry.printf_format.c_str());
2256 return error;
2257 }
2258
2259 // Our format string turned out to not be a printf style format
2260 // so lets clear the string
2261 if (clear_printf)
2262 entry.printf_format.clear();
2263 }
2264 }
2265
2266 // Check for dereferences
2267 if (variable[0] == '*') {
2268 entry.deref = true;
2269 variable = variable.drop_front();
2270 }
2271
2272 error = ParseEntry(variable, &g_root, entry);
2273 if (error.Fail())
2274 return error;
2275
2276 if (verify_is_thread_id) {
2277 if (entry.type != Entry::Type::ThreadID &&
2278 entry.type != Entry::Type::ThreadProtocolID) {
2279 error.SetErrorString("the 'tid' format can only be used on "
2280 "${thread.id} and ${thread.protocol_id}");
2281 }
2282 }
2283
2284 switch (entry.type) {
2285 case Entry::Type::Variable:
2286 case Entry::Type::VariableSynthetic:
2287 if (entry.number == 0) {
2288 if (entry.string.empty())
2289 entry.number =
2290 ValueObject::eValueObjectRepresentationStyleValue;
2291 else
2292 entry.number =
2293 ValueObject::eValueObjectRepresentationStyleSummary;
2294 }
2295 break;
2296 default:
2297 // Make sure someone didn't try to dereference anything but ${var}
2298 // or ${svar}
2299 if (entry.deref) {
2300 error.SetErrorStringWithFormat(
2301 "${%s} can't be dereferenced, only ${var} and ${svar} can.",
2302 variable.str().c_str());
2303 return error;
2304 }
2305 }
2306 parent_entry.AppendEntry(std::move(entry));
2307 }
2308 }
2309 break;
2310 }
2311 }
2312 return error;
2313}
2314
2315Status FormatEntity::ExtractVariableInfo(llvm::StringRef &format_str,
2316 llvm::StringRef &variable_name,
2317 llvm::StringRef &variable_format) {
2318 Status error;
2319 variable_name = llvm::StringRef();
2320 variable_format = llvm::StringRef();
2321
2322 const size_t paren_pos = format_str.find('}');
2323 if (paren_pos != llvm::StringRef::npos) {
2324 const size_t percent_pos = format_str.find('%');
2325 if (percent_pos < paren_pos) {
2326 if (percent_pos > 0) {
2327 if (percent_pos > 1)
2328 variable_name = format_str.substr(0, percent_pos);
2329 variable_format =
2330 format_str.substr(percent_pos + 1, paren_pos - (percent_pos + 1));
2331 }
2332 } else {
2333 variable_name = format_str.substr(0, paren_pos);
2334 }
2335 // Strip off elements and the formatting and the trailing '}'
2336 format_str = format_str.substr(paren_pos + 1);
2337 } else {
2338 error.SetErrorStringWithFormat(
2339 "missing terminating '}' character for '${%s'",
2340 format_str.str().c_str());
2341 }
2342 return error;
2343}
2344
2345bool FormatEntity::FormatFileSpec(const FileSpec &file_spec, Stream &s,
2346 llvm::StringRef variable_name,
2347 llvm::StringRef variable_format) {
2348 if (variable_name.empty() || variable_name.equals(".fullpath")) {
2349 file_spec.Dump(s.AsRawOstream());
2350 return true;
2351 } else if (variable_name.equals(".basename")) {
2352 s.PutCString(file_spec.GetFilename().GetStringRef());
2353 return true;
2354 } else if (variable_name.equals(".dirname")) {
2355 s.PutCString(file_spec.GetFilename().GetStringRef());
2356 return true;
2357 }
2358 return false;
2359}
2360
2361static std::string MakeMatch(const llvm::StringRef &prefix,
2362 const char *suffix) {
2363 std::string match(prefix.str());
2364 match.append(suffix);
2365 return match;
2366}
2367
2368static void AddMatches(const Definition *def, const llvm::StringRef &prefix,
2369 const llvm::StringRef &match_prefix,
2370 StringList &matches) {
2371 const size_t n = def->num_children;
2372 if (n > 0) {
2373 for (size_t i = 0; i < n; ++i) {
2374 std::string match = prefix.str();
2375 if (match_prefix.empty())
2376 matches.AppendString(MakeMatch(prefix, def->children[i].name));
2377 else if (strncmp(def->children[i].name, match_prefix.data(),
2378 match_prefix.size()) == 0)
2379 matches.AppendString(
2380 MakeMatch(prefix, def->children[i].name + match_prefix.size()));
2381 }
2382 }
2383}
2384
2385void FormatEntity::AutoComplete(CompletionRequest &request) {
2386 llvm::StringRef str = request.GetCursorArgumentPrefix();
2387
2388 const size_t dollar_pos = str.rfind('$');
2389 if (dollar_pos == llvm::StringRef::npos)
2390 return;
2391
2392 // Hitting TAB after $ at the end of the string add a "{"
2393 if (dollar_pos == str.size() - 1) {
2394 std::string match = str.str();
2395 match.append("{");
2396 request.AddCompletion(match);
2397 return;
2398 }
2399
2400 if (str[dollar_pos + 1] != '{')
2401 return;
2402
2403 const size_t close_pos = str.find('}', dollar_pos + 2);
2404 if (close_pos != llvm::StringRef::npos)
2405 return;
2406
2407 const size_t format_pos = str.find('%', dollar_pos + 2);
2408 if (format_pos != llvm::StringRef::npos)
2409 return;
2410
2411 llvm::StringRef partial_variable(str.substr(dollar_pos + 2));
2412 if (partial_variable.empty()) {
2413 // Suggest all top level entities as we are just past "${"
2414 StringList new_matches;
2415 AddMatches(&g_root, str, llvm::StringRef(), new_matches);
2416 request.AddCompletions(new_matches);
2417 return;
2418 }
2419
2420 // We have a partially specified variable, find it
2421 llvm::StringRef remainder;
2422 const Definition *entry_def = FindEntry(partial_variable, &g_root, remainder);
2423 if (!entry_def)
2424 return;
2425
2426 const size_t n = entry_def->num_children;
2427
2428 if (remainder.empty()) {
2429 // Exact match
2430 if (n > 0) {
2431 // "${thread.info" <TAB>
2432 request.AddCompletion(MakeMatch(str, "."));
2433 } else {
2434 // "${thread.id" <TAB>
2435 request.AddCompletion(MakeMatch(str, "}"));
2436 }
2437 } else if (remainder.equals(".")) {
2438 // "${thread." <TAB>
2439 StringList new_matches;
2440 AddMatches(entry_def, str, llvm::StringRef(), new_matches);
2441 request.AddCompletions(new_matches);
2442 } else {
2443 // We have a partial match
2444 // "${thre" <TAB>
2445 StringList new_matches;
2446 AddMatches(entry_def, str, remainder, new_matches);
2447 request.AddCompletions(new_matches);
2448 }
2449}