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/Target.h"
12#include "lldb/Utility/Status.h"
13#include "lldb/Utility/StreamString.h"
14
15using namespace lldb_private;
16using namespace lldb;
17
18bool OptionArgParser::ToBoolean(llvm::StringRef ref, bool fail_value,
19                                bool *success_ptr) {
20  if (success_ptr)
21    *success_ptr = true;
22  ref = ref.trim();
23  if (ref.equals_lower("false") || ref.equals_lower("off") ||
24      ref.equals_lower("no") || ref.equals_lower("0")) {
25    return false;
26  } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
27             ref.equals_lower("yes") || ref.equals_lower("1")) {
28    return true;
29  }
30  if (success_ptr)
31    *success_ptr = false;
32  return fail_value;
33}
34
35char OptionArgParser::ToChar(llvm::StringRef s, char fail_value,
36                             bool *success_ptr) {
37  if (success_ptr)
38    *success_ptr = false;
39  if (s.size() != 1)
40    return fail_value;
41
42  if (success_ptr)
43    *success_ptr = true;
44  return s[0];
45}
46
47int64_t OptionArgParser::ToOptionEnum(llvm::StringRef s,
48                                      const OptionEnumValues &enum_values,
49                                      int32_t fail_value, Status &error) {
50  error.Clear();
51  if (enum_values.empty()) {
52    error.SetErrorString("invalid enumeration argument");
53    return fail_value;
54  }
55
56  if (s.empty()) {
57    error.SetErrorString("empty enumeration string");
58    return fail_value;
59  }
60
61  for (const auto &enum_value : enum_values) {
62    llvm::StringRef this_enum(enum_value.string_value);
63    if (this_enum.startswith(s))
64      return enum_value.value;
65  }
66
67  StreamString strm;
68  strm.PutCString("invalid enumeration value, valid values are: ");
69  bool is_first = true;
70  for (const auto &enum_value : enum_values) {
71    strm.Printf("%s\"%s\"",
72        is_first ? is_first = false,"" : ", ", enum_value.string_value);
73  }
74  error.SetErrorString(strm.GetString());
75  return fail_value;
76}
77
78Status OptionArgParser::ToFormat(const char *s, lldb::Format &format,
79                                 size_t *byte_size_ptr) {
80  format = eFormatInvalid;
81  Status error;
82
83  if (s && s[0]) {
84    if (byte_size_ptr) {
85      if (isdigit(s[0])) {
86        char *format_char = nullptr;
87        unsigned long byte_size = ::strtoul(s, &format_char, 0);
88        if (byte_size != ULONG_MAX)
89          *byte_size_ptr = byte_size;
90        s = format_char;
91      } else
92        *byte_size_ptr = 0;
93    }
94
95    const bool partial_match_ok = true;
96    if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
97      StreamString error_strm;
98      error_strm.Printf(
99          "Invalid format character or name '%s'. Valid values are:\n", s);
100      for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
101        char format_char = FormatManager::GetFormatAsFormatChar(f);
102        if (format_char)
103          error_strm.Printf("'%c' or ", format_char);
104
105        error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
106        error_strm.EOL();
107      }
108
109      if (byte_size_ptr)
110        error_strm.PutCString(
111            "An optional byte size can precede the format character.\n");
112      error.SetErrorString(error_strm.GetString());
113    }
114
115    if (error.Fail())
116      return error;
117  } else {
118    error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
119  }
120  return error;
121}
122
123lldb::ScriptLanguage OptionArgParser::ToScriptLanguage(
124    llvm::StringRef s, lldb::ScriptLanguage fail_value, bool *success_ptr) {
125  if (success_ptr)
126    *success_ptr = true;
127
128  if (s.equals_lower("python"))
129    return eScriptLanguagePython;
130  if (s.equals_lower("lua"))
131    return eScriptLanguageLua;
132  if (s.equals_lower("default"))
133    return eScriptLanguageDefault;
134  if (s.equals_lower("none"))
135    return eScriptLanguageNone;
136
137  if (success_ptr)
138    *success_ptr = false;
139  return fail_value;
140}
141
142lldb::addr_t OptionArgParser::ToAddress(const ExecutionContext *exe_ctx,
143                                        llvm::StringRef s,
144                                        lldb::addr_t fail_value,
145                                        Status *error_ptr) {
146  bool error_set = false;
147  if (s.empty()) {
148    if (error_ptr)
149      error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
150                                          s.str().c_str());
151    return fail_value;
152  }
153
154  llvm::StringRef sref = s;
155
156  lldb::addr_t addr = LLDB_INVALID_ADDRESS;
157  if (!s.getAsInteger(0, addr)) {
158    if (error_ptr)
159      error_ptr->Clear();
160    return addr;
161  }
162
163  // Try base 16 with no prefix...
164  if (!s.getAsInteger(16, addr)) {
165    if (error_ptr)
166      error_ptr->Clear();
167    return addr;
168  }
169
170  Target *target = nullptr;
171  if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
172    if (error_ptr)
173      error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
174                                          s.str().c_str());
175    return fail_value;
176  }
177
178  lldb::ValueObjectSP valobj_sp;
179  EvaluateExpressionOptions options;
180  options.SetCoerceToId(false);
181  options.SetUnwindOnError(true);
182  options.SetKeepInMemory(false);
183  options.SetTryAllThreads(true);
184
185  ExpressionResults expr_result =
186      target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
187
188  bool success = false;
189  if (expr_result == eExpressionCompleted) {
190    if (valobj_sp)
191      valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
192          valobj_sp->GetDynamicValueType(), true);
193    // Get the address to watch.
194    if (valobj_sp)
195      addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
196    if (success) {
197      if (error_ptr)
198        error_ptr->Clear();
199      return addr;
200    } else {
201      if (error_ptr) {
202        error_set = true;
203        error_ptr->SetErrorStringWithFormat(
204            "address expression \"%s\" resulted in a value whose type "
205            "can't be converted to an address: %s",
206            s.str().c_str(), valobj_sp->GetTypeName().GetCString());
207      }
208    }
209
210  } else {
211    // Since the compiler can't handle things like "main + 12" we should try to
212    // do this for now. The compiler doesn't like adding offsets to function
213    // pointer types.
214    static RegularExpression g_symbol_plus_offset_regex(
215        "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
216
217    llvm::SmallVector<llvm::StringRef, 4> matches;
218    if (g_symbol_plus_offset_regex.Execute(sref, &matches)) {
219      uint64_t offset = 0;
220      std::string name = matches[1].str();
221      std::string sign = matches[2].str();
222      std::string str_offset = matches[3].str();
223      if (!llvm::StringRef(str_offset).getAsInteger(0, offset)) {
224        Status error;
225        addr = ToAddress(exe_ctx, name.c_str(), LLDB_INVALID_ADDRESS, &error);
226        if (addr != LLDB_INVALID_ADDRESS) {
227          if (sign[0] == '+')
228            return addr + offset;
229          else
230            return addr - offset;
231        }
232      }
233    }
234
235    if (error_ptr) {
236      error_set = true;
237      error_ptr->SetErrorStringWithFormat(
238          "address expression \"%s\" evaluation failed", s.str().c_str());
239    }
240  }
241
242  if (error_ptr) {
243    if (!error_set)
244      error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
245                                          s.str().c_str());
246  }
247  return fail_value;
248}
249