blob: 698432885d9bd1e157afe5f554211af93575ca7b [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 Turner11eb9c62016-10-05 20:03:37 +000028#include "llvm/ADT/STLExtras.h"
Zachary Turner691405b2016-10-03 22:51:09 +000029#include "llvm/ADT/StringExtras.h"
Zachary Turner54695a32016-08-29 19:58:14 +000030#include "llvm/ADT/StringSwitch.h"
31
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032using namespace lldb;
33using namespace lldb_private;
34
Caroline Tice2d5289d2010-12-10 00:26:54 +000035
Pavel Labath00b7f952015-03-02 12:46:22 +000036// A helper function for argument parsing.
Kate Stoneb9c1b512016-09-06 20:57:50 +000037// Parses the initial part of the first argument using normal double quote
38// rules:
39// backslash escapes the double quote and itself. The parsed string is appended
40// to the second
41// argument. The function returns the unparsed portion of the string, starting
42// at the closing
Pavel Labath00b7f952015-03-02 12:46:22 +000043// quote.
Kate Stoneb9c1b512016-09-06 20:57:50 +000044static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
45 std::string &result) {
46 // Inside double quotes, '\' and '"' are special.
47 static const char *k_escapable_characters = "\"\\";
48 while (true) {
49 // Skip over over regular characters and append them.
50 size_t regular = quoted.find_first_of(k_escapable_characters);
51 result += quoted.substr(0, regular);
52 quoted = quoted.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22 +000053
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 // If we have reached the end of string or the closing quote, we're done.
55 if (quoted.empty() || quoted.front() == '"')
56 break;
Pavel Labath00b7f952015-03-02 12:46:22 +000057
Kate Stoneb9c1b512016-09-06 20:57:50 +000058 // We have found a backslash.
59 quoted = quoted.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22 +000060
Kate Stoneb9c1b512016-09-06 20:57:50 +000061 if (quoted.empty()) {
62 // A lone backslash at the end of string, let's just append it.
63 result += '\\';
64 break;
Pavel Labath00b7f952015-03-02 12:46:22 +000065 }
66
Kate Stoneb9c1b512016-09-06 20:57:50 +000067 // If the character after the backslash is not a whitelisted escapable
68 // character, we
69 // leave the character sequence untouched.
70 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
71 result += '\\';
72
73 result += quoted.front();
74 quoted = quoted.drop_front();
75 }
76
77 return quoted;
Pavel Labath00b7f952015-03-02 12:46:22 +000078}
79
Zachary Turner691405b2016-10-03 22:51:09 +000080static size_t ArgvToArgc(const char **argv) {
81 if (!argv)
82 return 0;
83 size_t count = 0;
84 while (*argv++)
85 ++count;
86 return count;
87}
Pavel Labath00b7f952015-03-02 12:46:22 +000088
Zachary Turner691405b2016-10-03 22:51:09 +000089// A helper function for SetCommandString. Parses a single argument from the
90// command string, processing quotes and backslashes in a shell-like manner.
91// The function returns a tuple consisting of the parsed argument, the quote
92// char used, and the unparsed portion of the string starting at the first
93// unqouted, unescaped whitespace character.
94static std::tuple<std::string, char, llvm::StringRef>
95ParseSingleArgument(llvm::StringRef command) {
96 // Argument can be split into multiple discontiguous pieces, for example:
97 // "Hello ""World"
98 // this would result in a single argument "Hello World" (without the quotes)
99 // since the quotes would be removed and there is not space between the
100 // strings.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 std::string arg;
Pavel Labath00b7f952015-03-02 12:46:22 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 // Since we can have multiple quotes that form a single command
104 // in a command like: "Hello "world'!' (which will make a single
105 // argument "Hello world!") we remember the first quote character
106 // we encounter and use that for the quote character.
107 char first_quote_char = '\0';
Pavel Labath00b7f952015-03-02 12:46:22 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 bool arg_complete = false;
110 do {
111 // Skip over over regular characters and append them.
112 size_t regular = command.find_first_of(" \t\"'`\\");
113 arg += command.substr(0, regular);
114 command = command.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22 +0000115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 if (command.empty())
117 break;
Pavel Labath00b7f952015-03-02 12:46:22 +0000118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 char special = command.front();
120 command = command.drop_front();
121 switch (special) {
122 case '\\':
123 if (command.empty()) {
124 arg += '\\';
125 break;
126 }
127
128 // If the character after the backslash is not a whitelisted escapable
129 // character, we
130 // leave the character sequence untouched.
131 if (strchr(" \t\\'\"`", command.front()) == nullptr)
132 arg += '\\';
133
134 arg += command.front();
135 command = command.drop_front();
136
137 break;
138
139 case ' ':
140 case '\t':
141 // We are not inside any quotes, we just found a space after an
142 // argument. We are done.
143 arg_complete = true;
144 break;
145
146 case '"':
147 case '\'':
148 case '`':
149 // We found the start of a quote scope.
150 if (first_quote_char == '\0')
151 first_quote_char = special;
152
153 if (special == '"')
154 command = ParseDoubleQuotes(command, arg);
155 else {
156 // For single quotes, we simply skip ahead to the matching quote
157 // character
158 // (or the end of the string).
159 size_t quoted = command.find(special);
160 arg += command.substr(0, quoted);
161 command = command.substr(quoted);
162 }
163
164 // If we found a closing quote, skip it.
165 if (!command.empty())
Pavel Labath00b7f952015-03-02 12:46:22 +0000166 command = command.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22 +0000167
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 break;
169 }
170 } while (!arg_complete);
Pavel Labath00b7f952015-03-02 12:46:22 +0000171
Zachary Turner691405b2016-10-03 22:51:09 +0000172 return std::make_tuple(arg, first_quote_char, command);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000173}
174
Zachary Turner691405b2016-10-03 22:51:09 +0000175Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
176 size_t size = str.size();
177 ptr.reset(new char[size + 1]);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000178
Zachary Turner691405b2016-10-03 22:51:09 +0000179 ::memcpy(data(), str.data() ? str.data() : "", size);
180 ptr[size] = 0;
181 ref = llvm::StringRef(c_str(), size);
182}
183
184//----------------------------------------------------------------------
185// Args constructor
186//----------------------------------------------------------------------
187Args::Args(llvm::StringRef command) { SetCommandString(command); }
188
189Args::Args(const Args &rhs) { *this = rhs; }
190
191Args &Args::operator=(const Args &rhs) {
192 Clear();
193
194 m_argv.clear();
195 m_entries.clear();
196 for (auto &entry : rhs.m_entries) {
197 m_entries.emplace_back(entry.ref, entry.quote);
198 m_argv.push_back(m_entries.back().data());
199 }
200 m_argv.push_back(nullptr);
201 return *this;
202}
203
204//----------------------------------------------------------------------
205// Destructor
206//----------------------------------------------------------------------
207Args::~Args() {}
208
209void Args::Dump(Stream &s, const char *label_name) const {
210 if (!label_name)
211 return;
212
213 int i = 0;
214 for (auto &entry : m_entries) {
215 s.Indent();
Luke Drummond63dea592016-12-22 19:15:07 +0000216 s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
Zachary Turner691405b2016-10-03 22:51:09 +0000217 }
Luke Drummond63dea592016-12-22 19:15:07 +0000218 s.Format("{0}[{1}]=NULL\n", label_name, i);
Zachary Turner691405b2016-10-03 22:51:09 +0000219 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
Justin Bogner812101d2016-10-17 06:17:56 +0000334void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
335 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
Justin Bogner812101d2016-10-17 06:17:56 +0000363void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
364 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
Greg Clayton982c9762011-11-03 21:22:33 +0000365}
366
Justin Bogner812101d2016-10-17 06:17:56 +0000367void 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())
Justin Bogner812101d2016-10-17 06:17:56 +0000373 return;
Zachary Turner691405b2016-10-03 22:51:09 +0000374 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
375 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376}
377
Justin Bogner812101d2016-10-17 06:17:56 +0000378void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
379 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09 +0000380 assert(m_argv.size() == m_entries.size() + 1);
381 assert(m_argv.back() == nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000382
Zachary Turner691405b2016-10-03 22:51:09 +0000383 if (idx >= m_entries.size())
Justin Bogner812101d2016-10-17 06:17:56 +0000384 return;
Zachary Turner691405b2016-10-03 22:51:09 +0000385
386 if (arg_str.size() > m_entries[idx].ref.size()) {
387 m_entries[idx] = ArgEntry(arg_str, quote_char);
388 m_argv[idx] = m_entries[idx].data();
389 } else {
390 const char *src_data = arg_str.data() ? arg_str.data() : "";
391 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
392 m_entries[idx].ptr[arg_str.size()] = 0;
393 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395}
396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397void Args::DeleteArgumentAtIndex(size_t idx) {
Zachary Turner691405b2016-10-03 22:51:09 +0000398 if (idx >= m_entries.size())
399 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400
Zachary Turner691405b2016-10-03 22:51:09 +0000401 m_argv.erase(m_argv.begin() + idx);
402 m_entries.erase(m_entries.begin() + idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403}
404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405void Args::SetArguments(size_t argc, const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000406 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407
Zachary Turner691405b2016-10-03 22:51:09 +0000408 auto args = llvm::makeArrayRef(argv, argc);
409 m_entries.resize(argc);
410 m_argv.resize(argc + 1);
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000411 for (size_t i = 0; i < args.size(); ++i) {
Zachary Turner691405b2016-10-03 22:51:09 +0000412 char quote =
413 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
414 ? args[i][0]
415 : '\0';
416
417 m_entries[i] = ArgEntry(args[i], quote);
418 m_argv[i] = m_entries[i].data();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420}
421
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422void Args::SetArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000423 SetArguments(ArgvToArgc(argv), argv);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000424}
425
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426Error Args::ParseOptions(Options &options, ExecutionContext *execution_context,
427 PlatformSP platform_sp, bool require_validation) {
428 StreamString sstr;
429 Error error;
430 Option *long_options = options.GetLongOptions();
431 if (long_options == nullptr) {
432 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 for (int i = 0; long_options[i].definition != nullptr; ++i) {
437 if (long_options[i].flag == nullptr) {
438 if (isprint8(long_options[i].val)) {
439 sstr << (char)long_options[i].val;
440 switch (long_options[i].definition->option_has_arg) {
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000441 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 case OptionParser::eNoArgument:
443 break;
444 case OptionParser::eRequiredArgument:
445 sstr << ':';
446 break;
447 case OptionParser::eOptionalArgument:
448 sstr << "::";
449 break;
450 }
451 }
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000452 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 }
454 std::unique_lock<std::mutex> lock;
455 OptionParser::Prepare(lock);
456 int val;
457 while (1) {
458 int long_options_index = -1;
Zachary Turnere706c1d2016-11-13 04:24:38 +0000459 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
460 sstr.GetString(), long_options,
461 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 if (val == -1)
463 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000464
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465 // Did we get an error?
466 if (val == '?') {
467 error.SetErrorStringWithFormat("unknown or ambiguous option");
468 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000469 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 // The option auto-set itself
471 if (val == 0)
472 continue;
473
474 ((Options *)&options)->OptionSeen(val);
475
476 // Lookup the long option index
477 if (long_options_index == -1) {
478 for (int i = 0; long_options[i].definition || long_options[i].flag ||
479 long_options[i].val;
480 ++i) {
481 if (long_options[i].val == val) {
482 long_options_index = i;
483 break;
484 }
485 }
486 }
487 // Call the callback with the option
488 if (long_options_index >= 0 &&
489 long_options[long_options_index].definition) {
490 const OptionDefinition *def = long_options[long_options_index].definition;
491
492 if (!platform_sp) {
493 // User did not pass in an explicit platform. Try to grab
494 // from the execution context.
495 TargetSP target_sp =
496 execution_context ? execution_context->GetTargetSP() : TargetSP();
497 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
498 }
499 OptionValidator *validator = def->validator;
500
501 if (!platform_sp && require_validation) {
502 // Caller requires validation but we cannot validate as we
503 // don't have the mandatory platform against which to
504 // validate.
505 error.SetErrorString("cannot validate options: "
506 "no platform available");
507 return error;
508 }
509
510 bool validation_failed = false;
511 if (platform_sp) {
512 // Ensure we have an execution context, empty or not.
513 ExecutionContext dummy_context;
514 ExecutionContext *exe_ctx_p =
515 execution_context ? execution_context : &dummy_context;
516 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
517 validation_failed = true;
518 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
519 def->long_option,
520 def->validator->LongConditionString());
521 }
522 }
523
524 // As long as validation didn't fail, we set the option value.
525 if (!validation_failed)
526 error = options.SetOptionValue(
527 long_options_index,
528 (def->option_has_arg == OptionParser::eNoArgument)
529 ? nullptr
530 : OptionParser::GetOptionArgument(),
531 execution_context);
532 } else {
533 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
534 }
535 if (error.Fail())
536 break;
537 }
538
539 // Update our ARGV now that get options has consumed all the options
540 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
541 UpdateArgsAfterOptionParsing();
542 return error;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000543}
544
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545void Args::Clear() {
Zachary Turner691405b2016-10-03 22:51:09 +0000546 m_entries.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09 +0000548 m_argv.push_back(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549}
550
551lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000552 llvm::StringRef s, lldb::addr_t fail_value,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 Error *error_ptr) {
554 bool error_set = false;
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000555 if (s.empty()) {
556 if (error_ptr)
557 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
558 s.str().c_str());
559 return fail_value;
560 }
Zachary Turner95eae422016-09-21 16:01:28 +0000561
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000562 llvm::StringRef sref = s;
563
564 lldb::addr_t addr = LLDB_INVALID_ADDRESS;
565 if (!s.getAsInteger(0, addr)) {
566 if (error_ptr)
567 error_ptr->Clear();
568 return addr;
569 }
570
571 // Try base 16 with no prefix...
572 if (!s.getAsInteger(16, addr)) {
573 if (error_ptr)
574 error_ptr->Clear();
575 return addr;
576 }
577
578 Target *target = nullptr;
579 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
580 if (error_ptr)
581 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
582 s.str().c_str());
583 return fail_value;
584 }
585
586 lldb::ValueObjectSP valobj_sp;
587 EvaluateExpressionOptions options;
588 options.SetCoerceToId(false);
589 options.SetUnwindOnError(true);
590 options.SetKeepInMemory(false);
591 options.SetTryAllThreads(true);
592
593 ExpressionResults expr_result =
594 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
595
596 bool success = false;
597 if (expr_result == eExpressionCompleted) {
598 if (valobj_sp)
599 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
600 valobj_sp->GetDynamicValueType(), true);
601 // Get the address to watch.
602 if (valobj_sp)
603 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
604 if (success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 if (error_ptr)
606 error_ptr->Clear();
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000607 return addr;
608 } else {
609 if (error_ptr) {
610 error_set = true;
611 error_ptr->SetErrorStringWithFormat(
612 "address expression \"%s\" resulted in a value whose type "
613 "can't be converted to an address: %s",
Zachary Turnercb3c9f62016-11-08 22:23:50 +0000614 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 }
617
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000618 } else {
619 // Since the compiler can't handle things like "main + 12" we should
620 // try to do this for now. The compiler doesn't like adding offsets
621 // to function pointer types.
622 static RegularExpression g_symbol_plus_offset_regex(
623 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
624 RegularExpression::Match regex_match(3);
625 if (g_symbol_plus_offset_regex.Execute(sref, &regex_match)) {
626 uint64_t offset = 0;
627 bool add = true;
628 std::string name;
629 std::string str;
630 if (regex_match.GetMatchAtIndex(s, 1, name)) {
631 if (regex_match.GetMatchAtIndex(s, 2, str)) {
632 add = str[0] == '+';
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000634 if (regex_match.GetMatchAtIndex(s, 3, str)) {
635 offset = StringConvert::ToUInt64(str.c_str(), 0, 0, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000637 if (success) {
638 Error error;
639 addr = StringToAddress(exe_ctx, name.c_str(),
640 LLDB_INVALID_ADDRESS, &error);
641 if (addr != LLDB_INVALID_ADDRESS) {
642 if (add)
643 return addr + offset;
644 else
645 return addr - offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 }
647 }
648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 }
650 }
651 }
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000652
653 if (error_ptr) {
654 error_set = true;
655 error_ptr->SetErrorStringWithFormat(
Zachary Turnercb3c9f62016-11-08 22:23:50 +0000656 "address expression \"%s\" evaluation failed", s.str().c_str());
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000657 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 }
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000659
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 if (error_ptr) {
661 if (!error_set)
662 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
Zachary Turnercb3c9f62016-11-08 22:23:50 +0000663 s.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 }
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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
692 bool *success_ptr) {
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000693 if (success_ptr)
694 *success_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 ref = ref.trim();
696 if (ref.equals_lower("false") || ref.equals_lower("off") ||
697 ref.equals_lower("no") || ref.equals_lower("0")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 return false;
699 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
700 ref.equals_lower("yes") || ref.equals_lower("1")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 return true;
702 }
703 if (success_ptr)
704 *success_ptr = false;
705 return fail_value;
706}
707
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000708char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 if (success_ptr)
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000710 *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];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717}
718
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000719bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
720 uint32_t &minor, uint32_t &update) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 major = UINT32_MAX;
722 minor = UINT32_MAX;
723 update = UINT32_MAX;
724
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000725 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;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740}
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
Zachary Turner8cef4b02016-09-23 17:48:13 +0000780int64_t Args::StringToOptionEnum(llvm::StringRef s,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 OptionEnumValueElement *enum_values,
782 int32_t fail_value, Error &error) {
Zachary Turner8cef4b02016-09-23 17:48:13 +0000783 error.Clear();
784 if (!enum_values) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 error.SetErrorString("invalid enumeration argument");
Zachary Turner8cef4b02016-09-23 17:48:13 +0000786 return fail_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 }
Zachary Turner8cef4b02016-09-23 17:48:13 +0000788
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 }
Zachary Turnerc1564272016-11-16 21:15:24 +0000805 error.SetErrorString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 return fail_value;
807}
808
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000809lldb::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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 if (success_ptr)
823 *success_ptr = false;
824 return fail_value;
825}
826
827Error Args::StringToFormat(const char *s, lldb::Format &format,
828 size_t *byte_size_ptr) {
829 format = eFormatInvalid;
830 Error 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)
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");
Zachary Turnerc1564272016-11-16 21:15:24 +0000861 error.SetErrorString(error_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 }
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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872lldb::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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
883 if (s.empty())
884 return LLDB_INVALID_REGNUM;
885 uint32_t result = llvm::StringSwitch<uint32_t>(s)
886 .Case("pc", LLDB_REGNUM_GENERIC_PC)
887 .Case("sp", LLDB_REGNUM_GENERIC_SP)
888 .Case("fp", LLDB_REGNUM_GENERIC_FP)
889 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
890 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
891 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
892 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
893 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
894 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
895 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
896 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
897 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
898 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
899 .Default(LLDB_INVALID_REGNUM);
900 return result;
901}
902
Zachary Turner5c725f32016-09-19 21:56:59 +0000903void Args::AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
904 llvm::StringRef new_value) {
Todd Fiala36bf6a42016-09-22 16:00:01 +0000905 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 return;
907
908 // Build the new entry.
Zachary Turner5c725f32016-09-19 21:56:59 +0000909 std::string var_string(env_var_name);
Todd Fiala36bf6a42016-09-22 16:00:01 +0000910 if (!new_value.empty()) {
911 var_string += "=";
912 var_string += new_value;
913 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914
Zachary Turner5c725f32016-09-19 21:56:59 +0000915 size_t index = 0;
916 if (ContainsEnvironmentVariable(env_var_name, &index)) {
917 ReplaceArgumentAtIndex(index, var_string);
918 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 }
920
921 // We didn't find it. Append it instead.
Zachary Turner5c725f32016-09-19 21:56:59 +0000922 AppendArgument(var_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923}
924
Zachary Turner5c725f32016-09-19 21:56:59 +0000925bool Args::ContainsEnvironmentVariable(llvm::StringRef env_var_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 size_t *argument_index) const {
927 // Validate args.
Zachary Turner5c725f32016-09-19 21:56:59 +0000928 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929 return false;
930
931 // Check each arg to see if it matches the env var name.
Zachary Turner11eb9c62016-10-05 20:03:37 +0000932 for (auto arg : llvm::enumerate(m_entries)) {
Zachary Turner5c725f32016-09-19 21:56:59 +0000933 llvm::StringRef name, value;
Zachary Turner11eb9c62016-10-05 20:03:37 +0000934 std::tie(name, value) = arg.Value.ref.split('=');
935 if (name != env_var_name)
936 continue;
937
938 if (argument_index)
939 *argument_index = arg.Index;
940 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 }
942
943 // We didn't find a match.
944 return false;
945}
946
947size_t Args::FindArgumentIndexForOption(Option *long_options,
Zachary Turner11eb9c62016-10-05 20:03:37 +0000948 int long_options_index) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 char short_buffer[3];
950 char long_buffer[255];
951 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
952 long_options[long_options_index].val);
953 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
954 long_options[long_options_index].definition->long_option);
Zachary Turner11eb9c62016-10-05 20:03:37 +0000955
956 for (auto entry : llvm::enumerate(m_entries)) {
957 if (entry.Value.ref.startswith(short_buffer) ||
958 entry.Value.ref.startswith(long_buffer))
959 return entry.Index;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 }
961
Zachary Turner11eb9c62016-10-05 20:03:37 +0000962 return size_t(-1);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963}
964
965bool Args::IsPositionalArgument(const char *arg) {
966 if (arg == nullptr)
967 return false;
968
969 bool is_positional = true;
970 const char *cptr = arg;
971
972 if (cptr[0] == '%') {
973 ++cptr;
974 while (isdigit(cptr[0]))
975 ++cptr;
976 if (cptr[0] != '\0')
977 is_positional = false;
978 } else
979 is_positional = false;
980
981 return is_positional;
982}
983
Zachary Turnera4496982016-10-05 21:14:38 +0000984std::string Args::ParseAliasOptions(Options &options,
985 CommandReturnObject &result,
986 OptionArgVector *option_arg_vector,
987 llvm::StringRef raw_input_string) {
988 std::string result_string(raw_input_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 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);
Zachary Turnera4496982016-10-05 21:14:38 +0000996 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 }
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;
Zachary Turnerc1564272016-11-16 21:15:24 +00001022 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1023 sstr.GetString(), long_options,
1024 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025
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 Turnera4496982016-10-05 21:14:38 +00001056 return result_string;
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);
Zachary Turnera4496982016-10-05 21:14:38 +00001073 return result_string;
Zachary Turner5c28c662016-10-03 23:20:36 +00001074 }
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);
Zachary Turnera4496982016-10-05 21:14:38 +00001086 return result_string;
Zachary Turner5c28c662016-10-03 23:20:36 +00001087 }
1088 if (!option_arg)
1089 option_arg = "<no-argument>";
Zachary Turnerc1564272016-11-16 21:15:24 +00001090 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1091 option_arg);
Zachary Turner5c28c662016-10-03 23:20:36 +00001092
1093 // Find option in the argument list; also see if it was supposed to take
1094 // an argument and if one was supplied. Remove option (and argument, if
1095 // given) from the argument list. Also remove them from the
1096 // raw_input_string, if one was passed in.
1097 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
Zachary Turner11eb9c62016-10-05 20:03:37 +00001098 if (idx == size_t(-1))
1099 continue;
1100
Zachary Turnera4496982016-10-05 21:14:38 +00001101 if (!result_string.empty()) {
Zachary Turner2c84f902016-12-09 05:46:41 +00001102 auto tmp_arg = m_entries[idx].ref;
Zachary Turnera4496982016-10-05 21:14:38 +00001103 size_t pos = result_string.find(tmp_arg);
Zachary Turner11eb9c62016-10-05 20:03:37 +00001104 if (pos != std::string::npos)
Zachary Turner2c84f902016-12-09 05:46:41 +00001105 result_string.erase(pos, tmp_arg.size());
Zachary Turner11eb9c62016-10-05 20:03:37 +00001106 }
1107 ReplaceArgumentAtIndex(idx, llvm::StringRef());
1108 if ((long_options[long_options_index].definition->option_has_arg !=
1109 OptionParser::eNoArgument) &&
1110 (OptionParser::GetOptionArgument() != nullptr) &&
1111 (idx + 1 < GetArgumentCount()) &&
Zachary Turner2c84f902016-12-09 05:46:41 +00001112 (m_entries[idx + 1].ref == OptionParser::GetOptionArgument())) {
Zachary Turnera4496982016-10-05 21:14:38 +00001113 if (result_string.size() > 0) {
Zachary Turner2c84f902016-12-09 05:46:41 +00001114 auto tmp_arg = m_entries[idx + 1].ref;
Zachary Turnera4496982016-10-05 21:14:38 +00001115 size_t pos = result_string.find(tmp_arg);
Zachary Turner5c28c662016-10-03 23:20:36 +00001116 if (pos != std::string::npos)
Zachary Turner2c84f902016-12-09 05:46:41 +00001117 result_string.erase(pos, tmp_arg.size());
Zachary Turner5c28c662016-10-03 23:20:36 +00001118 }
Zachary Turner11eb9c62016-10-05 20:03:37 +00001119 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 }
Zachary Turnera4496982016-10-05 21:14:38 +00001122 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123}
1124
1125void Args::ParseArgsForCompletion(Options &options,
1126 OptionElementVector &option_element_vector,
1127 uint32_t cursor_index) {
1128 StreamString sstr;
1129 Option *long_options = options.GetLongOptions();
1130 option_element_vector.clear();
1131
1132 if (long_options == nullptr) {
1133 return;
1134 }
1135
1136 // Leading : tells getopt to return a : for a missing option argument AND
1137 // to suppress error messages.
1138
1139 sstr << ":";
1140 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1141 if (long_options[i].flag == nullptr) {
1142 sstr << (char)long_options[i].val;
1143 switch (long_options[i].definition->option_has_arg) {
1144 default:
1145 case OptionParser::eNoArgument:
1146 break;
1147 case OptionParser::eRequiredArgument:
1148 sstr << ":";
1149 break;
1150 case OptionParser::eOptionalArgument:
1151 sstr << "::";
1152 break;
1153 }
1154 }
1155 }
1156
1157 std::unique_lock<std::mutex> lock;
1158 OptionParser::Prepare(lock);
1159 OptionParser::EnableError(false);
1160
1161 int val;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001162 auto opt_defs = options.GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163
1164 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
Zachary Turner11eb9c62016-10-05 20:03:37 +00001165 // options to the front. So we have to build another Arg and pass that to
1166 // OptionParser::Parse so it doesn't change the one we have.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167
Zachary Turner11eb9c62016-10-05 20:03:37 +00001168 std::vector<char *> dummy_vec = m_argv;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169
1170 bool failed_once = false;
1171 uint32_t dash_dash_pos = -1;
1172
1173 while (1) {
1174 bool missing_argument = false;
1175 int long_options_index = -1;
1176
Zachary Turnere706c1d2016-11-13 04:24:38 +00001177 val = OptionParser::Parse(dummy_vec.size() - 1, &dummy_vec[0],
1178 sstr.GetString(), long_options,
1179 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180
1181 if (val == -1) {
1182 // When we're completing a "--" which is the last option on line,
1183 if (failed_once)
1184 break;
1185
1186 failed_once = true;
1187
1188 // If this is a bare "--" we mark it as such so we can complete it
1189 // successfully later.
1190 // Handling the "--" is a little tricky, since that may mean end of
1191 // options or arguments, or the
1192 // user might want to complete options by long name. I make this work by
1193 // checking whether the
1194 // cursor is in the "--" argument, and if so I assume we're completing the
1195 // long option, otherwise
1196 // I let it pass to OptionParser::Parse which will terminate the option
1197 // parsing.
1198 // Note, in either case we continue parsing the line so we can figure out
1199 // what other options
1200 // were passed. This will be useful when we come to restricting
1201 // completions based on what other
1202 // options we've seen on the line.
1203
1204 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1205 dummy_vec.size() - 1 &&
1206 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1207 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1208 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1209 cursor_index) {
1210 option_element_vector.push_back(
1211 OptionArgElement(OptionArgElement::eBareDoubleDash,
1212 OptionParser::GetOptionIndex() - 1,
1213 OptionArgElement::eBareDoubleDash));
1214 continue;
1215 } else
1216 break;
1217 } else
1218 break;
1219 } else if (val == '?') {
1220 option_element_vector.push_back(
1221 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1222 OptionParser::GetOptionIndex() - 1,
1223 OptionArgElement::eUnrecognizedArg));
1224 continue;
1225 } else if (val == 0) {
1226 continue;
1227 } else if (val == ':') {
1228 // This is a missing argument.
1229 val = OptionParser::GetOptionErrorCause();
1230 missing_argument = true;
1231 }
1232
1233 ((Options *)&options)->OptionSeen(val);
1234
1235 // Look up the long option index
1236 if (long_options_index == -1) {
1237 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1238 long_options[j].val;
1239 ++j) {
1240 if (long_options[j].val == val) {
1241 long_options_index = j;
1242 break;
1243 }
1244 }
1245 }
1246
1247 // See if the option takes an argument, and see if one was supplied.
1248 if (long_options_index >= 0) {
1249 int opt_defs_index = -1;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001250 for (size_t i = 0; i < opt_defs.size(); i++) {
1251 if (opt_defs[i].short_option != val)
1252 continue;
1253 opt_defs_index = i;
1254 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 }
1256
1257 const OptionDefinition *def = long_options[long_options_index].definition;
1258 int has_arg =
1259 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1260 switch (has_arg) {
1261 case OptionParser::eNoArgument:
1262 option_element_vector.push_back(OptionArgElement(
1263 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1264 break;
1265 case OptionParser::eRequiredArgument:
1266 if (OptionParser::GetOptionArgument() != nullptr) {
1267 int arg_index;
1268 if (missing_argument)
1269 arg_index = -1;
1270 else
1271 arg_index = OptionParser::GetOptionIndex() - 1;
1272
1273 option_element_vector.push_back(OptionArgElement(
1274 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1275 } else {
1276 option_element_vector.push_back(OptionArgElement(
1277 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1278 }
1279 break;
1280 case OptionParser::eOptionalArgument:
1281 if (OptionParser::GetOptionArgument() != nullptr) {
1282 option_element_vector.push_back(OptionArgElement(
1283 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1284 OptionParser::GetOptionIndex() - 1));
1285 } else {
1286 option_element_vector.push_back(OptionArgElement(
1287 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1288 OptionParser::GetOptionIndex() - 1));
1289 }
1290 break;
1291 default:
1292 // The options table is messed up. Here we'll just continue
1293 option_element_vector.push_back(
1294 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1295 OptionParser::GetOptionIndex() - 1,
1296 OptionArgElement::eUnrecognizedArg));
1297 break;
1298 }
1299 } else {
1300 option_element_vector.push_back(
1301 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1302 OptionParser::GetOptionIndex() - 1,
1303 OptionArgElement::eUnrecognizedArg));
1304 }
1305 }
1306
1307 // Finally we have to handle the case where the cursor index points at a
1308 // single "-". We want to mark that in
1309 // the option_element_vector, but only if it is not after the "--". But it
1310 // turns out that OptionParser::Parse just ignores
1311 // an isolated "-". So we have to look it up by hand here. We only care if
1312 // it is AT the cursor position.
1313 // Note, a single quoted dash is not the same as a single dash...
1314
Zachary Turner691405b2016-10-03 22:51:09 +00001315 const ArgEntry &cursor = m_entries[cursor_index];
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1317 cursor_index < dash_dash_pos) &&
Zachary Turner691405b2016-10-03 22:51:09 +00001318 cursor.quote == '\0' && cursor.ref == "-") {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319 option_element_vector.push_back(
1320 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1321 OptionArgElement::eBareDash));
1322 }
1323}
1324
1325void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1326 dst.clear();
1327 if (src) {
1328 for (const char *p = src; *p != '\0'; ++p) {
1329 size_t non_special_chars = ::strcspn(p, "\\");
1330 if (non_special_chars > 0) {
1331 dst.append(p, non_special_chars);
1332 p += non_special_chars;
1333 if (*p == '\0')
1334 break;
1335 }
1336
1337 if (*p == '\\') {
1338 ++p; // skip the slash
1339 switch (*p) {
1340 case 'a':
1341 dst.append(1, '\a');
1342 break;
1343 case 'b':
1344 dst.append(1, '\b');
1345 break;
1346 case 'f':
1347 dst.append(1, '\f');
1348 break;
1349 case 'n':
1350 dst.append(1, '\n');
1351 break;
1352 case 'r':
1353 dst.append(1, '\r');
1354 break;
1355 case 't':
1356 dst.append(1, '\t');
1357 break;
1358 case 'v':
1359 dst.append(1, '\v');
1360 break;
1361 case '\\':
1362 dst.append(1, '\\');
1363 break;
1364 case '\'':
1365 dst.append(1, '\'');
1366 break;
1367 case '"':
1368 dst.append(1, '"');
1369 break;
1370 case '0':
1371 // 1 to 3 octal chars
1372 {
1373 // Make a string that can hold onto the initial zero char,
1374 // up to 3 octal digits, and a terminating NULL.
1375 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1376
1377 int i;
1378 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1379 oct_str[i] = p[i];
1380
1381 // We don't want to consume the last octal character since
1382 // the main for loop will do this for us, so we advance p by
1383 // one less than i (even if i is zero)
1384 p += i - 1;
1385 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1386 if (octal_value <= UINT8_MAX) {
1387 dst.append(1, (char)octal_value);
1388 }
1389 }
1390 break;
1391
1392 case 'x':
1393 // hex number in the format
1394 if (isxdigit(p[1])) {
1395 ++p; // Skip the 'x'
1396
1397 // Make a string that can hold onto two hex chars plus a
1398 // NULL terminator
1399 char hex_str[3] = {*p, '\0', '\0'};
1400 if (isxdigit(p[1])) {
1401 ++p; // Skip the first of the two hex chars
1402 hex_str[1] = *p;
1403 }
1404
1405 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1406 if (hex_value <= UINT8_MAX)
1407 dst.append(1, (char)hex_value);
1408 } else {
1409 dst.append(1, 'x');
1410 }
1411 break;
1412
1413 default:
1414 // Just desensitize any other character by just printing what
1415 // came after the '\'
1416 dst.append(1, *p);
1417 break;
1418 }
1419 }
1420 }
1421 }
1422}
1423
1424void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1425 dst.clear();
1426 if (src) {
1427 for (const char *p = src; *p != '\0'; ++p) {
1428 if (isprint8(*p))
1429 dst.append(1, *p);
1430 else {
1431 switch (*p) {
1432 case '\a':
1433 dst.append("\\a");
1434 break;
1435 case '\b':
1436 dst.append("\\b");
1437 break;
1438 case '\f':
1439 dst.append("\\f");
1440 break;
1441 case '\n':
1442 dst.append("\\n");
1443 break;
1444 case '\r':
1445 dst.append("\\r");
1446 break;
1447 case '\t':
1448 dst.append("\\t");
1449 break;
1450 case '\v':
1451 dst.append("\\v");
1452 break;
1453 case '\'':
1454 dst.append("\\'");
1455 break;
1456 case '"':
1457 dst.append("\\\"");
1458 break;
1459 case '\\':
1460 dst.append("\\\\");
1461 break;
1462 default: {
1463 // Just encode as octal
1464 dst.append("\\0");
1465 char octal_str[32];
1466 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1467 dst.append(octal_str);
1468 } break;
1469 }
1470 }
1471 }
1472 }
1473}
1474
1475std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1476 char quote_char) {
1477 const char *chars_to_escape = nullptr;
1478 switch (quote_char) {
1479 case '\0':
1480 chars_to_escape = " \t\\'\"`";
1481 break;
1482 case '\'':
1483 chars_to_escape = "";
1484 break;
1485 case '"':
1486 chars_to_escape = "$\"`\\";
1487 break;
1488 default:
1489 assert(false && "Unhandled quote character");
1490 }
1491
1492 std::string res;
1493 res.reserve(arg.size());
1494 for (char c : arg) {
1495 if (::strchr(chars_to_escape, c))
1496 res.push_back('\\');
1497 res.push_back(c);
1498 }
1499 return res;
1500}