Bug Summary

File:tools/lldb/source/Interpreter/Args.cpp
Warning:line 910, column 14
Access to field 'long_option' results in a dereference of a null pointer (loaded from field 'definition')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Args.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D HAVE_ROUND -D LLDB_CONFIGURATION_RELEASE -D LLDB_USE_BUILTIN_DEMANGLER -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/lldb/source/Interpreter -I /build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/lldb/include -I /build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -I /usr/include/python2.7 -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/. -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register -Wno-vla-extension -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/lldb/source/Interpreter -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp
1//===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <cstdlib>
12// C++ Includes
13// Other libraries and framework includes
14// Project includes
15#include "lldb/DataFormatters/FormatManager.h"
16#include "lldb/Host/OptionParser.h"
17#include "lldb/Interpreter/Args.h"
18#include "lldb/Interpreter/CommandInterpreter.h"
19#include "lldb/Interpreter/CommandReturnObject.h"
20#include "lldb/Interpreter/Options.h"
21#include "lldb/Target/Target.h"
22#include "lldb/Utility/Stream.h"
23#include "lldb/Utility/StreamString.h"
24
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringSwitch.h"
28
29using namespace lldb;
30using namespace lldb_private;
31
32
33// A helper function for argument parsing.
34// Parses the initial part of the first argument using normal double quote
35// rules:
36// backslash escapes the double quote and itself. The parsed string is appended
37// to the second
38// argument. The function returns the unparsed portion of the string, starting
39// at the closing
40// quote.
41static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
42 std::string &result) {
43 // Inside double quotes, '\' and '"' are special.
44 static const char *k_escapable_characters = "\"\\";
45 while (true) {
46 // Skip over over regular characters and append them.
47 size_t regular = quoted.find_first_of(k_escapable_characters);
48 result += quoted.substr(0, regular);
49 quoted = quoted.substr(regular);
50
51 // If we have reached the end of string or the closing quote, we're done.
52 if (quoted.empty() || quoted.front() == '"')
53 break;
54
55 // We have found a backslash.
56 quoted = quoted.drop_front();
57
58 if (quoted.empty()) {
59 // A lone backslash at the end of string, let's just append it.
60 result += '\\';
61 break;
62 }
63
64 // If the character after the backslash is not a whitelisted escapable
65 // character, we
66 // leave the character sequence untouched.
67 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
68 result += '\\';
69
70 result += quoted.front();
71 quoted = quoted.drop_front();
72 }
73
74 return quoted;
75}
76
77static size_t ArgvToArgc(const char **argv) {
78 if (!argv)
79 return 0;
80 size_t count = 0;
81 while (*argv++)
82 ++count;
83 return count;
84}
85
86// A helper function for SetCommandString. Parses a single argument from the
87// command string, processing quotes and backslashes in a shell-like manner.
88// The function returns a tuple consisting of the parsed argument, the quote
89// char used, and the unparsed portion of the string starting at the first
90// unqouted, unescaped whitespace character.
91static std::tuple<std::string, char, llvm::StringRef>
92ParseSingleArgument(llvm::StringRef command) {
93 // Argument can be split into multiple discontiguous pieces, for example:
94 // "Hello ""World"
95 // this would result in a single argument "Hello World" (without the quotes)
96 // since the quotes would be removed and there is not space between the
97 // strings.
98 std::string arg;
99
100 // Since we can have multiple quotes that form a single command
101 // in a command like: "Hello "world'!' (which will make a single
102 // argument "Hello world!") we remember the first quote character
103 // we encounter and use that for the quote character.
104 char first_quote_char = '\0';
105
106 bool arg_complete = false;
107 do {
108 // Skip over over regular characters and append them.
109 size_t regular = command.find_first_of(" \t\"'`\\");
110 arg += command.substr(0, regular);
111 command = command.substr(regular);
112
113 if (command.empty())
114 break;
115
116 char special = command.front();
117 command = command.drop_front();
118 switch (special) {
119 case '\\':
120 if (command.empty()) {
121 arg += '\\';
122 break;
123 }
124
125 // If the character after the backslash is not a whitelisted escapable
126 // character, we
127 // leave the character sequence untouched.
128 if (strchr(" \t\\'\"`", command.front()) == nullptr)
129 arg += '\\';
130
131 arg += command.front();
132 command = command.drop_front();
133
134 break;
135
136 case ' ':
137 case '\t':
138 // We are not inside any quotes, we just found a space after an
139 // argument. We are done.
140 arg_complete = true;
141 break;
142
143 case '"':
144 case '\'':
145 case '`':
146 // We found the start of a quote scope.
147 if (first_quote_char == '\0')
148 first_quote_char = special;
149
150 if (special == '"')
151 command = ParseDoubleQuotes(command, arg);
152 else {
153 // For single quotes, we simply skip ahead to the matching quote
154 // character
155 // (or the end of the string).
156 size_t quoted = command.find(special);
157 arg += command.substr(0, quoted);
158 command = command.substr(quoted);
159 }
160
161 // If we found a closing quote, skip it.
162 if (!command.empty())
163 command = command.drop_front();
164
165 break;
166 }
167 } while (!arg_complete);
168
169 return std::make_tuple(arg, first_quote_char, command);
170}
171
172Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
173 size_t size = str.size();
174 ptr.reset(new char[size + 1]);
175
176 ::memcpy(data(), str.data() ? str.data() : "", size);
177 ptr[size] = 0;
178 ref = llvm::StringRef(c_str(), size);
179}
180
181//----------------------------------------------------------------------
182// Args constructor
183//----------------------------------------------------------------------
184Args::Args(llvm::StringRef command) { SetCommandString(command); }
185
186Args::Args(const Args &rhs) { *this = rhs; }
187
188Args::Args(const StringList &list) : Args() {
189 for(size_t i = 0; i < list.GetSize(); ++i)
190 AppendArgument(list[i]);
191}
192
193Args &Args::operator=(const Args &rhs) {
194 Clear();
195
196 m_argv.clear();
197 m_entries.clear();
198 for (auto &entry : rhs.m_entries) {
199 m_entries.emplace_back(entry.ref, entry.quote);
200 m_argv.push_back(m_entries.back().data());
201 }
202 m_argv.push_back(nullptr);
203 return *this;
204}
205
206//----------------------------------------------------------------------
207// Destructor
208//----------------------------------------------------------------------
209Args::~Args() {}
210
211void Args::Dump(Stream &s, const char *label_name) const {
212 if (!label_name)
213 return;
214
215 int i = 0;
216 for (auto &entry : m_entries) {
217 s.Indent();
218 s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
219 }
220 s.Format("{0}[{1}]=NULL\n", label_name, i);
221 s.EOL();
222}
223
224bool Args::GetCommandString(std::string &command) const {
225 command.clear();
226
227 for (size_t i = 0; i < m_entries.size(); ++i) {
228 if (i > 0)
229 command += ' ';
230 command += m_entries[i].ref;
231 }
232
233 return !m_entries.empty();
234}
235
236bool Args::GetQuotedCommandString(std::string &command) const {
237 command.clear();
238
239 for (size_t i = 0; i < m_entries.size(); ++i) {
240 if (i > 0)
241 command += ' ';
242
243 if (m_entries[i].quote) {
244 command += m_entries[i].quote;
245 command += m_entries[i].ref;
246 command += m_entries[i].quote;
247 } else {
248 command += m_entries[i].ref;
249 }
250 }
251
252 return !m_entries.empty();
253}
254
255void Args::SetCommandString(llvm::StringRef command) {
256 Clear();
257 m_argv.clear();
258
259 static const char *k_space_separators = " \t";
260 command = command.ltrim(k_space_separators);
261 std::string arg;
262 char quote;
263 while (!command.empty()) {
264 std::tie(arg, quote, command) = ParseSingleArgument(command);
265 m_entries.emplace_back(arg, quote);
266 m_argv.push_back(m_entries.back().data());
267 command = command.ltrim(k_space_separators);
268 }
269 m_argv.push_back(nullptr);
270}
271
272void Args::UpdateArgsAfterOptionParsing() {
273 assert(!m_argv.empty())(static_cast <bool> (!m_argv.empty()) ? void (0) : __assert_fail
("!m_argv.empty()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 273, __extension__ __PRETTY_FUNCTION__))
;
274 assert(m_argv.back() == nullptr)(static_cast <bool> (m_argv.back() == nullptr) ? void (
0) : __assert_fail ("m_argv.back() == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 274, __extension__ __PRETTY_FUNCTION__))
;
275
276 // Now m_argv might be out of date with m_entries, so we need to fix that.
277 // This happens because getopt_long_only may permute the order of the
278 // arguments in argv, so we need to re-order the quotes and the refs array
279 // to match.
280 for (size_t i = 0; i < m_argv.size() - 1; ++i) {
281 const char *argv = m_argv[i];
282 auto pos =
283 std::find_if(m_entries.begin() + i, m_entries.end(),
284 [argv](const ArgEntry &D) { return D.c_str() == argv; });
285 assert(pos != m_entries.end())(static_cast <bool> (pos != m_entries.end()) ? void (0)
: __assert_fail ("pos != m_entries.end()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 285, __extension__ __PRETTY_FUNCTION__))
;
286 size_t distance = std::distance(m_entries.begin(), pos);
287 if (i == distance)
288 continue;
289
290 assert(distance > i)(static_cast <bool> (distance > i) ? void (0) : __assert_fail
("distance > i", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 290, __extension__ __PRETTY_FUNCTION__))
;
291
292 std::swap(m_entries[i], m_entries[distance]);
293 assert(m_entries[i].ref.data() == m_argv[i])(static_cast <bool> (m_entries[i].ref.data() == m_argv[
i]) ? void (0) : __assert_fail ("m_entries[i].ref.data() == m_argv[i]"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 293, __extension__ __PRETTY_FUNCTION__))
;
294 }
295 m_entries.resize(m_argv.size() - 1);
296}
297
298size_t Args::GetArgumentCount() const { return m_entries.size(); }
299
300const char *Args::GetArgumentAtIndex(size_t idx) const {
301 if (idx < m_argv.size())
302 return m_argv[idx];
303 return nullptr;
304}
305
306char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
307 if (idx < m_entries.size())
308 return m_entries[idx].quote;
309 return '\0';
310}
311
312char **Args::GetArgumentVector() {
313 assert(!m_argv.empty())(static_cast <bool> (!m_argv.empty()) ? void (0) : __assert_fail
("!m_argv.empty()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 313, __extension__ __PRETTY_FUNCTION__))
;
314 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
315 // when argv or envp is null. So the code below is actually wrong. However,
316 // other code in LLDB depends on it being null. The code has been acting this
317 // way for some time, so it makes sense to leave it this way until someone
318 // has the time to come along and fix it.
319 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
320}
321
322const char **Args::GetConstArgumentVector() const {
323 assert(!m_argv.empty())(static_cast <bool> (!m_argv.empty()) ? void (0) : __assert_fail
("!m_argv.empty()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 323, __extension__ __PRETTY_FUNCTION__))
;
324 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
325 : nullptr;
326}
327
328void Args::Shift() {
329 // Don't pop the last NULL terminator from the argv array
330 if (m_entries.empty())
331 return;
332 m_argv.erase(m_argv.begin());
333 m_entries.erase(m_entries.begin());
334}
335
336void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
337 InsertArgumentAtIndex(0, arg_str, quote_char);
338}
339
340void Args::AppendArguments(const Args &rhs) {
341 assert(m_argv.size() == m_entries.size() + 1)(static_cast <bool> (m_argv.size() == m_entries.size() +
1) ? void (0) : __assert_fail ("m_argv.size() == m_entries.size() + 1"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 341, __extension__ __PRETTY_FUNCTION__))
;
342 assert(m_argv.back() == nullptr)(static_cast <bool> (m_argv.back() == nullptr) ? void (
0) : __assert_fail ("m_argv.back() == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 342, __extension__ __PRETTY_FUNCTION__))
;
343 m_argv.pop_back();
344 for (auto &entry : rhs.m_entries) {
345 m_entries.emplace_back(entry.ref, entry.quote);
346 m_argv.push_back(m_entries.back().data());
347 }
348 m_argv.push_back(nullptr);
349}
350
351void Args::AppendArguments(const char **argv) {
352 size_t argc = ArgvToArgc(argv);
353
354 assert(m_argv.size() == m_entries.size() + 1)(static_cast <bool> (m_argv.size() == m_entries.size() +
1) ? void (0) : __assert_fail ("m_argv.size() == m_entries.size() + 1"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 354, __extension__ __PRETTY_FUNCTION__))
;
355 assert(m_argv.back() == nullptr)(static_cast <bool> (m_argv.back() == nullptr) ? void (
0) : __assert_fail ("m_argv.back() == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 355, __extension__ __PRETTY_FUNCTION__))
;
356 m_argv.pop_back();
357 for (auto arg : llvm::makeArrayRef(argv, argc)) {
358 m_entries.emplace_back(arg, '\0');
359 m_argv.push_back(m_entries.back().data());
360 }
361
362 m_argv.push_back(nullptr);
363}
364
365void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
366 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
367}
368
369void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
370 char quote_char) {
371 assert(m_argv.size() == m_entries.size() + 1)(static_cast <bool> (m_argv.size() == m_entries.size() +
1) ? void (0) : __assert_fail ("m_argv.size() == m_entries.size() + 1"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 371, __extension__ __PRETTY_FUNCTION__))
;
372 assert(m_argv.back() == nullptr)(static_cast <bool> (m_argv.back() == nullptr) ? void (
0) : __assert_fail ("m_argv.back() == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 372, __extension__ __PRETTY_FUNCTION__))
;
373
374 if (idx > m_entries.size())
375 return;
376 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
377 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
378}
379
380void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
381 char quote_char) {
382 assert(m_argv.size() == m_entries.size() + 1)(static_cast <bool> (m_argv.size() == m_entries.size() +
1) ? void (0) : __assert_fail ("m_argv.size() == m_entries.size() + 1"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 382, __extension__ __PRETTY_FUNCTION__))
;
383 assert(m_argv.back() == nullptr)(static_cast <bool> (m_argv.back() == nullptr) ? void (
0) : __assert_fail ("m_argv.back() == nullptr", "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 383, __extension__ __PRETTY_FUNCTION__))
;
384
385 if (idx >= m_entries.size())
386 return;
387
388 if (arg_str.size() > m_entries[idx].ref.size()) {
389 m_entries[idx] = ArgEntry(arg_str, quote_char);
390 m_argv[idx] = m_entries[idx].data();
391 } else {
392 const char *src_data = arg_str.data() ? arg_str.data() : "";
393 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
394 m_entries[idx].ptr[arg_str.size()] = 0;
395 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
396 }
397}
398
399void Args::DeleteArgumentAtIndex(size_t idx) {
400 if (idx >= m_entries.size())
401 return;
402
403 m_argv.erase(m_argv.begin() + idx);
404 m_entries.erase(m_entries.begin() + idx);
405}
406
407void Args::SetArguments(size_t argc, const char **argv) {
408 Clear();
409
410 auto args = llvm::makeArrayRef(argv, argc);
411 m_entries.resize(argc);
412 m_argv.resize(argc + 1);
413 for (size_t i = 0; i < args.size(); ++i) {
414 char quote =
415 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
416 ? args[i][0]
417 : '\0';
418
419 m_entries[i] = ArgEntry(args[i], quote);
420 m_argv[i] = m_entries[i].data();
421 }
422}
423
424void Args::SetArguments(const char **argv) {
425 SetArguments(ArgvToArgc(argv), argv);
426}
427
428Status Args::ParseOptions(Options &options, ExecutionContext *execution_context,
429 PlatformSP platform_sp, bool require_validation) {
430 StreamString sstr;
431 Status error;
432 Option *long_options = options.GetLongOptions();
433 if (long_options == nullptr) {
434 error.SetErrorStringWithFormat("invalid long options");
435 return error;
436 }
437
438 for (int i = 0; long_options[i].definition != nullptr; ++i) {
439 if (long_options[i].flag == nullptr) {
440 if (isprint8(long_options[i].val)) {
441 sstr << (char)long_options[i].val;
442 switch (long_options[i].definition->option_has_arg) {
443 default:
444 case OptionParser::eNoArgument:
445 break;
446 case OptionParser::eRequiredArgument:
447 sstr << ':';
448 break;
449 case OptionParser::eOptionalArgument:
450 sstr << "::";
451 break;
452 }
453 }
454 }
455 }
456 std::unique_lock<std::mutex> lock;
457 OptionParser::Prepare(lock);
458 int val;
459 while (1) {
460 int long_options_index = -1;
461 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
462 sstr.GetString(), long_options,
463 &long_options_index);
464 if (val == -1)
465 break;
466
467 // Did we get an error?
468 if (val == '?') {
469 error.SetErrorStringWithFormat("unknown or ambiguous option");
470 break;
471 }
472 // The option auto-set itself
473 if (val == 0)
474 continue;
475
476 ((Options *)&options)->OptionSeen(val);
477
478 // Lookup the long option index
479 if (long_options_index == -1) {
480 for (int i = 0; long_options[i].definition || long_options[i].flag ||
481 long_options[i].val;
482 ++i) {
483 if (long_options[i].val == val) {
484 long_options_index = i;
485 break;
486 }
487 }
488 }
489 // Call the callback with the option
490 if (long_options_index >= 0 &&
491 long_options[long_options_index].definition) {
492 const OptionDefinition *def = long_options[long_options_index].definition;
493
494 if (!platform_sp) {
495 // User did not pass in an explicit platform. Try to grab
496 // from the execution context.
497 TargetSP target_sp =
498 execution_context ? execution_context->GetTargetSP() : TargetSP();
499 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
500 }
501 OptionValidator *validator = def->validator;
502
503 if (!platform_sp && require_validation) {
504 // Caller requires validation but we cannot validate as we
505 // don't have the mandatory platform against which to
506 // validate.
507 error.SetErrorString("cannot validate options: "
508 "no platform available");
509 return error;
510 }
511
512 bool validation_failed = false;
513 if (platform_sp) {
514 // Ensure we have an execution context, empty or not.
515 ExecutionContext dummy_context;
516 ExecutionContext *exe_ctx_p =
517 execution_context ? execution_context : &dummy_context;
518 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
519 validation_failed = true;
520 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
521 def->long_option,
522 def->validator->LongConditionString());
523 }
524 }
525
526 // As long as validation didn't fail, we set the option value.
527 if (!validation_failed)
528 error = options.SetOptionValue(
529 long_options_index,
530 (def->option_has_arg == OptionParser::eNoArgument)
531 ? nullptr
532 : OptionParser::GetOptionArgument(),
533 execution_context);
534 } else {
535 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
536 }
537 if (error.Fail())
538 break;
539 }
540
541 // Update our ARGV now that get options has consumed all the options
542 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
543 UpdateArgsAfterOptionParsing();
544 return error;
545}
546
547void Args::Clear() {
548 m_entries.clear();
549 m_argv.clear();
550 m_argv.push_back(nullptr);
551}
552
553lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
554 llvm::StringRef s, lldb::addr_t fail_value,
555 Status *error_ptr) {
556 bool error_set = false;
557 if (s.empty()) {
558 if (error_ptr)
559 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
560 s.str().c_str());
561 return fail_value;
562 }
563
564 llvm::StringRef sref = s;
565
566 lldb::addr_t addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
567 if (!s.getAsInteger(0, addr)) {
568 if (error_ptr)
569 error_ptr->Clear();
570 return addr;
571 }
572
573 // Try base 16 with no prefix...
574 if (!s.getAsInteger(16, addr)) {
575 if (error_ptr)
576 error_ptr->Clear();
577 return addr;
578 }
579
580 Target *target = nullptr;
581 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
582 if (error_ptr)
583 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
584 s.str().c_str());
585 return fail_value;
586 }
587
588 lldb::ValueObjectSP valobj_sp;
589 EvaluateExpressionOptions options;
590 options.SetCoerceToId(false);
591 options.SetUnwindOnError(true);
592 options.SetKeepInMemory(false);
593 options.SetTryAllThreads(true);
594
595 ExpressionResults expr_result =
596 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
597
598 bool success = false;
599 if (expr_result == eExpressionCompleted) {
600 if (valobj_sp)
601 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
602 valobj_sp->GetDynamicValueType(), true);
603 // Get the address to watch.
604 if (valobj_sp)
605 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
606 if (success) {
607 if (error_ptr)
608 error_ptr->Clear();
609 return addr;
610 } else {
611 if (error_ptr) {
612 error_set = true;
613 error_ptr->SetErrorStringWithFormat(
614 "address expression \"%s\" resulted in a value whose type "
615 "can't be converted to an address: %s",
616 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
617 }
618 }
619
620 } else {
621 // Since the compiler can't handle things like "main + 12" we should
622 // try to do this for now. The compiler doesn't like adding offsets
623 // to function pointer types.
624 static RegularExpression g_symbol_plus_offset_regex(
625 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
626 RegularExpression::Match regex_match(3);
627 if (g_symbol_plus_offset_regex.Execute(sref, &regex_match)) {
628 uint64_t offset = 0;
629 bool add = true;
630 std::string name;
631 std::string str;
632 if (regex_match.GetMatchAtIndex(s, 1, name)) {
633 if (regex_match.GetMatchAtIndex(s, 2, str)) {
634 add = str[0] == '+';
635
636 if (regex_match.GetMatchAtIndex(s, 3, str)) {
637 if (!llvm::StringRef(str).getAsInteger(0, offset)) {
638 Status error;
639 addr = StringToAddress(exe_ctx, name.c_str(),
640 LLDB_INVALID_ADDRESS(18446744073709551615UL), &error);
641 if (addr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
642 if (add)
643 return addr + offset;
644 else
645 return addr - offset;
646 }
647 }
648 }
649 }
650 }
651 }
652
653 if (error_ptr) {
654 error_set = true;
655 error_ptr->SetErrorStringWithFormat(
656 "address expression \"%s\" evaluation failed", s.str().c_str());
657 }
658 }
659
660 if (error_ptr) {
661 if (!error_set)
662 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
663 s.str().c_str());
664 }
665 return fail_value;
666}
667
668const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
669 bool return_null_if_empty) {
670 static const char *k_white_space = " \t\v";
671 if (!s.empty()) {
672 if (leading) {
673 size_t pos = s.find_first_not_of(k_white_space);
674 if (pos == std::string::npos)
675 s.clear();
676 else if (pos > 0)
677 s.erase(0, pos);
678 }
679
680 if (trailing) {
681 size_t rpos = s.find_last_not_of(k_white_space);
682 if (rpos != std::string::npos && rpos + 1 < s.size())
683 s.erase(rpos + 1);
684 }
685 }
686 if (return_null_if_empty && s.empty())
687 return nullptr;
688 return s.c_str();
689}
690
691bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
692 bool *success_ptr) {
693 if (success_ptr)
694 *success_ptr = true;
695 ref = ref.trim();
696 if (ref.equals_lower("false") || ref.equals_lower("off") ||
697 ref.equals_lower("no") || ref.equals_lower("0")) {
698 return false;
699 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
700 ref.equals_lower("yes") || ref.equals_lower("1")) {
701 return true;
702 }
703 if (success_ptr)
704 *success_ptr = false;
705 return fail_value;
706}
707
708char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
709 if (success_ptr)
710 *success_ptr = false;
711 if (s.size() != 1)
712 return fail_value;
713
714 if (success_ptr)
715 *success_ptr = true;
716 return s[0];
717}
718
719bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
720 uint32_t &minor, uint32_t &update) {
721 major = UINT32_MAX(4294967295U);
722 minor = UINT32_MAX(4294967295U);
723 update = UINT32_MAX(4294967295U);
724
725 if (string.empty())
726 return false;
727
728 llvm::StringRef major_str, minor_str, update_str;
729
730 std::tie(major_str, minor_str) = string.split('.');
731 std::tie(minor_str, update_str) = minor_str.split('.');
732 if (major_str.getAsInteger(10, major))
733 return false;
734 if (!minor_str.empty() && minor_str.getAsInteger(10, minor))
735 return false;
736 if (!update_str.empty() && update_str.getAsInteger(10, update))
737 return false;
738
739 return true;
740}
741
742const char *Args::GetShellSafeArgument(const FileSpec &shell,
743 const char *unsafe_arg,
744 std::string &safe_arg) {
745 struct ShellDescriptor {
746 ConstString m_basename;
747 const char *m_escapables;
748 };
749
750 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
751 {ConstString("tcsh"), " '\"<>()&$"},
752 {ConstString("sh"), " '\"<>()&"}};
753
754 // safe minimal set
755 const char *escapables = " '\"";
756
757 if (auto basename = shell.GetFilename()) {
758 for (const auto &Shell : g_Shells) {
759 if (Shell.m_basename == basename) {
760 escapables = Shell.m_escapables;
761 break;
762 }
763 }
764 }
765
766 safe_arg.assign(unsafe_arg);
767 size_t prev_pos = 0;
768 while (prev_pos < safe_arg.size()) {
769 // Escape spaces and quotes
770 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
771 if (pos != std::string::npos) {
772 safe_arg.insert(pos, 1, '\\');
773 prev_pos = pos + 2;
774 } else
775 break;
776 }
777 return safe_arg.c_str();
778}
779
780int64_t Args::StringToOptionEnum(llvm::StringRef s,
781 OptionEnumValueElement *enum_values,
782 int32_t fail_value, Status &error) {
783 error.Clear();
784 if (!enum_values) {
785 error.SetErrorString("invalid enumeration argument");
786 return fail_value;
787 }
788
789 if (s.empty()) {
790 error.SetErrorString("empty enumeration string");
791 return fail_value;
792 }
793
794 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
795 llvm::StringRef this_enum(enum_values[i].string_value);
796 if (this_enum.startswith(s))
797 return enum_values[i].value;
798 }
799
800 StreamString strm;
801 strm.PutCString("invalid enumeration value, valid values are: ");
802 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
803 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
804 }
805 error.SetErrorString(strm.GetString());
806 return fail_value;
807}
808
809lldb::ScriptLanguage
810Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
811 bool *success_ptr) {
812 if (success_ptr)
813 *success_ptr = true;
814
815 if (s.equals_lower("python"))
816 return eScriptLanguagePython;
817 if (s.equals_lower("default"))
818 return eScriptLanguageDefault;
819 if (s.equals_lower("none"))
820 return eScriptLanguageNone;
821
822 if (success_ptr)
823 *success_ptr = false;
824 return fail_value;
825}
826
827Status Args::StringToFormat(const char *s, lldb::Format &format,
828 size_t *byte_size_ptr) {
829 format = eFormatInvalid;
830 Status error;
831
832 if (s && s[0]) {
833 if (byte_size_ptr) {
834 if (isdigit(s[0])) {
835 char *format_char = nullptr;
836 unsigned long byte_size = ::strtoul(s, &format_char, 0);
837 if (byte_size != ULONG_MAX(9223372036854775807L *2UL+1UL))
838 *byte_size_ptr = byte_size;
839 s = format_char;
840 } else
841 *byte_size_ptr = 0;
842 }
843
844 const bool partial_match_ok = true;
845 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
846 StreamString error_strm;
847 error_strm.Printf(
848 "Invalid format character or name '%s'. Valid values are:\n", s);
849 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
850 char format_char = FormatManager::GetFormatAsFormatChar(f);
851 if (format_char)
852 error_strm.Printf("'%c' or ", format_char);
853
854 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
855 error_strm.EOL();
856 }
857
858 if (byte_size_ptr)
859 error_strm.PutCString(
860 "An optional byte size can precede the format character.\n");
861 error.SetErrorString(error_strm.GetString());
862 }
863
864 if (error.Fail())
865 return error;
866 } else {
867 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
868 }
869 return error;
870}
871
872lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
873 lldb::Encoding fail_value) {
874 return llvm::StringSwitch<lldb::Encoding>(s)
875 .Case("uint", eEncodingUint)
876 .Case("sint", eEncodingSint)
877 .Case("ieee754", eEncodingIEEE754)
878 .Case("vector", eEncodingVector)
879 .Default(fail_value);
880}
881
882uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
883 if (s.empty())
884 return LLDB_INVALID_REGNUM(4294967295U);
885 uint32_t result = llvm::StringSwitch<uint32_t>(s)
886 .Case("pc", LLDB_REGNUM_GENERIC_PC0)
887 .Case("sp", LLDB_REGNUM_GENERIC_SP1)
888 .Case("fp", LLDB_REGNUM_GENERIC_FP2)
889 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA3)
890 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS4)
891 .Case("arg1", LLDB_REGNUM_GENERIC_ARG15)
892 .Case("arg2", LLDB_REGNUM_GENERIC_ARG26)
893 .Case("arg3", LLDB_REGNUM_GENERIC_ARG37)
894 .Case("arg4", LLDB_REGNUM_GENERIC_ARG48)
895 .Case("arg5", LLDB_REGNUM_GENERIC_ARG59)
896 .Case("arg6", LLDB_REGNUM_GENERIC_ARG610)
897 .Case("arg7", LLDB_REGNUM_GENERIC_ARG711)
898 .Case("arg8", LLDB_REGNUM_GENERIC_ARG812)
899 .Default(LLDB_INVALID_REGNUM(4294967295U));
900 return result;
901}
902
903size_t Args::FindArgumentIndexForOption(Option *long_options,
904 int long_options_index) const {
905 char short_buffer[3];
906 char long_buffer[255];
907 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
908 long_options[long_options_index].val);
909 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
910 long_options[long_options_index].definition->long_option);
21
Access to field 'long_option' results in a dereference of a null pointer (loaded from field 'definition')
911
912 for (auto entry : llvm::enumerate(m_entries)) {
913 if (entry.value().ref.startswith(short_buffer) ||
914 entry.value().ref.startswith(long_buffer))
915 return entry.index();
916 }
917
918 return size_t(-1);
919}
920
921bool Args::IsPositionalArgument(const char *arg) {
922 if (arg == nullptr)
923 return false;
924
925 bool is_positional = true;
926 const char *cptr = arg;
927
928 if (cptr[0] == '%') {
929 ++cptr;
930 while (isdigit(cptr[0]))
931 ++cptr;
932 if (cptr[0] != '\0')
933 is_positional = false;
934 } else
935 is_positional = false;
936
937 return is_positional;
938}
939
940std::string Args::ParseAliasOptions(Options &options,
941 CommandReturnObject &result,
942 OptionArgVector *option_arg_vector,
943 llvm::StringRef raw_input_string) {
944 std::string result_string(raw_input_string);
945 StreamString sstr;
946 int i;
947 Option *long_options = options.GetLongOptions();
948
949 if (long_options == nullptr) {
1
Assuming the condition is false
2
Taking false branch
950 result.AppendError("invalid long options");
951 result.SetStatus(eReturnStatusFailed);
952 return result_string;
953 }
954
955 for (i = 0; long_options[i].definition != nullptr; ++i) {
3
Assuming the condition is false
4
Loop condition is false. Execution continues on line 972
956 if (long_options[i].flag == nullptr) {
957 sstr << (char)long_options[i].val;
958 switch (long_options[i].definition->option_has_arg) {
959 default:
960 case OptionParser::eNoArgument:
961 break;
962 case OptionParser::eRequiredArgument:
963 sstr << ":";
964 break;
965 case OptionParser::eOptionalArgument:
966 sstr << "::";
967 break;
968 }
969 }
970 }
971
972 std::unique_lock<std::mutex> lock;
973 OptionParser::Prepare(lock);
974 result.SetStatus(eReturnStatusSuccessFinishNoResult);
975 int val;
976 while (1) {
5
Loop condition is true. Entering loop body
977 int long_options_index = -1;
978 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
979 sstr.GetString(), long_options,
980 &long_options_index);
981
982 if (val == -1)
6
Assuming the condition is false
7
Taking false branch
983 break;
984
985 if (val == '?') {
8
Assuming the condition is false
9
Taking false branch
986 result.AppendError("unknown or ambiguous option");
987 result.SetStatus(eReturnStatusFailed);
988 break;
989 }
990
991 if (val == 0)
10
Assuming 'val' is not equal to 0
11
Taking false branch
992 continue;
993
994 options.OptionSeen(val);
995
996 // Look up the long option index
997 if (long_options_index == -1) {
12
Assuming the condition is false
13
Taking false branch
998 for (int j = 0; long_options[j].definition || long_options[j].flag ||
999 long_options[j].val;
1000 ++j) {
1001 if (long_options[j].val == val) {
1002 long_options_index = j;
1003 break;
1004 }
1005 }
1006 }
1007
1008 // See if the option takes an argument, and see if one was supplied.
1009 if (long_options_index == -1) {
14
Taking false branch
1010 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1011 result.SetStatus(eReturnStatusFailed);
1012 return result_string;
1013 }
1014
1015 StreamString option_str;
1016 option_str.Printf("-%c", val);
1017 const OptionDefinition *def = long_options[long_options_index].definition;
1018 int has_arg =
1019 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
15
Assuming pointer value is null
16
'?' condition is true
1020
1021 const char *option_arg = nullptr;
1022 switch (has_arg) {
17
Control jumps to 'case eNoArgument:' at line 1035
1023 case OptionParser::eRequiredArgument:
1024 if (OptionParser::GetOptionArgument() == nullptr) {
1025 result.AppendErrorWithFormat(
1026 "Option '%s' is missing argument specifier.\n",
1027 option_str.GetData());
1028 result.SetStatus(eReturnStatusFailed);
1029 return result_string;
1030 }
1031 LLVM_FALLTHROUGH[[clang::fallthrough]];
1032 case OptionParser::eOptionalArgument:
1033 option_arg = OptionParser::GetOptionArgument();
1034 LLVM_FALLTHROUGH[[clang::fallthrough]];
1035 case OptionParser::eNoArgument:
1036 break;
18
Execution continues on line 1044
1037 default:
1038 result.AppendErrorWithFormat("error with options table; invalid value "
1039 "in has_arg field for option '%c'.\n",
1040 val);
1041 result.SetStatus(eReturnStatusFailed);
1042 return result_string;
1043 }
1044 if (!option_arg)
19
Taking true branch
1045 option_arg = "<no-argument>";
1046 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1047 option_arg);
1048
1049 // Find option in the argument list; also see if it was supposed to take
1050 // an argument and if one was supplied. Remove option (and argument, if
1051 // given) from the argument list. Also remove them from the
1052 // raw_input_string, if one was passed in.
1053 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
20
Calling 'Args::FindArgumentIndexForOption'
1054 if (idx == size_t(-1))
1055 continue;
1056
1057 if (!result_string.empty()) {
1058 auto tmp_arg = m_entries[idx].ref;
1059 size_t pos = result_string.find(tmp_arg);
1060 if (pos != std::string::npos)
1061 result_string.erase(pos, tmp_arg.size());
1062 }
1063 ReplaceArgumentAtIndex(idx, llvm::StringRef());
1064 if ((long_options[long_options_index].definition->option_has_arg !=
1065 OptionParser::eNoArgument) &&
1066 (OptionParser::GetOptionArgument() != nullptr) &&
1067 (idx + 1 < GetArgumentCount()) &&
1068 (m_entries[idx + 1].ref == OptionParser::GetOptionArgument())) {
1069 if (result_string.size() > 0) {
1070 auto tmp_arg = m_entries[idx + 1].ref;
1071 size_t pos = result_string.find(tmp_arg);
1072 if (pos != std::string::npos)
1073 result_string.erase(pos, tmp_arg.size());
1074 }
1075 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
1076 }
1077 }
1078 return result_string;
1079}
1080
1081void Args::ParseArgsForCompletion(Options &options,
1082 OptionElementVector &option_element_vector,
1083 uint32_t cursor_index) {
1084 StreamString sstr;
1085 Option *long_options = options.GetLongOptions();
1086 option_element_vector.clear();
1087
1088 if (long_options == nullptr) {
1089 return;
1090 }
1091
1092 // Leading : tells getopt to return a : for a missing option argument AND
1093 // to suppress error messages.
1094
1095 sstr << ":";
1096 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1097 if (long_options[i].flag == nullptr) {
1098 sstr << (char)long_options[i].val;
1099 switch (long_options[i].definition->option_has_arg) {
1100 default:
1101 case OptionParser::eNoArgument:
1102 break;
1103 case OptionParser::eRequiredArgument:
1104 sstr << ":";
1105 break;
1106 case OptionParser::eOptionalArgument:
1107 sstr << "::";
1108 break;
1109 }
1110 }
1111 }
1112
1113 std::unique_lock<std::mutex> lock;
1114 OptionParser::Prepare(lock);
1115 OptionParser::EnableError(false);
1116
1117 int val;
1118 auto opt_defs = options.GetDefinitions();
1119
1120 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
1121 // options to the front. So we have to build another Arg and pass that to
1122 // OptionParser::Parse so it doesn't change the one we have.
1123
1124 std::vector<char *> dummy_vec = m_argv;
1125
1126 bool failed_once = false;
1127 uint32_t dash_dash_pos = -1;
1128
1129 while (1) {
1130 bool missing_argument = false;
1131 int long_options_index = -1;
1132
1133 val = OptionParser::Parse(dummy_vec.size() - 1, &dummy_vec[0],
1134 sstr.GetString(), long_options,
1135 &long_options_index);
1136
1137 if (val == -1) {
1138 // When we're completing a "--" which is the last option on line,
1139 if (failed_once)
1140 break;
1141
1142 failed_once = true;
1143
1144 // If this is a bare "--" we mark it as such so we can complete it
1145 // successfully later.
1146 // Handling the "--" is a little tricky, since that may mean end of
1147 // options or arguments, or the
1148 // user might want to complete options by long name. I make this work by
1149 // checking whether the
1150 // cursor is in the "--" argument, and if so I assume we're completing the
1151 // long option, otherwise
1152 // I let it pass to OptionParser::Parse which will terminate the option
1153 // parsing.
1154 // Note, in either case we continue parsing the line so we can figure out
1155 // what other options
1156 // were passed. This will be useful when we come to restricting
1157 // completions based on what other
1158 // options we've seen on the line.
1159
1160 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1161 dummy_vec.size() - 1 &&
1162 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1163 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1164 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1165 cursor_index) {
1166 option_element_vector.push_back(
1167 OptionArgElement(OptionArgElement::eBareDoubleDash,
1168 OptionParser::GetOptionIndex() - 1,
1169 OptionArgElement::eBareDoubleDash));
1170 continue;
1171 } else
1172 break;
1173 } else
1174 break;
1175 } else if (val == '?') {
1176 option_element_vector.push_back(
1177 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1178 OptionParser::GetOptionIndex() - 1,
1179 OptionArgElement::eUnrecognizedArg));
1180 continue;
1181 } else if (val == 0) {
1182 continue;
1183 } else if (val == ':') {
1184 // This is a missing argument.
1185 val = OptionParser::GetOptionErrorCause();
1186 missing_argument = true;
1187 }
1188
1189 ((Options *)&options)->OptionSeen(val);
1190
1191 // Look up the long option index
1192 if (long_options_index == -1) {
1193 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1194 long_options[j].val;
1195 ++j) {
1196 if (long_options[j].val == val) {
1197 long_options_index = j;
1198 break;
1199 }
1200 }
1201 }
1202
1203 // See if the option takes an argument, and see if one was supplied.
1204 if (long_options_index >= 0) {
1205 int opt_defs_index = -1;
1206 for (size_t i = 0; i < opt_defs.size(); i++) {
1207 if (opt_defs[i].short_option != val)
1208 continue;
1209 opt_defs_index = i;
1210 break;
1211 }
1212
1213 const OptionDefinition *def = long_options[long_options_index].definition;
1214 int has_arg =
1215 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1216 switch (has_arg) {
1217 case OptionParser::eNoArgument:
1218 option_element_vector.push_back(OptionArgElement(
1219 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1220 break;
1221 case OptionParser::eRequiredArgument:
1222 if (OptionParser::GetOptionArgument() != nullptr) {
1223 int arg_index;
1224 if (missing_argument)
1225 arg_index = -1;
1226 else
1227 arg_index = OptionParser::GetOptionIndex() - 1;
1228
1229 option_element_vector.push_back(OptionArgElement(
1230 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1231 } else {
1232 option_element_vector.push_back(OptionArgElement(
1233 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1234 }
1235 break;
1236 case OptionParser::eOptionalArgument:
1237 if (OptionParser::GetOptionArgument() != nullptr) {
1238 option_element_vector.push_back(OptionArgElement(
1239 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1240 OptionParser::GetOptionIndex() - 1));
1241 } else {
1242 option_element_vector.push_back(OptionArgElement(
1243 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1244 OptionParser::GetOptionIndex() - 1));
1245 }
1246 break;
1247 default:
1248 // The options table is messed up. Here we'll just continue
1249 option_element_vector.push_back(
1250 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1251 OptionParser::GetOptionIndex() - 1,
1252 OptionArgElement::eUnrecognizedArg));
1253 break;
1254 }
1255 } else {
1256 option_element_vector.push_back(
1257 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1258 OptionParser::GetOptionIndex() - 1,
1259 OptionArgElement::eUnrecognizedArg));
1260 }
1261 }
1262
1263 // Finally we have to handle the case where the cursor index points at a
1264 // single "-". We want to mark that in
1265 // the option_element_vector, but only if it is not after the "--". But it
1266 // turns out that OptionParser::Parse just ignores
1267 // an isolated "-". So we have to look it up by hand here. We only care if
1268 // it is AT the cursor position.
1269 // Note, a single quoted dash is not the same as a single dash...
1270
1271 const ArgEntry &cursor = m_entries[cursor_index];
1272 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1273 cursor_index < dash_dash_pos) &&
1274 cursor.quote == '\0' && cursor.ref == "-") {
1275 option_element_vector.push_back(
1276 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1277 OptionArgElement::eBareDash));
1278 }
1279}
1280
1281void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1282 dst.clear();
1283 if (src) {
1284 for (const char *p = src; *p != '\0'; ++p) {
1285 size_t non_special_chars = ::strcspn(p, "\\");
1286 if (non_special_chars > 0) {
1287 dst.append(p, non_special_chars);
1288 p += non_special_chars;
1289 if (*p == '\0')
1290 break;
1291 }
1292
1293 if (*p == '\\') {
1294 ++p; // skip the slash
1295 switch (*p) {
1296 case 'a':
1297 dst.append(1, '\a');
1298 break;
1299 case 'b':
1300 dst.append(1, '\b');
1301 break;
1302 case 'f':
1303 dst.append(1, '\f');
1304 break;
1305 case 'n':
1306 dst.append(1, '\n');
1307 break;
1308 case 'r':
1309 dst.append(1, '\r');
1310 break;
1311 case 't':
1312 dst.append(1, '\t');
1313 break;
1314 case 'v':
1315 dst.append(1, '\v');
1316 break;
1317 case '\\':
1318 dst.append(1, '\\');
1319 break;
1320 case '\'':
1321 dst.append(1, '\'');
1322 break;
1323 case '"':
1324 dst.append(1, '"');
1325 break;
1326 case '0':
1327 // 1 to 3 octal chars
1328 {
1329 // Make a string that can hold onto the initial zero char,
1330 // up to 3 octal digits, and a terminating NULL.
1331 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1332
1333 int i;
1334 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1335 oct_str[i] = p[i];
1336
1337 // We don't want to consume the last octal character since
1338 // the main for loop will do this for us, so we advance p by
1339 // one less than i (even if i is zero)
1340 p += i - 1;
1341 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1342 if (octal_value <= UINT8_MAX(255)) {
1343 dst.append(1, (char)octal_value);
1344 }
1345 }
1346 break;
1347
1348 case 'x':
1349 // hex number in the format
1350 if (isxdigit(p[1])) {
1351 ++p; // Skip the 'x'
1352
1353 // Make a string that can hold onto two hex chars plus a
1354 // NULL terminator
1355 char hex_str[3] = {*p, '\0', '\0'};
1356 if (isxdigit(p[1])) {
1357 ++p; // Skip the first of the two hex chars
1358 hex_str[1] = *p;
1359 }
1360
1361 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1362 if (hex_value <= UINT8_MAX(255))
1363 dst.append(1, (char)hex_value);
1364 } else {
1365 dst.append(1, 'x');
1366 }
1367 break;
1368
1369 default:
1370 // Just desensitize any other character by just printing what
1371 // came after the '\'
1372 dst.append(1, *p);
1373 break;
1374 }
1375 }
1376 }
1377 }
1378}
1379
1380void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1381 dst.clear();
1382 if (src) {
1383 for (const char *p = src; *p != '\0'; ++p) {
1384 if (isprint8(*p))
1385 dst.append(1, *p);
1386 else {
1387 switch (*p) {
1388 case '\a':
1389 dst.append("\\a");
1390 break;
1391 case '\b':
1392 dst.append("\\b");
1393 break;
1394 case '\f':
1395 dst.append("\\f");
1396 break;
1397 case '\n':
1398 dst.append("\\n");
1399 break;
1400 case '\r':
1401 dst.append("\\r");
1402 break;
1403 case '\t':
1404 dst.append("\\t");
1405 break;
1406 case '\v':
1407 dst.append("\\v");
1408 break;
1409 case '\'':
1410 dst.append("\\'");
1411 break;
1412 case '"':
1413 dst.append("\\\"");
1414 break;
1415 case '\\':
1416 dst.append("\\\\");
1417 break;
1418 default: {
1419 // Just encode as octal
1420 dst.append("\\0");
1421 char octal_str[32];
1422 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1423 dst.append(octal_str);
1424 } break;
1425 }
1426 }
1427 }
1428 }
1429}
1430
1431std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1432 char quote_char) {
1433 const char *chars_to_escape = nullptr;
1434 switch (quote_char) {
1435 case '\0':
1436 chars_to_escape = " \t\\'\"`";
1437 break;
1438 case '\'':
1439 chars_to_escape = "";
1440 break;
1441 case '"':
1442 chars_to_escape = "$\"`\\";
1443 break;
1444 default:
1445 assert(false && "Unhandled quote character")(static_cast <bool> (false && "Unhandled quote character"
) ? void (0) : __assert_fail ("false && \"Unhandled quote character\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/lldb/source/Interpreter/Args.cpp"
, 1445, __extension__ __PRETTY_FUNCTION__))
;
1446 }
1447
1448 std::string res;
1449 res.reserve(arg.size());
1450 for (char c : arg) {
1451 if (::strchr(chars_to_escape, c))
1452 res.push_back('\\');
1453 res.push_back(c);
1454 }
1455 return res;
1456}