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
9#include "lldb/Interpreter/OptionArgParser.h"
10#include "lldb/DataFormatters/FormatManager.h"
11#include "lldb/Target/ABI.h"
12#include "lldb/Target/RegisterContext.h"
13#include "lldb/Target/Target.h"
14#include "lldb/Utility/RegisterValue.h"
15#include "lldb/Utility/Status.h"
16#include "lldb/Utility/StreamString.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(RHS: "false") || ref.equals_insensitive(RHS: "off") ||
27 ref.equals_insensitive(RHS: "no") || ref.equals_insensitive(RHS: "0")) {
28 return false;
29 } else if (ref.equals_insensitive(RHS: "true") || ref.equals_insensitive(RHS: "on") ||
30 ref.equals_insensitive(RHS: "yes") || ref.equals_insensitive(RHS: "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(Prefix: s))
67 return enum_value.value;
68 }
69
70 StreamString strm;
71 strm.PutCString(cstr: "invalid enumeration value, valid values are: ");
72 bool is_first = true;
73 for (const auto &enum_value : enum_values) {
74 strm.Printf(format: "%s\"%s\"",
75 is_first ? is_first = false,"" : ", ", enum_value.string_value);
76 }
77 error.SetErrorString(strm.GetString());
78 return fail_value;
79}
80
81Status OptionArgParser::ToFormat(const char *s, lldb::Format &format,
82 size_t *byte_size_ptr) {
83 format = eFormatInvalid;
84 Status error;
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(nptr: s, endptr: &format_char, base: 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
98 if (!FormatManager::GetFormatFromCString(format_cstr: s, format)) {
99 StreamString error_strm;
100 error_strm.Printf(
101 format: "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(format: f);
104 if (format_char)
105 error_strm.Printf(format: "'%c' or ", format_char);
106
107 error_strm.Printf(format: "\"%s\"", FormatManager::GetFormatAsCString(format: f));
108 error_strm.EOL();
109 }
110
111 if (byte_size_ptr)
112 error_strm.PutCString(
113 cstr: "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
125lldb::ScriptLanguage OptionArgParser::ToScriptLanguage(
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(RHS: "python"))
131 return eScriptLanguagePython;
132 if (s.equals_insensitive(RHS: "lua"))
133 return eScriptLanguageLua;
134 if (s.equals_insensitive(RHS: "default"))
135 return eScriptLanguageDefault;
136 if (s.equals_insensitive(RHS: "none"))
137 return eScriptLanguageNone;
138
139 if (success_ptr)
140 *success_ptr = false;
141 return fail_value;
142}
143
144lldb::addr_t OptionArgParser::ToRawAddress(const ExecutionContext *exe_ctx,
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: error_ptr);
149 return maybe_addr ? *maybe_addr : fail_value;
150}
151
152lldb::addr_t OptionArgParser::ToAddress(const ExecutionContext *exe_ctx,
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: 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(pc: 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
181 lldb::addr_t addr = LLDB_INVALID_ADDRESS;
182 if (!s.getAsInteger(Radix: 0, Result&: 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(Radix: 16, Result&: 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;
205 EvaluateExpressionOptions options;
206 options.SetCoerceToId(false);
207 options.SetUnwindOnError(true);
208 options.SetKeepInMemory(false);
209 options.SetTryAllThreads(true);
210
211 ExpressionResults expr_result =
212 target->EvaluateExpression(expression: s, exe_scope: exe_ctx->GetFramePtr(), result_valobj_sp&: valobj_sp, options);
213
214 bool success = false;
215 if (expr_result == eExpressionCompleted) {
216 if (valobj_sp)
217 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
218 dynValue: valobj_sp->GetDynamicValueType(), synthValue: true);
219 // Get the address to watch.
220 if (valobj_sp)
221 addr = valobj_sp->GetValueAsUnsigned(fail_value: 0, success: &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(string: sref, matches: &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(Prefix: "$")) {
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_value&: reg_val);
277 if (success && reg_val.GetType() != RegisterValue::eTypeInvalid) {
278 register_value = reg_val.GetAsUInt64(fail_value: 0, success_ptr: &success);
279 if (!success)
280 register_value.reset();
281 }
282 }
283 }
284 }
285 if (!str_offset.empty() && !str_offset.getAsInteger(Radix: 0, Result&: offset)) {
286 Status error;
287 if (register_value)
288 addr = register_value.value();
289 else
290 addr = ToAddress(exe_ctx, s: name, LLDB_INVALID_ADDRESS, error_ptr: &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}
307

source code of lldb/source/Interpreter/OptionArgParser.cpp