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
11#include "lldb/Target/ABI.h"
13#include "lldb/Target/Target.h"
15#include "lldb/Utility/Status.h"
17
18using namespace lldb_private;
19using namespace lldb;
20
21bool OptionArgParser::ToBoolean(llvm::StringRef ref, bool fail_value,
22 bool *success_ptr) {
23 if (success_ptr)
24 *success_ptr = true;
25 ref = ref.trim();
26 if (ref.equals_insensitive("false") || ref.equals_insensitive("off") ||
27 ref.equals_insensitive("no") || ref.equals_insensitive("0")) {
28 return false;
29 } else if (ref.equals_insensitive("true") || ref.equals_insensitive("on") ||
30 ref.equals_insensitive("yes") || ref.equals_insensitive("1")) {
31 return true;
32 }
33 if (success_ptr)
34 *success_ptr = false;
35 return fail_value;
36}
37
38char OptionArgParser::ToChar(llvm::StringRef s, char fail_value,
39 bool *success_ptr) {
40 if (success_ptr)
41 *success_ptr = false;
42 if (s.size() != 1)
43 return fail_value;
44
45 if (success_ptr)
46 *success_ptr = true;
47 return s[0];
48}
49
50int64_t OptionArgParser::ToOptionEnum(llvm::StringRef s,
51 const OptionEnumValues &enum_values,
52 int32_t fail_value, Status &error) {
53 error.Clear();
54 if (enum_values.empty()) {
55 error.SetErrorString("invalid enumeration argument");
56 return fail_value;
57 }
58
59 if (s.empty()) {
60 error.SetErrorString("empty enumeration string");
61 return fail_value;
62 }
63
64 for (const auto &enum_value : enum_values) {
65 llvm::StringRef this_enum(enum_value.string_value);
66 if (this_enum.starts_with(s))
67 return enum_value.value;
68 }
69
70 StreamString strm;
71 strm.PutCString("invalid enumeration value, valid values are: ");
72 bool is_first = true;
73 for (const auto &enum_value : enum_values) {
74 strm.Printf("%s\"%s\"",
75 is_first ? is_first = false,"" : ", ", enum_value.string_value);
76 }
77 error.SetErrorString(strm.GetString());
78 return fail_value;
79}
80
82 size_t *byte_size_ptr) {
83 format = eFormatInvalid;
85
86 if (s && s[0]) {
87 if (byte_size_ptr) {
88 if (isdigit(s[0])) {
89 char *format_char = nullptr;
90 unsigned long byte_size = ::strtoul(s, &format_char, 0);
91 if (byte_size != ULONG_MAX)
92 *byte_size_ptr = byte_size;
93 s = format_char;
94 } else
95 *byte_size_ptr = 0;
96 }
97
99 StreamString error_strm;
100 error_strm.Printf(
101 "Invalid format character or name '%s'. Valid values are:\n", s);
102 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
103 char format_char = FormatManager::GetFormatAsFormatChar(f);
104 if (format_char)
105 error_strm.Printf("'%c' or ", format_char);
106
107 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
108 error_strm.EOL();
109 }
110
111 if (byte_size_ptr)
112 error_strm.PutCString(
113 "An optional byte size can precede the format character.\n");
114 error.SetErrorString(error_strm.GetString());
115 }
116
117 if (error.Fail())
118 return error;
119 } else {
120 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
121 }
122 return error;
123}
124
126 llvm::StringRef s, lldb::ScriptLanguage fail_value, bool *success_ptr) {
127 if (success_ptr)
128 *success_ptr = true;
129
130 if (s.equals_insensitive("python"))
132 if (s.equals_insensitive("lua"))
133 return eScriptLanguageLua;
134 if (s.equals_insensitive("default"))
136 if (s.equals_insensitive("none"))
137 return eScriptLanguageNone;
138
139 if (success_ptr)
140 *success_ptr = false;
141 return fail_value;
142}
143
145 llvm::StringRef s,
146 lldb::addr_t fail_value,
147 Status *error_ptr) {
148 std::optional<lldb::addr_t> maybe_addr = DoToAddress(exe_ctx, s, error_ptr);
149 return maybe_addr ? *maybe_addr : fail_value;
150}
151
153 llvm::StringRef s,
154 lldb::addr_t fail_value,
155 Status *error_ptr) {
156 std::optional<lldb::addr_t> maybe_addr = DoToAddress(exe_ctx, s, error_ptr);
157 if (!maybe_addr)
158 return fail_value;
159
160 lldb::addr_t addr = *maybe_addr;
161
162 if (Process *process = exe_ctx->GetProcessPtr())
163 if (ABISP abi_sp = process->GetABI())
164 addr = abi_sp->FixCodeAddress(addr);
165
166 return addr;
167}
168
169std::optional<lldb::addr_t>
170OptionArgParser::DoToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s,
171 Status *error_ptr) {
172 if (s.empty()) {
173 if (error_ptr)
174 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
175 s.str().c_str());
176 return {};
177 }
178
179 llvm::StringRef sref = s;
180
182 if (!s.getAsInteger(0, addr)) {
183 if (error_ptr)
184 error_ptr->Clear();
185
186 return addr;
187 }
188
189 // Try base 16 with no prefix...
190 if (!s.getAsInteger(16, addr)) {
191 if (error_ptr)
192 error_ptr->Clear();
193 return addr;
194 }
195
196 Target *target = nullptr;
197 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
198 if (error_ptr)
199 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
200 s.str().c_str());
201 return {};
202 }
203
204 lldb::ValueObjectSP valobj_sp;
206 options.SetCoerceToId(false);
207 options.SetUnwindOnError(true);
208 options.SetKeepInMemory(false);
209 options.SetTryAllThreads(true);
210
211 ExpressionResults expr_result =
212 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
213
214 bool success = false;
215 if (expr_result == eExpressionCompleted) {
216 if (valobj_sp)
217 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
218 valobj_sp->GetDynamicValueType(), true);
219 // Get the address to watch.
220 if (valobj_sp)
221 addr = valobj_sp->GetValueAsUnsigned(0, &success);
222 if (success) {
223 if (error_ptr)
224 error_ptr->Clear();
225 return addr;
226 }
227 if (error_ptr)
228 error_ptr->SetErrorStringWithFormat(
229 "address expression \"%s\" resulted in a value whose type "
230 "can't be converted to an address: %s",
231 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
232 return {};
233 }
234
235 // Since the compiler can't handle things like "main + 12" we should try to
236 // do this for now. The compiler doesn't like adding offsets to function
237 // pointer types.
238 // Some languages also don't have a natural representation for register
239 // values (e.g. swift) so handle simple uses of them here as well.
240 // We use a regex to parse these forms, the regex handles:
241 // $reg_name
242 // $reg_name+offset
243 // symbol_name+offset
244 //
245 // The important matching elements in the regex below are:
246 // 1: The reg name if there's no +offset
247 // 3: The symbol/reg name if there is an offset
248 // 4: +/-
249 // 5: The offset value.
250 static RegularExpression g_symbol_plus_offset_regex(
251 "^(\\$[^ +-]+)|(([^ +-]+)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*)$");
252
253 llvm::SmallVector<llvm::StringRef, 4> matches;
254 if (g_symbol_plus_offset_regex.Execute(sref, &matches)) {
255 uint64_t offset = 0;
256 llvm::StringRef name;
257 if (!matches[1].empty())
258 name = matches[1];
259 else
260 name = matches[3];
261
262 llvm::StringRef sign = matches[4];
263 llvm::StringRef str_offset = matches[5];
264
265 // Some languages don't have a natural type for register values, but it
266 // is still useful to look them up here:
267 std::optional<lldb::addr_t> register_value;
268 StackFrame *frame = exe_ctx->GetFramePtr();
269 llvm::StringRef reg_name = name;
270 if (frame && reg_name.consume_front("$")) {
271 RegisterContextSP reg_ctx_sp = frame->GetRegisterContext();
272 if (reg_ctx_sp) {
273 const RegisterInfo *reg_info = reg_ctx_sp->GetRegisterInfoByName(reg_name);
274 if (reg_info) {
275 RegisterValue reg_val;
276 bool success = reg_ctx_sp->ReadRegister(reg_info, reg_val);
277 if (success && reg_val.GetType() != RegisterValue::eTypeInvalid) {
278 register_value = reg_val.GetAsUInt64(0, &success);
279 if (!success)
280 register_value.reset();
281 }
282 }
283 }
284 }
285 if (!str_offset.empty() && !str_offset.getAsInteger(0, offset)) {
287 if (register_value)
288 addr = register_value.value();
289 else
290 addr = ToAddress(exe_ctx, name, LLDB_INVALID_ADDRESS, &error);
291 if (addr != LLDB_INVALID_ADDRESS) {
292 if (sign[0] == '+')
293 return addr + offset;
294 return addr - offset;
295 }
296 } else if (register_value)
297 // In the case of register values, someone might just want to get the
298 // value in a language whose expression parser doesn't support registers.
299 return register_value.value();
300 }
301
302 if (error_ptr)
303 error_ptr->SetErrorStringWithFormat(
304 "address expression \"%s\" evaluation failed", s.str().c_str());
305 return {};
306}
static llvm::raw_ostream & error(Stream &strm)
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:334
void SetKeepInMemory(bool keep=true)
Definition: Target.h:344
void SetCoerceToId(bool coerce=true)
Definition: Target.h:330
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:367
"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:341
uint64_t GetAsUInt64(uint64_t fail_value=UINT64_MAX, bool *success_ptr=nullptr) const
RegisterValue::Type GetType() const
Definition: RegisterValue.h:91
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:42
lldb::RegisterContextSP GetRegisterContext()
Get the RegisterContext for this frame, if possible.
An error handling class.
Definition: Status.h:44
void Clear()
Clear the object state.
Definition: Status.cpp:167
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:247
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:65
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:2655
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
Definition: SBAddress.h:15
ScriptLanguage
Script interpreter types.
@ eScriptLanguageLua
@ eScriptLanguageDefault
@ eScriptLanguageNone
@ eScriptLanguagePython
std::shared_ptr< lldb_private::ABI > ABISP
Definition: lldb-forward.h:310
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:472
Format
Display format definitions.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Definition: lldb-forward.h:386
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),...