blob: 5fe6a22b94ec8fdf4ca0ea933c487e90adcba71d [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Eli Friedman5661f922010-06-09 10:59:23 +000011#include <cstdlib>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C++ Includes
13// Other libraries and framework includes
14// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015#include "lldb/Core/Stream.h"
16#include "lldb/Core/StreamFile.h"
17#include "lldb/Core/StreamString.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000018#include "lldb/DataFormatters/FormatManager.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000019#include "lldb/Host/StringConvert.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "lldb/Interpreter/Args.h"
Zachary Turnerd37221d2014-07-09 16:31:49 +000021#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Interpreter/CommandReturnObject.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000023#include "lldb/Interpreter/Options.h"
Greg Claytonb9d5df52012-12-06 22:49:16 +000024#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000025#include "lldb/Target/StackFrame.h"
Greg Claytonb9d5df52012-12-06 22:49:16 +000026#include "lldb/Target/Target.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Zachary Turner691405b2016-10-03 22:51:09 +000028#include "llvm/ADT/StringExtras.h"
Zachary Turner54695a32016-08-29 19:58:14 +000029#include "llvm/ADT/StringSwitch.h"
30
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031using namespace lldb;
32using namespace lldb_private;
33
Caroline Tice2d5289d2010-12-10 00:26:54 +000034
Pavel Labath00b7f952015-03-02 12:46:22 +000035// A helper function for argument parsing.
Kate Stoneb9c1b512016-09-06 20:57:50 +000036// Parses the initial part of the first argument using normal double quote
37// rules:
38// backslash escapes the double quote and itself. The parsed string is appended
39// to the second
40// argument. The function returns the unparsed portion of the string, starting
41// at the closing
Pavel Labath00b7f952015-03-02 12:46:22 +000042// quote.
Kate Stoneb9c1b512016-09-06 20:57:50 +000043static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
44 std::string &result) {
45 // Inside double quotes, '\' and '"' are special.
46 static const char *k_escapable_characters = "\"\\";
47 while (true) {
48 // Skip over over regular characters and append them.
49 size_t regular = quoted.find_first_of(k_escapable_characters);
50 result += quoted.substr(0, regular);
51 quoted = quoted.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22 +000052
Kate Stoneb9c1b512016-09-06 20:57:50 +000053 // If we have reached the end of string or the closing quote, we're done.
54 if (quoted.empty() || quoted.front() == '"')
55 break;
Pavel Labath00b7f952015-03-02 12:46:22 +000056
Kate Stoneb9c1b512016-09-06 20:57:50 +000057 // We have found a backslash.
58 quoted = quoted.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22 +000059
Kate Stoneb9c1b512016-09-06 20:57:50 +000060 if (quoted.empty()) {
61 // A lone backslash at the end of string, let's just append it.
62 result += '\\';
63 break;
Pavel Labath00b7f952015-03-02 12:46:22 +000064 }
65
Kate Stoneb9c1b512016-09-06 20:57:50 +000066 // If the character after the backslash is not a whitelisted escapable
67 // character, we
68 // leave the character sequence untouched.
69 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
70 result += '\\';
71
72 result += quoted.front();
73 quoted = quoted.drop_front();
74 }
75
76 return quoted;
Pavel Labath00b7f952015-03-02 12:46:22 +000077}
78
Zachary Turner691405b2016-10-03 22:51:09 +000079static size_t ArgvToArgc(const char **argv) {
80 if (!argv)
81 return 0;
82 size_t count = 0;
83 while (*argv++)
84 ++count;
85 return count;
86}
Pavel Labath00b7f952015-03-02 12:46:22 +000087
Zachary Turner691405b2016-10-03 22:51:09 +000088// A helper function for SetCommandString. Parses a single argument from the
89// command string, processing quotes and backslashes in a shell-like manner.
90// The function returns a tuple consisting of the parsed argument, the quote
91// char used, and the unparsed portion of the string starting at the first
92// unqouted, unescaped whitespace character.
93static std::tuple<std::string, char, llvm::StringRef>
94ParseSingleArgument(llvm::StringRef command) {
95 // Argument can be split into multiple discontiguous pieces, for example:
96 // "Hello ""World"
97 // this would result in a single argument "Hello World" (without the quotes)
98 // since the quotes would be removed and there is not space between the
99 // strings.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 std::string arg;
Pavel Labath00b7f952015-03-02 12:46:22 +0000101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 // Since we can have multiple quotes that form a single command
103 // in a command like: "Hello "world'!' (which will make a single
104 // argument "Hello world!") we remember the first quote character
105 // we encounter and use that for the quote character.
106 char first_quote_char = '\0';
Pavel Labath00b7f952015-03-02 12:46:22 +0000107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108 bool arg_complete = false;
109 do {
110 // Skip over over regular characters and append them.
111 size_t regular = command.find_first_of(" \t\"'`\\");
112 arg += command.substr(0, regular);
113 command = command.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22 +0000114
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 if (command.empty())
116 break;
Pavel Labath00b7f952015-03-02 12:46:22 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 char special = command.front();
119 command = command.drop_front();
120 switch (special) {
121 case '\\':
122 if (command.empty()) {
123 arg += '\\';
124 break;
125 }
126
127 // If the character after the backslash is not a whitelisted escapable
128 // character, we
129 // leave the character sequence untouched.
130 if (strchr(" \t\\'\"`", command.front()) == nullptr)
131 arg += '\\';
132
133 arg += command.front();
134 command = command.drop_front();
135
136 break;
137
138 case ' ':
139 case '\t':
140 // We are not inside any quotes, we just found a space after an
141 // argument. We are done.
142 arg_complete = true;
143 break;
144
145 case '"':
146 case '\'':
147 case '`':
148 // We found the start of a quote scope.
149 if (first_quote_char == '\0')
150 first_quote_char = special;
151
152 if (special == '"')
153 command = ParseDoubleQuotes(command, arg);
154 else {
155 // For single quotes, we simply skip ahead to the matching quote
156 // character
157 // (or the end of the string).
158 size_t quoted = command.find(special);
159 arg += command.substr(0, quoted);
160 command = command.substr(quoted);
161 }
162
163 // If we found a closing quote, skip it.
164 if (!command.empty())
Pavel Labath00b7f952015-03-02 12:46:22 +0000165 command = command.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22 +0000166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 break;
168 }
169 } while (!arg_complete);
Pavel Labath00b7f952015-03-02 12:46:22 +0000170
Zachary Turner691405b2016-10-03 22:51:09 +0000171 return std::make_tuple(arg, first_quote_char, command);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000172}
173
Zachary Turner691405b2016-10-03 22:51:09 +0000174Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
175 size_t size = str.size();
176 ptr.reset(new char[size + 1]);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000177
Zachary Turner691405b2016-10-03 22:51:09 +0000178 ::memcpy(data(), str.data() ? str.data() : "", size);
179 ptr[size] = 0;
180 ref = llvm::StringRef(c_str(), size);
181}
182
183//----------------------------------------------------------------------
184// Args constructor
185//----------------------------------------------------------------------
186Args::Args(llvm::StringRef command) { SetCommandString(command); }
187
188Args::Args(const Args &rhs) { *this = rhs; }
189
190Args &Args::operator=(const Args &rhs) {
191 Clear();
192
193 m_argv.clear();
194 m_entries.clear();
195 for (auto &entry : rhs.m_entries) {
196 m_entries.emplace_back(entry.ref, entry.quote);
197 m_argv.push_back(m_entries.back().data());
198 }
199 m_argv.push_back(nullptr);
200 return *this;
201}
202
203//----------------------------------------------------------------------
204// Destructor
205//----------------------------------------------------------------------
206Args::~Args() {}
207
208void Args::Dump(Stream &s, const char *label_name) const {
209 if (!label_name)
210 return;
211
212 int i = 0;
213 for (auto &entry : m_entries) {
214 s.Indent();
215 s.Printf("%s[%zi]=\"%*s\"\n", label_name, i++, entry.ref.size(),
216 entry.ref.data());
217 }
218 s.Printf("%s[%zi]=NULL\n", label_name, i);
219 s.EOL();
220}
221
222bool Args::GetCommandString(std::string &command) const {
223 command.clear();
224
225 for (size_t i = 0; i < m_entries.size(); ++i) {
226 if (i > 0)
227 command += ' ';
228 command += m_entries[i].ref;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 }
230
Zachary Turner691405b2016-10-03 22:51:09 +0000231 return !m_entries.empty();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232}
233
Zachary Turner691405b2016-10-03 22:51:09 +0000234bool Args::GetQuotedCommandString(std::string &command) const {
235 command.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236
Zachary Turner691405b2016-10-03 22:51:09 +0000237 for (size_t i = 0; i < m_entries.size(); ++i) {
238 if (i > 0)
239 command += ' ';
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240
Zachary Turner691405b2016-10-03 22:51:09 +0000241 if (m_entries[i].quote) {
242 command += m_entries[i].quote;
243 command += m_entries[i].ref;
244 command += m_entries[i].quote;
245 } else {
246 command += m_entries[i].ref;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000247 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 }
Pavel Labath00b7f952015-03-02 12:46:22 +0000249
Zachary Turner691405b2016-10-03 22:51:09 +0000250 return !m_entries.empty();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000251}
252
Zachary Turner691405b2016-10-03 22:51:09 +0000253void Args::SetCommandString(llvm::StringRef command) {
254 Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09 +0000256
257 static const char *k_space_separators = " \t";
258 command = command.ltrim(k_space_separators);
259 std::string arg;
260 char quote;
261 while (!command.empty()) {
262 std::tie(arg, quote, command) = ParseSingleArgument(command);
263 m_entries.emplace_back(arg, quote);
264 m_argv.push_back(m_entries.back().data());
265 command = command.ltrim(k_space_separators);
266 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268}
269
Zachary Turner691405b2016-10-03 22:51:09 +0000270void Args::UpdateArgsAfterOptionParsing() {
271 assert(!m_argv.empty());
272 assert(m_argv.back() == nullptr);
273
274 // Now m_argv might be out of date with m_entries, so we need to fix that.
275 // This happens because getopt_long_only may permute the order of the
276 // arguments in argv, so we need to re-order the quotes and the refs array
277 // to match.
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000278 for (size_t i = 0; i < m_argv.size() - 1; ++i) {
Zachary Turner691405b2016-10-03 22:51:09 +0000279 const char *argv = m_argv[i];
280 auto pos =
281 std::find_if(m_entries.begin() + i, m_entries.end(),
282 [argv](const ArgEntry &D) { return D.c_str() == argv; });
283 assert(pos != m_entries.end());
284 size_t distance = std::distance(m_entries.begin(), pos);
285 if (i == distance)
286 continue;
287
288 assert(distance > i);
289
290 std::swap(m_entries[i], m_entries[distance]);
291 assert(m_entries[i].ref.data() == m_argv[i]);
292 }
293 m_entries.resize(m_argv.size() - 1);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294}
295
Zachary Turner691405b2016-10-03 22:51:09 +0000296size_t Args::GetArgumentCount() const { return m_entries.size(); }
297
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298const char *Args::GetArgumentAtIndex(size_t idx) const {
299 if (idx < m_argv.size())
300 return m_argv[idx];
301 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000302}
303
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
Zachary Turner691405b2016-10-03 22:51:09 +0000305 if (idx < m_entries.size())
306 return m_entries[idx].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 return '\0';
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308}
309
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310char **Args::GetArgumentVector() {
Zachary Turner691405b2016-10-03 22:51:09 +0000311 assert(!m_argv.empty());
312 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
313 // when argv or envp is null. So the code below is actually wrong. However,
314 // other code in LLDB depends on it being null. The code has been acting this
315 // way for some time, so it makes sense to leave it this way until someone
316 // has the time to come along and fix it.
317 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318}
319
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320const char **Args::GetConstArgumentVector() const {
Zachary Turner691405b2016-10-03 22:51:09 +0000321 assert(!m_argv.empty());
322 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
323 : nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000324}
325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326void Args::Shift() {
327 // Don't pop the last NULL terminator from the argv array
Zachary Turner691405b2016-10-03 22:51:09 +0000328 if (m_entries.empty())
329 return;
330 m_argv.erase(m_argv.begin());
331 m_entries.erase(m_entries.begin());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332}
333
Zachary Turner5c725f32016-09-19 21:56:59 +0000334llvm::StringRef Args::Unshift(llvm::StringRef arg_str, char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09 +0000335 return InsertArgumentAtIndex(0, arg_str, quote_char);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000336}
337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338void Args::AppendArguments(const Args &rhs) {
Zachary Turner691405b2016-10-03 22:51:09 +0000339 assert(m_argv.size() == m_entries.size() + 1);
340 assert(m_argv.back() == nullptr);
341 m_argv.pop_back();
342 for (auto &entry : rhs.m_entries) {
343 m_entries.emplace_back(entry.ref, entry.quote);
344 m_argv.push_back(m_entries.back().data());
345 }
346 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000347}
348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349void Args::AppendArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000350 size_t argc = ArgvToArgc(argv);
351
352 assert(m_argv.size() == m_entries.size() + 1);
353 assert(m_argv.back() == nullptr);
354 m_argv.pop_back();
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000355 for (auto arg : llvm::makeArrayRef(argv, argc)) {
356 m_entries.emplace_back(arg, '\0');
Zachary Turner691405b2016-10-03 22:51:09 +0000357 m_argv.push_back(m_entries.back().data());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 }
Zachary Turner691405b2016-10-03 22:51:09 +0000359
360 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000361}
362
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000363llvm::StringRef Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
364 return InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
Greg Clayton982c9762011-11-03 21:22:33 +0000365}
366
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000367llvm::StringRef Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
368 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09 +0000369 assert(m_argv.size() == m_entries.size() + 1);
370 assert(m_argv.back() == nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371
Zachary Turner691405b2016-10-03 22:51:09 +0000372 if (idx > m_entries.size())
373 return llvm::StringRef();
374 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
375 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
376 return m_entries[idx].ref;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377}
378
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000379llvm::StringRef Args::ReplaceArgumentAtIndex(size_t idx,
380 llvm::StringRef arg_str,
381 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09 +0000382 assert(m_argv.size() == m_entries.size() + 1);
383 assert(m_argv.back() == nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384
Zachary Turner691405b2016-10-03 22:51:09 +0000385 if (idx >= m_entries.size())
386 return llvm::StringRef();
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());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 }
Zachary Turner691405b2016-10-03 22:51:09 +0000397
398 return m_entries[idx].ref;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399}
400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401void Args::DeleteArgumentAtIndex(size_t idx) {
Zachary Turner691405b2016-10-03 22:51:09 +0000402 if (idx >= m_entries.size())
403 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000404
Zachary Turner691405b2016-10-03 22:51:09 +0000405 m_argv.erase(m_argv.begin() + idx);
406 m_entries.erase(m_entries.begin() + idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407}
408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409void Args::SetArguments(size_t argc, const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000410 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000411
Zachary Turner691405b2016-10-03 22:51:09 +0000412 auto args = llvm::makeArrayRef(argv, argc);
413 m_entries.resize(argc);
414 m_argv.resize(argc + 1);
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000415 for (size_t i = 0; i < args.size(); ++i) {
Zachary Turner691405b2016-10-03 22:51:09 +0000416 char quote =
417 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
418 ? args[i][0]
419 : '\0';
420
421 m_entries[i] = ArgEntry(args[i], quote);
422 m_argv[i] = m_entries[i].data();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000424}
425
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426void Args::SetArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000427 SetArguments(ArgvToArgc(argv), argv);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428}
429
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430Error Args::ParseOptions(Options &options, ExecutionContext *execution_context,
431 PlatformSP platform_sp, bool require_validation) {
432 StreamString sstr;
433 Error error;
434 Option *long_options = options.GetLongOptions();
435 if (long_options == nullptr) {
436 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000437 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000439
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 for (int i = 0; long_options[i].definition != nullptr; ++i) {
441 if (long_options[i].flag == nullptr) {
442 if (isprint8(long_options[i].val)) {
443 sstr << (char)long_options[i].val;
444 switch (long_options[i].definition->option_has_arg) {
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000445 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 case OptionParser::eNoArgument:
447 break;
448 case OptionParser::eRequiredArgument:
449 sstr << ':';
450 break;
451 case OptionParser::eOptionalArgument:
452 sstr << "::";
453 break;
454 }
455 }
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000456 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 }
458 std::unique_lock<std::mutex> lock;
459 OptionParser::Prepare(lock);
460 int val;
461 while (1) {
462 int long_options_index = -1;
463 val =
464 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
465 sstr.GetData(), long_options, &long_options_index);
466 if (val == -1)
467 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000468
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 // Did we get an error?
470 if (val == '?') {
471 error.SetErrorStringWithFormat("unknown or ambiguous option");
472 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000473 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 // The option auto-set itself
475 if (val == 0)
476 continue;
477
478 ((Options *)&options)->OptionSeen(val);
479
480 // Lookup the long option index
481 if (long_options_index == -1) {
482 for (int i = 0; long_options[i].definition || long_options[i].flag ||
483 long_options[i].val;
484 ++i) {
485 if (long_options[i].val == val) {
486 long_options_index = i;
487 break;
488 }
489 }
490 }
491 // Call the callback with the option
492 if (long_options_index >= 0 &&
493 long_options[long_options_index].definition) {
494 const OptionDefinition *def = long_options[long_options_index].definition;
495
496 if (!platform_sp) {
497 // User did not pass in an explicit platform. Try to grab
498 // from the execution context.
499 TargetSP target_sp =
500 execution_context ? execution_context->GetTargetSP() : TargetSP();
501 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
502 }
503 OptionValidator *validator = def->validator;
504
505 if (!platform_sp && require_validation) {
506 // Caller requires validation but we cannot validate as we
507 // don't have the mandatory platform against which to
508 // validate.
509 error.SetErrorString("cannot validate options: "
510 "no platform available");
511 return error;
512 }
513
514 bool validation_failed = false;
515 if (platform_sp) {
516 // Ensure we have an execution context, empty or not.
517 ExecutionContext dummy_context;
518 ExecutionContext *exe_ctx_p =
519 execution_context ? execution_context : &dummy_context;
520 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
521 validation_failed = true;
522 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
523 def->long_option,
524 def->validator->LongConditionString());
525 }
526 }
527
528 // As long as validation didn't fail, we set the option value.
529 if (!validation_failed)
530 error = options.SetOptionValue(
531 long_options_index,
532 (def->option_has_arg == OptionParser::eNoArgument)
533 ? nullptr
534 : OptionParser::GetOptionArgument(),
535 execution_context);
536 } else {
537 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
538 }
539 if (error.Fail())
540 break;
541 }
542
543 // Update our ARGV now that get options has consumed all the options
544 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
545 UpdateArgsAfterOptionParsing();
546 return error;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000547}
548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549void Args::Clear() {
Zachary Turner691405b2016-10-03 22:51:09 +0000550 m_entries.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09 +0000552 m_argv.push_back(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553}
554
555lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
556 const char *s, lldb::addr_t fail_value,
557 Error *error_ptr) {
558 bool error_set = false;
559 if (s && s[0]) {
Zachary Turner95eae422016-09-21 16:01:28 +0000560 llvm::StringRef sref = s;
561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 char *end = nullptr;
563 lldb::addr_t addr = ::strtoull(s, &end, 0);
564 if (*end == '\0') {
565 if (error_ptr)
566 error_ptr->Clear();
567 return addr; // All characters were used, return the result
568 }
569 // Try base 16 with no prefix...
570 addr = ::strtoull(s, &end, 16);
571 if (*end == '\0') {
572 if (error_ptr)
573 error_ptr->Clear();
574 return addr; // All characters were used, return the result
575 }
576
577 if (exe_ctx) {
578 Target *target = exe_ctx->GetTargetPtr();
579 if (target) {
580 lldb::ValueObjectSP valobj_sp;
581 EvaluateExpressionOptions options;
582 options.SetCoerceToId(false);
583 options.SetUnwindOnError(true);
584 options.SetKeepInMemory(false);
585 options.SetTryAllThreads(true);
586
587 ExpressionResults expr_result = target->EvaluateExpression(
588 s, exe_ctx->GetFramePtr(), valobj_sp, options);
589
590 bool success = false;
591 if (expr_result == eExpressionCompleted) {
592 if (valobj_sp)
593 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
594 valobj_sp->GetDynamicValueType(), true);
595 // Get the address to watch.
596 if (valobj_sp)
597 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
598 if (success) {
599 if (error_ptr)
600 error_ptr->Clear();
601 return addr;
602 } else {
603 if (error_ptr) {
604 error_set = true;
605 error_ptr->SetErrorStringWithFormat(
606 "address expression \"%s\" resulted in a value whose type "
607 "can't be converted to an address: %s",
608 s, valobj_sp->GetTypeName().GetCString());
609 }
610 }
611
612 } else {
613 // Since the compiler can't handle things like "main + 12" we should
614 // try to do this for now. The compiler doesn't like adding offsets
615 // to function pointer types.
Zachary Turner95eae422016-09-21 16:01:28 +0000616 static RegularExpression g_symbol_plus_offset_regex(llvm::StringRef(
617 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 RegularExpression::Match regex_match(3);
Zachary Turner95eae422016-09-21 16:01:28 +0000619 if (g_symbol_plus_offset_regex.Execute(sref, &regex_match)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 uint64_t offset = 0;
621 bool add = true;
622 std::string name;
623 std::string str;
624 if (regex_match.GetMatchAtIndex(s, 1, name)) {
625 if (regex_match.GetMatchAtIndex(s, 2, str)) {
626 add = str[0] == '+';
627
628 if (regex_match.GetMatchAtIndex(s, 3, str)) {
629 offset = StringConvert::ToUInt64(str.c_str(), 0, 0, &success);
630
631 if (success) {
632 Error error;
633 addr = StringToAddress(exe_ctx, name.c_str(),
634 LLDB_INVALID_ADDRESS, &error);
635 if (addr != LLDB_INVALID_ADDRESS) {
636 if (add)
637 return addr + offset;
638 else
639 return addr - offset;
640 }
641 }
642 }
643 }
644 }
645 }
646
647 if (error_ptr) {
648 error_set = true;
649 error_ptr->SetErrorStringWithFormat(
650 "address expression \"%s\" evaluation failed", s);
651 }
652 }
653 }
654 }
655 }
656 if (error_ptr) {
657 if (!error_set)
658 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
659 s);
660 }
661 return fail_value;
662}
663
664const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
665 bool return_null_if_empty) {
666 static const char *k_white_space = " \t\v";
667 if (!s.empty()) {
668 if (leading) {
669 size_t pos = s.find_first_not_of(k_white_space);
670 if (pos == std::string::npos)
671 s.clear();
672 else if (pos > 0)
673 s.erase(0, pos);
674 }
675
676 if (trailing) {
677 size_t rpos = s.find_last_not_of(k_white_space);
678 if (rpos != std::string::npos && rpos + 1 < s.size())
679 s.erase(rpos + 1);
680 }
681 }
682 if (return_null_if_empty && s.empty())
683 return nullptr;
684 return s.c_str();
685}
686
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
688 bool *success_ptr) {
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000689 if (success_ptr)
690 *success_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 ref = ref.trim();
692 if (ref.equals_lower("false") || ref.equals_lower("off") ||
693 ref.equals_lower("no") || ref.equals_lower("0")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 return false;
695 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
696 ref.equals_lower("yes") || ref.equals_lower("1")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 return true;
698 }
699 if (success_ptr)
700 *success_ptr = false;
701 return fail_value;
702}
703
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000704char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 if (success_ptr)
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000706 *success_ptr = false;
707 if (s.size() != 1)
708 return fail_value;
709
710 if (success_ptr)
711 *success_ptr = true;
712 return s[0];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713}
714
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000715bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
716 uint32_t &minor, uint32_t &update) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 major = UINT32_MAX;
718 minor = UINT32_MAX;
719 update = UINT32_MAX;
720
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000721 if (string.empty())
722 return false;
723
724 llvm::StringRef major_str, minor_str, update_str;
725
726 std::tie(major_str, minor_str) = string.split('.');
727 std::tie(minor_str, update_str) = minor_str.split('.');
728 if (major_str.getAsInteger(10, major))
729 return false;
730 if (!minor_str.empty() && minor_str.getAsInteger(10, minor))
731 return false;
732 if (!update_str.empty() && update_str.getAsInteger(10, update))
733 return false;
734
735 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736}
737
738const char *Args::GetShellSafeArgument(const FileSpec &shell,
739 const char *unsafe_arg,
740 std::string &safe_arg) {
741 struct ShellDescriptor {
742 ConstString m_basename;
743 const char *m_escapables;
744 };
745
746 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
747 {ConstString("tcsh"), " '\"<>()&$"},
748 {ConstString("sh"), " '\"<>()&"}};
749
750 // safe minimal set
751 const char *escapables = " '\"";
752
753 if (auto basename = shell.GetFilename()) {
754 for (const auto &Shell : g_Shells) {
755 if (Shell.m_basename == basename) {
756 escapables = Shell.m_escapables;
757 break;
758 }
759 }
760 }
761
762 safe_arg.assign(unsafe_arg);
763 size_t prev_pos = 0;
764 while (prev_pos < safe_arg.size()) {
765 // Escape spaces and quotes
766 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
767 if (pos != std::string::npos) {
768 safe_arg.insert(pos, 1, '\\');
769 prev_pos = pos + 2;
770 } else
771 break;
772 }
773 return safe_arg.c_str();
774}
775
Zachary Turner8cef4b02016-09-23 17:48:13 +0000776int64_t Args::StringToOptionEnum(llvm::StringRef s,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 OptionEnumValueElement *enum_values,
778 int32_t fail_value, Error &error) {
Zachary Turner8cef4b02016-09-23 17:48:13 +0000779 error.Clear();
780 if (!enum_values) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 error.SetErrorString("invalid enumeration argument");
Zachary Turner8cef4b02016-09-23 17:48:13 +0000782 return fail_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 }
Zachary Turner8cef4b02016-09-23 17:48:13 +0000784
785 if (s.empty()) {
786 error.SetErrorString("empty enumeration string");
787 return fail_value;
788 }
789
790 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
791 llvm::StringRef this_enum(enum_values[i].string_value);
792 if (this_enum.startswith(s))
793 return enum_values[i].value;
794 }
795
796 StreamString strm;
797 strm.PutCString("invalid enumeration value, valid values are: ");
798 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
799 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
800 }
801 error.SetErrorString(strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 return fail_value;
803}
804
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000805lldb::ScriptLanguage
806Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
807 bool *success_ptr) {
808 if (success_ptr)
809 *success_ptr = true;
810
811 if (s.equals_lower("python"))
812 return eScriptLanguagePython;
813 if (s.equals_lower("default"))
814 return eScriptLanguageDefault;
815 if (s.equals_lower("none"))
816 return eScriptLanguageNone;
817
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 if (success_ptr)
819 *success_ptr = false;
820 return fail_value;
821}
822
823Error Args::StringToFormat(const char *s, lldb::Format &format,
824 size_t *byte_size_ptr) {
825 format = eFormatInvalid;
826 Error error;
827
828 if (s && s[0]) {
829 if (byte_size_ptr) {
830 if (isdigit(s[0])) {
831 char *format_char = nullptr;
832 unsigned long byte_size = ::strtoul(s, &format_char, 0);
833 if (byte_size != ULONG_MAX)
834 *byte_size_ptr = byte_size;
835 s = format_char;
836 } else
837 *byte_size_ptr = 0;
838 }
839
840 const bool partial_match_ok = true;
841 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
842 StreamString error_strm;
843 error_strm.Printf(
844 "Invalid format character or name '%s'. Valid values are:\n", s);
845 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
846 char format_char = FormatManager::GetFormatAsFormatChar(f);
847 if (format_char)
848 error_strm.Printf("'%c' or ", format_char);
849
850 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
851 error_strm.EOL();
852 }
853
854 if (byte_size_ptr)
855 error_strm.PutCString(
856 "An optional byte size can precede the format character.\n");
857 error.SetErrorString(error_strm.GetString().c_str());
858 }
859
860 if (error.Fail())
861 return error;
862 } else {
863 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
864 }
865 return error;
866}
867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
869 lldb::Encoding fail_value) {
870 return llvm::StringSwitch<lldb::Encoding>(s)
871 .Case("uint", eEncodingUint)
872 .Case("sint", eEncodingSint)
873 .Case("ieee754", eEncodingIEEE754)
874 .Case("vector", eEncodingVector)
875 .Default(fail_value);
876}
877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
879 if (s.empty())
880 return LLDB_INVALID_REGNUM;
881 uint32_t result = llvm::StringSwitch<uint32_t>(s)
882 .Case("pc", LLDB_REGNUM_GENERIC_PC)
883 .Case("sp", LLDB_REGNUM_GENERIC_SP)
884 .Case("fp", LLDB_REGNUM_GENERIC_FP)
885 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
886 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
887 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
888 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
889 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
890 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
891 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
892 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
893 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
894 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
895 .Default(LLDB_INVALID_REGNUM);
896 return result;
897}
898
Zachary Turner5c725f32016-09-19 21:56:59 +0000899void Args::AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
900 llvm::StringRef new_value) {
Todd Fiala36bf6a42016-09-22 16:00:01 +0000901 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 return;
903
904 // Build the new entry.
Zachary Turner5c725f32016-09-19 21:56:59 +0000905 std::string var_string(env_var_name);
Todd Fiala36bf6a42016-09-22 16:00:01 +0000906 if (!new_value.empty()) {
907 var_string += "=";
908 var_string += new_value;
909 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910
Zachary Turner5c725f32016-09-19 21:56:59 +0000911 size_t index = 0;
912 if (ContainsEnvironmentVariable(env_var_name, &index)) {
913 ReplaceArgumentAtIndex(index, var_string);
914 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 }
916
917 // We didn't find it. Append it instead.
Zachary Turner5c725f32016-09-19 21:56:59 +0000918 AppendArgument(var_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919}
920
Zachary Turner5c725f32016-09-19 21:56:59 +0000921bool Args::ContainsEnvironmentVariable(llvm::StringRef env_var_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922 size_t *argument_index) const {
923 // Validate args.
Zachary Turner5c725f32016-09-19 21:56:59 +0000924 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 return false;
926
927 // Check each arg to see if it matches the env var name.
928 for (size_t i = 0; i < GetArgumentCount(); ++i) {
Todd Fiala150aa322016-09-22 00:59:23 +0000929 auto arg_value = llvm::StringRef::withNullAsEmpty(GetArgumentAtIndex(i));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000930
Zachary Turner5c725f32016-09-19 21:56:59 +0000931 llvm::StringRef name, value;
932 std::tie(name, value) = arg_value.split('=');
Todd Fiala36bf6a42016-09-22 16:00:01 +0000933 if (name == env_var_name) {
Zachary Turner5c725f32016-09-19 21:56:59 +0000934 if (argument_index)
935 *argument_index = i;
936 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937 }
938 }
939
940 // We didn't find a match.
941 return false;
942}
943
944size_t Args::FindArgumentIndexForOption(Option *long_options,
945 int long_options_index) {
946 char short_buffer[3];
947 char long_buffer[255];
948 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
949 long_options[long_options_index].val);
950 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
951 long_options[long_options_index].definition->long_option);
952 size_t end = GetArgumentCount();
953 size_t idx = 0;
954 while (idx < end) {
955 if ((::strncmp(GetArgumentAtIndex(idx), short_buffer,
956 strlen(short_buffer)) == 0) ||
957 (::strncmp(GetArgumentAtIndex(idx), long_buffer, strlen(long_buffer)) ==
958 0)) {
959 return idx;
960 }
961 ++idx;
962 }
963
964 return end;
965}
966
967bool Args::IsPositionalArgument(const char *arg) {
968 if (arg == nullptr)
969 return false;
970
971 bool is_positional = true;
972 const char *cptr = arg;
973
974 if (cptr[0] == '%') {
975 ++cptr;
976 while (isdigit(cptr[0]))
977 ++cptr;
978 if (cptr[0] != '\0')
979 is_positional = false;
980 } else
981 is_positional = false;
982
983 return is_positional;
984}
985
986void Args::ParseAliasOptions(Options &options, CommandReturnObject &result,
987 OptionArgVector *option_arg_vector,
988 std::string &raw_input_string) {
989 StreamString sstr;
990 int i;
991 Option *long_options = options.GetLongOptions();
992
993 if (long_options == nullptr) {
994 result.AppendError("invalid long options");
995 result.SetStatus(eReturnStatusFailed);
996 return;
997 }
998
999 for (i = 0; long_options[i].definition != nullptr; ++i) {
1000 if (long_options[i].flag == nullptr) {
1001 sstr << (char)long_options[i].val;
1002 switch (long_options[i].definition->option_has_arg) {
1003 default:
1004 case OptionParser::eNoArgument:
1005 break;
1006 case OptionParser::eRequiredArgument:
1007 sstr << ":";
1008 break;
1009 case OptionParser::eOptionalArgument:
1010 sstr << "::";
1011 break;
1012 }
1013 }
1014 }
1015
1016 std::unique_lock<std::mutex> lock;
1017 OptionParser::Prepare(lock);
Zachary Turner5c28c662016-10-03 23:20:36 +00001018 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 int val;
1020 while (1) {
1021 int long_options_index = -1;
1022 val =
1023 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1024 sstr.GetData(), long_options, &long_options_index);
1025
1026 if (val == -1)
1027 break;
1028
1029 if (val == '?') {
1030 result.AppendError("unknown or ambiguous option");
1031 result.SetStatus(eReturnStatusFailed);
1032 break;
1033 }
1034
1035 if (val == 0)
1036 continue;
1037
1038 options.OptionSeen(val);
1039
1040 // Look up the long option index
1041 if (long_options_index == -1) {
1042 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1043 long_options[j].val;
1044 ++j) {
1045 if (long_options[j].val == val) {
1046 long_options_index = j;
1047 break;
1048 }
1049 }
1050 }
1051
1052 // See if the option takes an argument, and see if one was supplied.
Zachary Turner5c28c662016-10-03 23:20:36 +00001053 if (long_options_index == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1055 result.SetStatus(eReturnStatusFailed);
Zachary Turner5c28c662016-10-03 23:20:36 +00001056 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 }
1058
Zachary Turner5c28c662016-10-03 23:20:36 +00001059 StreamString option_str;
1060 option_str.Printf("-%c", val);
1061 const OptionDefinition *def = long_options[long_options_index].definition;
1062 int has_arg =
1063 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1064
1065 const char *option_arg = nullptr;
1066 switch (has_arg) {
1067 case OptionParser::eRequiredArgument:
1068 if (OptionParser::GetOptionArgument() == nullptr) {
1069 result.AppendErrorWithFormat(
1070 "Option '%s' is missing argument specifier.\n",
1071 option_str.GetData());
1072 result.SetStatus(eReturnStatusFailed);
1073 return;
1074 }
1075 LLVM_FALLTHROUGH;
1076 case OptionParser::eOptionalArgument:
1077 option_arg = OptionParser::GetOptionArgument();
1078 LLVM_FALLTHROUGH;
1079 case OptionParser::eNoArgument:
1080 break;
1081 default:
1082 result.AppendErrorWithFormat("error with options table; invalid value "
1083 "in has_arg field for option '%c'.\n",
1084 val);
1085 result.SetStatus(eReturnStatusFailed);
1086 return;
1087 }
1088 if (!option_arg)
1089 option_arg = "<no-argument>";
1090 option_arg_vector->emplace_back(option_str.GetData(), has_arg, option_arg);
1091
1092 // Find option in the argument list; also see if it was supposed to take
1093 // an argument and if one was supplied. Remove option (and argument, if
1094 // given) from the argument list. Also remove them from the
1095 // raw_input_string, if one was passed in.
1096 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
1097 if (idx < GetArgumentCount()) {
1098 if (raw_input_string.size() > 0) {
1099 const char *tmp_arg = GetArgumentAtIndex(idx);
1100 size_t pos = raw_input_string.find(tmp_arg);
1101 if (pos != std::string::npos)
1102 raw_input_string.erase(pos, strlen(tmp_arg));
1103 }
1104 ReplaceArgumentAtIndex(idx, llvm::StringRef());
1105 if ((long_options[long_options_index].definition->option_has_arg !=
1106 OptionParser::eNoArgument) &&
1107 (OptionParser::GetOptionArgument() != nullptr) &&
1108 (idx + 1 < GetArgumentCount()) &&
1109 (strcmp(OptionParser::GetOptionArgument(),
1110 GetArgumentAtIndex(idx + 1)) == 0)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 if (raw_input_string.size() > 0) {
Zachary Turner5c28c662016-10-03 23:20:36 +00001112 const char *tmp_arg = GetArgumentAtIndex(idx + 1);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 size_t pos = raw_input_string.find(tmp_arg);
1114 if (pos != std::string::npos)
1115 raw_input_string.erase(pos, strlen(tmp_arg));
1116 }
Zachary Turner5c28c662016-10-03 23:20:36 +00001117 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 }
1119 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 }
1121}
1122
1123void Args::ParseArgsForCompletion(Options &options,
1124 OptionElementVector &option_element_vector,
1125 uint32_t cursor_index) {
1126 StreamString sstr;
1127 Option *long_options = options.GetLongOptions();
1128 option_element_vector.clear();
1129
1130 if (long_options == nullptr) {
1131 return;
1132 }
1133
1134 // Leading : tells getopt to return a : for a missing option argument AND
1135 // to suppress error messages.
1136
1137 sstr << ":";
1138 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1139 if (long_options[i].flag == nullptr) {
1140 sstr << (char)long_options[i].val;
1141 switch (long_options[i].definition->option_has_arg) {
1142 default:
1143 case OptionParser::eNoArgument:
1144 break;
1145 case OptionParser::eRequiredArgument:
1146 sstr << ":";
1147 break;
1148 case OptionParser::eOptionalArgument:
1149 sstr << "::";
1150 break;
1151 }
1152 }
1153 }
1154
1155 std::unique_lock<std::mutex> lock;
1156 OptionParser::Prepare(lock);
1157 OptionParser::EnableError(false);
1158
1159 int val;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001160 auto opt_defs = options.GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161
1162 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
1163 // options to the front.
1164 // So we have to build another Arg and pass that to OptionParser::Parse so it
1165 // doesn't
1166 // change the one we have.
1167
1168 std::vector<const char *> dummy_vec(
1169 GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
1170
1171 bool failed_once = false;
1172 uint32_t dash_dash_pos = -1;
1173
1174 while (1) {
1175 bool missing_argument = false;
1176 int long_options_index = -1;
1177
1178 val = OptionParser::Parse(
1179 dummy_vec.size() - 1, const_cast<char *const *>(&dummy_vec.front()),
1180 sstr.GetData(), long_options, &long_options_index);
1181
1182 if (val == -1) {
1183 // When we're completing a "--" which is the last option on line,
1184 if (failed_once)
1185 break;
1186
1187 failed_once = true;
1188
1189 // If this is a bare "--" we mark it as such so we can complete it
1190 // successfully later.
1191 // Handling the "--" is a little tricky, since that may mean end of
1192 // options or arguments, or the
1193 // user might want to complete options by long name. I make this work by
1194 // checking whether the
1195 // cursor is in the "--" argument, and if so I assume we're completing the
1196 // long option, otherwise
1197 // I let it pass to OptionParser::Parse which will terminate the option
1198 // parsing.
1199 // Note, in either case we continue parsing the line so we can figure out
1200 // what other options
1201 // were passed. This will be useful when we come to restricting
1202 // completions based on what other
1203 // options we've seen on the line.
1204
1205 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1206 dummy_vec.size() - 1 &&
1207 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1208 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1209 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1210 cursor_index) {
1211 option_element_vector.push_back(
1212 OptionArgElement(OptionArgElement::eBareDoubleDash,
1213 OptionParser::GetOptionIndex() - 1,
1214 OptionArgElement::eBareDoubleDash));
1215 continue;
1216 } else
1217 break;
1218 } else
1219 break;
1220 } else if (val == '?') {
1221 option_element_vector.push_back(
1222 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1223 OptionParser::GetOptionIndex() - 1,
1224 OptionArgElement::eUnrecognizedArg));
1225 continue;
1226 } else if (val == 0) {
1227 continue;
1228 } else if (val == ':') {
1229 // This is a missing argument.
1230 val = OptionParser::GetOptionErrorCause();
1231 missing_argument = true;
1232 }
1233
1234 ((Options *)&options)->OptionSeen(val);
1235
1236 // Look up the long option index
1237 if (long_options_index == -1) {
1238 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1239 long_options[j].val;
1240 ++j) {
1241 if (long_options[j].val == val) {
1242 long_options_index = j;
1243 break;
1244 }
1245 }
1246 }
1247
1248 // See if the option takes an argument, and see if one was supplied.
1249 if (long_options_index >= 0) {
1250 int opt_defs_index = -1;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001251 for (size_t i = 0; i < opt_defs.size(); i++) {
1252 if (opt_defs[i].short_option != val)
1253 continue;
1254 opt_defs_index = i;
1255 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 }
1257
1258 const OptionDefinition *def = long_options[long_options_index].definition;
1259 int has_arg =
1260 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1261 switch (has_arg) {
1262 case OptionParser::eNoArgument:
1263 option_element_vector.push_back(OptionArgElement(
1264 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1265 break;
1266 case OptionParser::eRequiredArgument:
1267 if (OptionParser::GetOptionArgument() != nullptr) {
1268 int arg_index;
1269 if (missing_argument)
1270 arg_index = -1;
1271 else
1272 arg_index = OptionParser::GetOptionIndex() - 1;
1273
1274 option_element_vector.push_back(OptionArgElement(
1275 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1276 } else {
1277 option_element_vector.push_back(OptionArgElement(
1278 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1279 }
1280 break;
1281 case OptionParser::eOptionalArgument:
1282 if (OptionParser::GetOptionArgument() != nullptr) {
1283 option_element_vector.push_back(OptionArgElement(
1284 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1285 OptionParser::GetOptionIndex() - 1));
1286 } else {
1287 option_element_vector.push_back(OptionArgElement(
1288 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1289 OptionParser::GetOptionIndex() - 1));
1290 }
1291 break;
1292 default:
1293 // The options table is messed up. Here we'll just continue
1294 option_element_vector.push_back(
1295 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1296 OptionParser::GetOptionIndex() - 1,
1297 OptionArgElement::eUnrecognizedArg));
1298 break;
1299 }
1300 } else {
1301 option_element_vector.push_back(
1302 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1303 OptionParser::GetOptionIndex() - 1,
1304 OptionArgElement::eUnrecognizedArg));
1305 }
1306 }
1307
1308 // Finally we have to handle the case where the cursor index points at a
1309 // single "-". We want to mark that in
1310 // the option_element_vector, but only if it is not after the "--". But it
1311 // turns out that OptionParser::Parse just ignores
1312 // an isolated "-". So we have to look it up by hand here. We only care if
1313 // it is AT the cursor position.
1314 // Note, a single quoted dash is not the same as a single dash...
1315
Zachary Turner691405b2016-10-03 22:51:09 +00001316 const ArgEntry &cursor = m_entries[cursor_index];
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1318 cursor_index < dash_dash_pos) &&
Zachary Turner691405b2016-10-03 22:51:09 +00001319 cursor.quote == '\0' && cursor.ref == "-") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 option_element_vector.push_back(
1321 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1322 OptionArgElement::eBareDash));
1323 }
1324}
1325
1326void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1327 dst.clear();
1328 if (src) {
1329 for (const char *p = src; *p != '\0'; ++p) {
1330 size_t non_special_chars = ::strcspn(p, "\\");
1331 if (non_special_chars > 0) {
1332 dst.append(p, non_special_chars);
1333 p += non_special_chars;
1334 if (*p == '\0')
1335 break;
1336 }
1337
1338 if (*p == '\\') {
1339 ++p; // skip the slash
1340 switch (*p) {
1341 case 'a':
1342 dst.append(1, '\a');
1343 break;
1344 case 'b':
1345 dst.append(1, '\b');
1346 break;
1347 case 'f':
1348 dst.append(1, '\f');
1349 break;
1350 case 'n':
1351 dst.append(1, '\n');
1352 break;
1353 case 'r':
1354 dst.append(1, '\r');
1355 break;
1356 case 't':
1357 dst.append(1, '\t');
1358 break;
1359 case 'v':
1360 dst.append(1, '\v');
1361 break;
1362 case '\\':
1363 dst.append(1, '\\');
1364 break;
1365 case '\'':
1366 dst.append(1, '\'');
1367 break;
1368 case '"':
1369 dst.append(1, '"');
1370 break;
1371 case '0':
1372 // 1 to 3 octal chars
1373 {
1374 // Make a string that can hold onto the initial zero char,
1375 // up to 3 octal digits, and a terminating NULL.
1376 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1377
1378 int i;
1379 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1380 oct_str[i] = p[i];
1381
1382 // We don't want to consume the last octal character since
1383 // the main for loop will do this for us, so we advance p by
1384 // one less than i (even if i is zero)
1385 p += i - 1;
1386 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1387 if (octal_value <= UINT8_MAX) {
1388 dst.append(1, (char)octal_value);
1389 }
1390 }
1391 break;
1392
1393 case 'x':
1394 // hex number in the format
1395 if (isxdigit(p[1])) {
1396 ++p; // Skip the 'x'
1397
1398 // Make a string that can hold onto two hex chars plus a
1399 // NULL terminator
1400 char hex_str[3] = {*p, '\0', '\0'};
1401 if (isxdigit(p[1])) {
1402 ++p; // Skip the first of the two hex chars
1403 hex_str[1] = *p;
1404 }
1405
1406 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1407 if (hex_value <= UINT8_MAX)
1408 dst.append(1, (char)hex_value);
1409 } else {
1410 dst.append(1, 'x');
1411 }
1412 break;
1413
1414 default:
1415 // Just desensitize any other character by just printing what
1416 // came after the '\'
1417 dst.append(1, *p);
1418 break;
1419 }
1420 }
1421 }
1422 }
1423}
1424
1425void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1426 dst.clear();
1427 if (src) {
1428 for (const char *p = src; *p != '\0'; ++p) {
1429 if (isprint8(*p))
1430 dst.append(1, *p);
1431 else {
1432 switch (*p) {
1433 case '\a':
1434 dst.append("\\a");
1435 break;
1436 case '\b':
1437 dst.append("\\b");
1438 break;
1439 case '\f':
1440 dst.append("\\f");
1441 break;
1442 case '\n':
1443 dst.append("\\n");
1444 break;
1445 case '\r':
1446 dst.append("\\r");
1447 break;
1448 case '\t':
1449 dst.append("\\t");
1450 break;
1451 case '\v':
1452 dst.append("\\v");
1453 break;
1454 case '\'':
1455 dst.append("\\'");
1456 break;
1457 case '"':
1458 dst.append("\\\"");
1459 break;
1460 case '\\':
1461 dst.append("\\\\");
1462 break;
1463 default: {
1464 // Just encode as octal
1465 dst.append("\\0");
1466 char octal_str[32];
1467 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1468 dst.append(octal_str);
1469 } break;
1470 }
1471 }
1472 }
1473 }
1474}
1475
1476std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1477 char quote_char) {
1478 const char *chars_to_escape = nullptr;
1479 switch (quote_char) {
1480 case '\0':
1481 chars_to_escape = " \t\\'\"`";
1482 break;
1483 case '\'':
1484 chars_to_escape = "";
1485 break;
1486 case '"':
1487 chars_to_escape = "$\"`\\";
1488 break;
1489 default:
1490 assert(false && "Unhandled quote character");
1491 }
1492
1493 std::string res;
1494 res.reserve(arg.size());
1495 for (char c : arg) {
1496 if (::strchr(chars_to_escape, c))
1497 res.push_back('\\');
1498 res.push_back(c);
1499 }
1500 return res;
1501}