LLDB mainline
OptionArgParser.cpp
Go to the documentation of this file.
1//===-- OptionArgParser.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
12#include "lldb/Target/ABI.h"
14#include "lldb/Target/Target.h"
16#include "lldb/Utility/Status.h"
18
19using namespace lldb_private;
20using namespace lldb;
21
22bool OptionArgParser::ToBoolean(llvm::StringRef ref, bool fail_value,
23 bool *success_ptr) {
24 if (success_ptr)
25 *success_ptr = true;
26 ref = ref.trim();
27 if (ref.equals_insensitive("false") || ref.equals_insensitive("off") ||
28 ref.equals_insensitive("no") || ref.equals_insensitive("0")) {
29 return false;
30 } else if (ref.equals_insensitive("true") || ref.equals_insensitive("on") ||
31 ref.equals_insensitive("yes") || ref.equals_insensitive("1")) {
32 return true;
33 }
34 if (success_ptr)
35 *success_ptr = false;
36 return fail_value;
37}
38
39llvm::Expected<bool> OptionArgParser::ToBoolean(llvm::StringRef option_name,
40 llvm::StringRef option_arg) {
41 bool parse_success;
42 const bool option_value =
43 ToBoolean(option_arg, false /* doesn't matter */, &parse_success);
44 if (parse_success)
45 return option_value;
46 else
47 return llvm::createStringError(
48 "Invalid boolean value for option '%s': '%s'",
49 option_name.str().c_str(),
50 option_arg.empty() ? "<null>" : option_arg.str().c_str());
51}
52
53char OptionArgParser::ToChar(llvm::StringRef s, char fail_value,
54 bool *success_ptr) {
55 if (success_ptr)
56 *success_ptr = false;
57 if (s.size() != 1)
58 return fail_value;
59
60 if (success_ptr)
61 *success_ptr = true;
62 return s[0];
63}
64
65int64_t OptionArgParser::ToOptionEnum(llvm::StringRef s,
66 const OptionEnumValues &enum_values,
67 int32_t fail_value, Status &error) {
68 error.Clear();
69 if (enum_values.empty()) {
70 error = Status::FromErrorString("invalid enumeration argument");
71 return fail_value;
72 }
73
74 if (s.empty()) {
75 error = Status::FromErrorString("empty enumeration string");
76 return fail_value;
77 }
78
79 for (const auto &enum_value : enum_values) {
80 llvm::StringRef this_enum(enum_value.string_value);
81 if (this_enum.starts_with(s))
82 return enum_value.value;
83 }
84
85 StreamString strm;
86 strm.PutCString("invalid enumeration value, valid values are: ");
87 bool is_first = true;
88 for (const auto &enum_value : enum_values) {
89 strm.Printf("%s\"%s\"",
90 is_first ? is_first = false,"" : ", ", enum_value.string_value);
91 }
92 error = Status(strm.GetString().str());
93 return fail_value;
94}
95
97 size_t *byte_size_ptr) {
98 format = eFormatInvalid;
100
101 if (s && s[0]) {
102 if (byte_size_ptr) {
103 if (isdigit(s[0])) {
104 char *format_char = nullptr;
105 unsigned long byte_size = ::strtoul(s, &format_char, 0);
106 if (byte_size != ULONG_MAX)
107 *byte_size_ptr = byte_size;
108 s = format_char;
109 } else
110 *byte_size_ptr = 0;
111 }
112
113 if (!FormatManager::GetFormatFromCString(s, format)) {
114 StreamString error_strm;
115 error_strm.Printf(
116 "Invalid format character or name '%s'. Valid values are:\n", s);
117 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
118 char format_char = FormatManager::GetFormatAsFormatChar(f);
119 if (format_char)
120 error_strm.Printf("'%c' or ", format_char);
121
122 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
123 error_strm.EOL();
124 }
125
126 if (byte_size_ptr)
127 error_strm.PutCString(
128 "An optional byte size can precede the format character.\n");
129 error = Status(error_strm.GetString().str());
130 }
131
132 if (error.Fail())
133 return error;
134 } else {
135 error = Status::FromErrorStringWithFormat("%s option string",
136 s ? "empty" : "invalid");
137 }
138 return error;
139}
140
142 llvm::StringRef s, lldb::ScriptLanguage fail_value, bool *success_ptr) {
143 if (success_ptr)
144 *success_ptr = true;
145
146 if (s.equals_insensitive("python"))
148 if (s.equals_insensitive("lua"))
149 return eScriptLanguageLua;
150 if (s.equals_insensitive("default"))
152 if (s.equals_insensitive("none"))
153 return eScriptLanguageNone;
154
155 if (success_ptr)
156 *success_ptr = false;
157 return fail_value;
158}
159
161 llvm::StringRef s,
162 lldb::addr_t fail_value,
163 Status *error_ptr) {
164 std::optional<lldb::addr_t> maybe_addr = DoToAddress(exe_ctx, s, error_ptr);
165 return maybe_addr.value_or(fail_value);
166}
167
169 llvm::StringRef s,
170 lldb::addr_t fail_value,
171 Status *error_ptr) {
172 std::optional<lldb::addr_t> maybe_addr = DoToAddress(exe_ctx, s, error_ptr);
173 if (!maybe_addr)
174 return fail_value;
175
176 lldb::addr_t addr = *maybe_addr;
177
178 if (Process *process = exe_ctx->GetProcessPtr())
179 addr = process->FixAnyAddress(addr);
180
181 return addr;
182}
183
184std::optional<lldb::addr_t>
185OptionArgParser::DoToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s,
186 Status *error_ptr) {
187 if (s.empty()) {
188 if (error_ptr)
190 "invalid address expression \"%s\"", s.str().c_str());
191 return {};
192 }
193
194 llvm::StringRef sref = s;
195
197 if (!s.getAsInteger(0, addr)) {
198 if (error_ptr)
199 error_ptr->Clear();
200
201 return addr;
202 }
203
204 // Try base 16 with no prefix...
205 if (!s.getAsInteger(16, addr)) {
206 if (error_ptr)
207 error_ptr->Clear();
208 return addr;
209 }
210
211 Target *target = nullptr;
212 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
213 if (error_ptr)
215 "invalid address expression \"%s\"", s.str().c_str());
216 return {};
217 }
218
219 lldb::ValueObjectSP valobj_sp;
221 options.SetCoerceToId(false);
222 options.SetUnwindOnError(true);
223 options.SetKeepInMemory(false);
224 options.SetTryAllThreads(true);
225
226 ExpressionResults expr_result =
227 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
228
229 bool success = false;
230 if (expr_result == eExpressionCompleted) {
231 if (valobj_sp)
232 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
233 valobj_sp->GetDynamicValueType(), true);
234 // Get the address to watch.
235 if (valobj_sp) {
236 // In C an array decays to a pointer to its first element, whose value is
237 // the address of the array object itself. An aggregate has no scalar
238 // value, so GetValueAsUnsigned() would fail here; use the array's own
239 // load address instead.
240 if (valobj_sp->GetCompilerType().IsArrayType()) {
241 addr = valobj_sp->GetAddressOf(/*scalar_is_load_address=*/true).address;
242 success = addr != LLDB_INVALID_ADDRESS;
243 } else {
244 addr = valobj_sp->GetValueAsUnsigned(0, &success);
245 }
246 }
247 if (success) {
248 if (error_ptr)
249 error_ptr->Clear();
250 return addr;
251 }
252 if (error_ptr)
254 "address expression \"%s\" resulted in a value whose type "
255 "can't be converted to an address: %s",
256 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
257 return {};
258 }
259
260 // Since the compiler can't handle things like "main + 12" we should try to
261 // do this for now. The compiler doesn't like adding offsets to function
262 // pointer types.
263 // Some languages also don't have a natural representation for register
264 // values (e.g. swift) so handle simple uses of them here as well.
265 // We use a regex to parse these forms, the regex handles:
266 // $reg_name
267 // $reg_name+offset
268 // symbol_name+offset
269 //
270 // The important matching elements in the regex below are:
271 // 1: The reg name if there's no +offset
272 // 3: The symbol/reg name if there is an offset
273 // 4: +/-
274 // 5: The offset value.
275 // clang-format off
276 static RegularExpression g_symbol_plus_offset_regex(
277 "^(\\$[^ +-]+)|(([^ +-]+)[[:space:]]*([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*)$");
278 // clang-format on
279
280 llvm::SmallVector<llvm::StringRef, 4> matches;
281 if (g_symbol_plus_offset_regex.Execute(sref, &matches)) {
282 uint64_t offset = 0;
283 llvm::StringRef name;
284 if (!matches[1].empty())
285 name = matches[1];
286 else
287 name = matches[3];
288
289 llvm::StringRef sign = matches[4];
290 llvm::StringRef str_offset = matches[5];
291
292 // Some languages don't have a natural type for register values, but it
293 // is still useful to look them up here:
294 std::optional<lldb::addr_t> register_value;
295 StackFrame *frame = exe_ctx->GetFramePtr();
296 llvm::StringRef reg_name = name;
297 if (frame && reg_name.consume_front("$")) {
298 RegisterContextSP reg_ctx_sp = frame->GetRegisterContext();
299 if (reg_ctx_sp) {
300 const RegisterInfo *reg_info = reg_ctx_sp->GetRegisterInfoByName(reg_name);
301 if (reg_info) {
302 RegisterValue reg_val;
303 bool success = reg_ctx_sp->ReadRegister(reg_info, reg_val);
304 if (success && reg_val.GetType() != RegisterValue::eTypeInvalid) {
305 register_value = reg_val.GetAsUInt64(0, &success);
306 if (!success)
307 register_value.reset();
308 }
309 }
310 }
311 }
312 if (!str_offset.empty() && !str_offset.getAsInteger(0, offset)) {
314 if (register_value)
315 addr = register_value.value();
316 else
317 addr = ToAddress(exe_ctx, name, LLDB_INVALID_ADDRESS, &error);
318 if (addr != LLDB_INVALID_ADDRESS) {
319 if (sign[0] == '+')
320 return addr + offset;
321 return addr - offset;
322 }
323 } else if (register_value)
324 // In the case of register values, someone might just want to get the
325 // value in a language whose expression parser doesn't support registers.
326 return register_value.value();
327 }
328
329 if (error_ptr)
331 "address expression \"%s\" evaluation failed", s.str().c_str());
332 return {};
333}
static llvm::raw_ostream & error(Stream &strm)
void SetUnwindOnError(bool unwind=false)
Definition Target.h:396
void SetKeepInMemory(bool keep=true)
Definition Target.h:406
void SetCoerceToId(bool coerce=true)
Definition Target.h:392
void SetTryAllThreads(bool try_others=true)
Definition Target.h:429
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
static const char * GetFormatAsCString(lldb::Format format)
static bool GetFormatFromCString(const char *format_cstr, lldb::Format &format)
static char GetFormatAsFormatChar(lldb::Format format)
A plug-in interface definition class for debugging a process.
Definition Process.h:359
uint64_t GetAsUInt64(uint64_t fail_value=UINT64_MAX, bool *success_ptr=nullptr) const
RegisterValue::Type GetType() const
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual lldb::RegisterContextSP GetRegisterContext()
Get the RegisterContext for this frame, if possible.
An error handling class.
Definition Status.h:118
void Clear()
Clear the object state.
Definition Status.cpp:214
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Definition Target.cpp:2940
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
ScriptLanguage
Script interpreter types.
@ eScriptLanguageDefault
@ eScriptLanguageNone
@ eScriptLanguagePython
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Format
Display format definitions.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static lldb::ScriptLanguage ToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value, bool *success_ptr)
static char ToChar(llvm::StringRef s, char fail_value, bool *success_ptr)
static lldb::addr_t ToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
Try to parse an address.
static lldb::addr_t ToRawAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
As for ToAddress but do not remove non-address bits from the result.
static std::optional< lldb::addr_t > DoToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, Status *error)
static Status ToFormat(const char *s, lldb::Format &format, size_t *byte_size_ptr)
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)
Every register is described in detail including its name, alternate name (optional),...