blob: c428a2352ca39e4c961c3f928340a2dc7d1c6bfd [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();
Ed Maste9a605f92016-10-06 17:55:22 +0000216 s.Printf("%s[%zi]=\"%*s\"\n", label_name, i++, int(entry.ref.size()),
Zachary Turner691405b2016-10-03 22:51:09 +0000217 entry.ref.data());
218 }
219 s.Printf("%s[%zi]=NULL\n", label_name, i);
220 s.EOL();
221}
222
223bool Args::GetCommandString(std::string &command) const {
224 command.clear();
225
226 for (size_t i = 0; i < m_entries.size(); ++i) {
227 if (i > 0)
228 command += ' ';
229 command += m_entries[i].ref;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 }
231
Zachary Turner691405b2016-10-03 22:51:09 +0000232 return !m_entries.empty();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233}
234
Zachary Turner691405b2016-10-03 22:51:09 +0000235bool Args::GetQuotedCommandString(std::string &command) const {
236 command.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237
Zachary Turner691405b2016-10-03 22:51:09 +0000238 for (size_t i = 0; i < m_entries.size(); ++i) {
239 if (i > 0)
240 command += ' ';
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241
Zachary Turner691405b2016-10-03 22:51:09 +0000242 if (m_entries[i].quote) {
243 command += m_entries[i].quote;
244 command += m_entries[i].ref;
245 command += m_entries[i].quote;
246 } else {
247 command += m_entries[i].ref;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 }
Pavel Labath00b7f952015-03-02 12:46:22 +0000250
Zachary Turner691405b2016-10-03 22:51:09 +0000251 return !m_entries.empty();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000252}
253
Zachary Turner691405b2016-10-03 22:51:09 +0000254void Args::SetCommandString(llvm::StringRef command) {
255 Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09 +0000257
258 static const char *k_space_separators = " \t";
259 command = command.ltrim(k_space_separators);
260 std::string arg;
261 char quote;
262 while (!command.empty()) {
263 std::tie(arg, quote, command) = ParseSingleArgument(command);
264 m_entries.emplace_back(arg, quote);
265 m_argv.push_back(m_entries.back().data());
266 command = command.ltrim(k_space_separators);
267 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269}
270
Zachary Turner691405b2016-10-03 22:51:09 +0000271void Args::UpdateArgsAfterOptionParsing() {
272 assert(!m_argv.empty());
273 assert(m_argv.back() == nullptr);
274
275 // Now m_argv might be out of date with m_entries, so we need to fix that.
276 // This happens because getopt_long_only may permute the order of the
277 // arguments in argv, so we need to re-order the quotes and the refs array
278 // to match.
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000279 for (size_t i = 0; i < m_argv.size() - 1; ++i) {
Zachary Turner691405b2016-10-03 22:51:09 +0000280 const char *argv = m_argv[i];
281 auto pos =
282 std::find_if(m_entries.begin() + i, m_entries.end(),
283 [argv](const ArgEntry &D) { return D.c_str() == argv; });
284 assert(pos != m_entries.end());
285 size_t distance = std::distance(m_entries.begin(), pos);
286 if (i == distance)
287 continue;
288
289 assert(distance > i);
290
291 std::swap(m_entries[i], m_entries[distance]);
292 assert(m_entries[i].ref.data() == m_argv[i]);
293 }
294 m_entries.resize(m_argv.size() - 1);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000295}
296
Zachary Turner691405b2016-10-03 22:51:09 +0000297size_t Args::GetArgumentCount() const { return m_entries.size(); }
298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299const char *Args::GetArgumentAtIndex(size_t idx) const {
300 if (idx < m_argv.size())
301 return m_argv[idx];
302 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000303}
304
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
Zachary Turner691405b2016-10-03 22:51:09 +0000306 if (idx < m_entries.size())
307 return m_entries[idx].quote;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 return '\0';
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000309}
310
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311char **Args::GetArgumentVector() {
Zachary Turner691405b2016-10-03 22:51:09 +0000312 assert(!m_argv.empty());
313 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
314 // when argv or envp is null. So the code below is actually wrong. However,
315 // other code in LLDB depends on it being null. The code has been acting this
316 // way for some time, so it makes sense to leave it this way until someone
317 // has the time to come along and fix it.
318 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319}
320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321const char **Args::GetConstArgumentVector() const {
Zachary Turner691405b2016-10-03 22:51:09 +0000322 assert(!m_argv.empty());
323 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
324 : nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325}
326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327void Args::Shift() {
328 // Don't pop the last NULL terminator from the argv array
Zachary Turner691405b2016-10-03 22:51:09 +0000329 if (m_entries.empty())
330 return;
331 m_argv.erase(m_argv.begin());
332 m_entries.erase(m_entries.begin());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000333}
334
Justin Bogner812101d2016-10-17 06:17:56 +0000335void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
336 InsertArgumentAtIndex(0, arg_str, quote_char);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337}
338
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339void Args::AppendArguments(const Args &rhs) {
Zachary Turner691405b2016-10-03 22:51:09 +0000340 assert(m_argv.size() == m_entries.size() + 1);
341 assert(m_argv.back() == nullptr);
342 m_argv.pop_back();
343 for (auto &entry : rhs.m_entries) {
344 m_entries.emplace_back(entry.ref, entry.quote);
345 m_argv.push_back(m_entries.back().data());
346 }
347 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000348}
349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350void Args::AppendArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000351 size_t argc = ArgvToArgc(argv);
352
353 assert(m_argv.size() == m_entries.size() + 1);
354 assert(m_argv.back() == nullptr);
355 m_argv.pop_back();
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000356 for (auto arg : llvm::makeArrayRef(argv, argc)) {
357 m_entries.emplace_back(arg, '\0');
Zachary Turner691405b2016-10-03 22:51:09 +0000358 m_argv.push_back(m_entries.back().data());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 }
Zachary Turner691405b2016-10-03 22:51:09 +0000360
361 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000362}
363
Justin Bogner812101d2016-10-17 06:17:56 +0000364void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
365 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
Greg Clayton982c9762011-11-03 21:22:33 +0000366}
367
Justin Bogner812101d2016-10-17 06:17:56 +0000368void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
369 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09 +0000370 assert(m_argv.size() == m_entries.size() + 1);
371 assert(m_argv.back() == nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372
Zachary Turner691405b2016-10-03 22:51:09 +0000373 if (idx > m_entries.size())
Justin Bogner812101d2016-10-17 06:17:56 +0000374 return;
Zachary Turner691405b2016-10-03 22:51:09 +0000375 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
376 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377}
378
Justin Bogner812101d2016-10-17 06:17:56 +0000379void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
380 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09 +0000381 assert(m_argv.size() == m_entries.size() + 1);
382 assert(m_argv.back() == nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000383
Zachary Turner691405b2016-10-03 22:51:09 +0000384 if (idx >= m_entries.size())
Justin Bogner812101d2016-10-17 06:17:56 +0000385 return;
Zachary Turner691405b2016-10-03 22:51:09 +0000386
387 if (arg_str.size() > m_entries[idx].ref.size()) {
388 m_entries[idx] = ArgEntry(arg_str, quote_char);
389 m_argv[idx] = m_entries[idx].data();
390 } else {
391 const char *src_data = arg_str.data() ? arg_str.data() : "";
392 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
393 m_entries[idx].ptr[arg_str.size()] = 0;
394 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396}
397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398void Args::DeleteArgumentAtIndex(size_t idx) {
Zachary Turner691405b2016-10-03 22:51:09 +0000399 if (idx >= m_entries.size())
400 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401
Zachary Turner691405b2016-10-03 22:51:09 +0000402 m_argv.erase(m_argv.begin() + idx);
403 m_entries.erase(m_entries.begin() + idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000404}
405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406void Args::SetArguments(size_t argc, const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000407 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408
Zachary Turner691405b2016-10-03 22:51:09 +0000409 auto args = llvm::makeArrayRef(argv, argc);
410 m_entries.resize(argc);
411 m_argv.resize(argc + 1);
Zachary Turner5a8ad4592016-10-05 17:07:34 +0000412 for (size_t i = 0; i < args.size(); ++i) {
Zachary Turner691405b2016-10-03 22:51:09 +0000413 char quote =
414 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
415 ? args[i][0]
416 : '\0';
417
418 m_entries[i] = ArgEntry(args[i], quote);
419 m_argv[i] = m_entries[i].data();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421}
422
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423void Args::SetArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09 +0000424 SetArguments(ArgvToArgc(argv), argv);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000425}
426
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427Error Args::ParseOptions(Options &options, ExecutionContext *execution_context,
428 PlatformSP platform_sp, bool require_validation) {
429 StreamString sstr;
430 Error error;
431 Option *long_options = options.GetLongOptions();
432 if (long_options == nullptr) {
433 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000435 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 for (int i = 0; long_options[i].definition != nullptr; ++i) {
438 if (long_options[i].flag == nullptr) {
439 if (isprint8(long_options[i].val)) {
440 sstr << (char)long_options[i].val;
441 switch (long_options[i].definition->option_has_arg) {
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000442 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 case OptionParser::eNoArgument:
444 break;
445 case OptionParser::eRequiredArgument:
446 sstr << ':';
447 break;
448 case OptionParser::eOptionalArgument:
449 sstr << "::";
450 break;
451 }
452 }
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 }
455 std::unique_lock<std::mutex> lock;
456 OptionParser::Prepare(lock);
457 int val;
458 while (1) {
459 int long_options_index = -1;
Zachary Turnere706c1d2016-11-13 04:24:38 +0000460 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
461 sstr.GetString(), long_options,
462 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 if (val == -1)
464 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000465
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 // Did we get an error?
467 if (val == '?') {
468 error.SetErrorStringWithFormat("unknown or ambiguous option");
469 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000470 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 // The option auto-set itself
472 if (val == 0)
473 continue;
474
475 ((Options *)&options)->OptionSeen(val);
476
477 // Lookup the long option index
478 if (long_options_index == -1) {
479 for (int i = 0; long_options[i].definition || long_options[i].flag ||
480 long_options[i].val;
481 ++i) {
482 if (long_options[i].val == val) {
483 long_options_index = i;
484 break;
485 }
486 }
487 }
488 // Call the callback with the option
489 if (long_options_index >= 0 &&
490 long_options[long_options_index].definition) {
491 const OptionDefinition *def = long_options[long_options_index].definition;
492
493 if (!platform_sp) {
494 // User did not pass in an explicit platform. Try to grab
495 // from the execution context.
496 TargetSP target_sp =
497 execution_context ? execution_context->GetTargetSP() : TargetSP();
498 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
499 }
500 OptionValidator *validator = def->validator;
501
502 if (!platform_sp && require_validation) {
503 // Caller requires validation but we cannot validate as we
504 // don't have the mandatory platform against which to
505 // validate.
506 error.SetErrorString("cannot validate options: "
507 "no platform available");
508 return error;
509 }
510
511 bool validation_failed = false;
512 if (platform_sp) {
513 // Ensure we have an execution context, empty or not.
514 ExecutionContext dummy_context;
515 ExecutionContext *exe_ctx_p =
516 execution_context ? execution_context : &dummy_context;
517 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
518 validation_failed = true;
519 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
520 def->long_option,
521 def->validator->LongConditionString());
522 }
523 }
524
525 // As long as validation didn't fail, we set the option value.
526 if (!validation_failed)
527 error = options.SetOptionValue(
528 long_options_index,
529 (def->option_has_arg == OptionParser::eNoArgument)
530 ? nullptr
531 : OptionParser::GetOptionArgument(),
532 execution_context);
533 } else {
534 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
535 }
536 if (error.Fail())
537 break;
538 }
539
540 // Update our ARGV now that get options has consumed all the options
541 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
542 UpdateArgsAfterOptionParsing();
543 return error;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000544}
545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546void Args::Clear() {
Zachary Turner691405b2016-10-03 22:51:09 +0000547 m_entries.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09 +0000549 m_argv.push_back(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550}
551
552lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000553 llvm::StringRef s, lldb::addr_t fail_value,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 Error *error_ptr) {
555 bool error_set = false;
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000556 if (s.empty()) {
557 if (error_ptr)
558 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
559 s.str().c_str());
560 return fail_value;
561 }
Zachary Turner95eae422016-09-21 16:01:28 +0000562
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000563 llvm::StringRef sref = s;
564
565 lldb::addr_t addr = LLDB_INVALID_ADDRESS;
566 if (!s.getAsInteger(0, addr)) {
567 if (error_ptr)
568 error_ptr->Clear();
569 return addr;
570 }
571
572 // Try base 16 with no prefix...
573 if (!s.getAsInteger(16, addr)) {
574 if (error_ptr)
575 error_ptr->Clear();
576 return addr;
577 }
578
579 Target *target = nullptr;
580 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
581 if (error_ptr)
582 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
583 s.str().c_str());
584 return fail_value;
585 }
586
587 lldb::ValueObjectSP valobj_sp;
588 EvaluateExpressionOptions options;
589 options.SetCoerceToId(false);
590 options.SetUnwindOnError(true);
591 options.SetKeepInMemory(false);
592 options.SetTryAllThreads(true);
593
594 ExpressionResults expr_result =
595 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
596
597 bool success = false;
598 if (expr_result == eExpressionCompleted) {
599 if (valobj_sp)
600 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
601 valobj_sp->GetDynamicValueType(), true);
602 // Get the address to watch.
603 if (valobj_sp)
604 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
605 if (success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606 if (error_ptr)
607 error_ptr->Clear();
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000608 return addr;
609 } else {
610 if (error_ptr) {
611 error_set = true;
612 error_ptr->SetErrorStringWithFormat(
613 "address expression \"%s\" resulted in a value whose type "
614 "can't be converted to an address: %s",
Zachary Turnercb3c9f62016-11-08 22:23:50 +0000615 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 }
618
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000619 } else {
620 // Since the compiler can't handle things like "main + 12" we should
621 // try to do this for now. The compiler doesn't like adding offsets
622 // to function pointer types.
623 static RegularExpression g_symbol_plus_offset_regex(
624 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
625 RegularExpression::Match regex_match(3);
626 if (g_symbol_plus_offset_regex.Execute(sref, &regex_match)) {
627 uint64_t offset = 0;
628 bool add = true;
629 std::string name;
630 std::string str;
631 if (regex_match.GetMatchAtIndex(s, 1, name)) {
632 if (regex_match.GetMatchAtIndex(s, 2, str)) {
633 add = str[0] == '+';
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000635 if (regex_match.GetMatchAtIndex(s, 3, str)) {
636 offset = StringConvert::ToUInt64(str.c_str(), 0, 0, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000638 if (success) {
639 Error error;
640 addr = StringToAddress(exe_ctx, name.c_str(),
641 LLDB_INVALID_ADDRESS, &error);
642 if (addr != LLDB_INVALID_ADDRESS) {
643 if (add)
644 return addr + offset;
645 else
646 return addr - offset;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 }
648 }
649 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 }
651 }
652 }
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000653
654 if (error_ptr) {
655 error_set = true;
656 error_ptr->SetErrorStringWithFormat(
Zachary Turnercb3c9f62016-11-08 22:23:50 +0000657 "address expression \"%s\" evaluation failed", s.str().c_str());
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 }
Zachary Turnerc5d7df92016-11-08 04:52:16 +0000660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 if (error_ptr) {
662 if (!error_set)
663 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
Zachary Turnercb3c9f62016-11-08 22:23:50 +0000664 s.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 }
666 return fail_value;
667}
668
669const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
670 bool return_null_if_empty) {
671 static const char *k_white_space = " \t\v";
672 if (!s.empty()) {
673 if (leading) {
674 size_t pos = s.find_first_not_of(k_white_space);
675 if (pos == std::string::npos)
676 s.clear();
677 else if (pos > 0)
678 s.erase(0, pos);
679 }
680
681 if (trailing) {
682 size_t rpos = s.find_last_not_of(k_white_space);
683 if (rpos != std::string::npos && rpos + 1 < s.size())
684 s.erase(rpos + 1);
685 }
686 }
687 if (return_null_if_empty && s.empty())
688 return nullptr;
689 return s.c_str();
690}
691
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
693 bool *success_ptr) {
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000694 if (success_ptr)
695 *success_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 ref = ref.trim();
697 if (ref.equals_lower("false") || ref.equals_lower("off") ||
698 ref.equals_lower("no") || ref.equals_lower("0")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 return false;
700 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
701 ref.equals_lower("yes") || ref.equals_lower("1")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 return true;
703 }
704 if (success_ptr)
705 *success_ptr = false;
706 return fail_value;
707}
708
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000709char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 if (success_ptr)
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000711 *success_ptr = false;
712 if (s.size() != 1)
713 return fail_value;
714
715 if (success_ptr)
716 *success_ptr = true;
717 return s[0];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718}
719
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000720bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
721 uint32_t &minor, uint32_t &update) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 major = UINT32_MAX;
723 minor = UINT32_MAX;
724 update = UINT32_MAX;
725
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000726 if (string.empty())
727 return false;
728
729 llvm::StringRef major_str, minor_str, update_str;
730
731 std::tie(major_str, minor_str) = string.split('.');
732 std::tie(minor_str, update_str) = minor_str.split('.');
733 if (major_str.getAsInteger(10, major))
734 return false;
735 if (!minor_str.empty() && minor_str.getAsInteger(10, minor))
736 return false;
737 if (!update_str.empty() && update_str.getAsInteger(10, update))
738 return false;
739
740 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741}
742
743const char *Args::GetShellSafeArgument(const FileSpec &shell,
744 const char *unsafe_arg,
745 std::string &safe_arg) {
746 struct ShellDescriptor {
747 ConstString m_basename;
748 const char *m_escapables;
749 };
750
751 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
752 {ConstString("tcsh"), " '\"<>()&$"},
753 {ConstString("sh"), " '\"<>()&"}};
754
755 // safe minimal set
756 const char *escapables = " '\"";
757
758 if (auto basename = shell.GetFilename()) {
759 for (const auto &Shell : g_Shells) {
760 if (Shell.m_basename == basename) {
761 escapables = Shell.m_escapables;
762 break;
763 }
764 }
765 }
766
767 safe_arg.assign(unsafe_arg);
768 size_t prev_pos = 0;
769 while (prev_pos < safe_arg.size()) {
770 // Escape spaces and quotes
771 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
772 if (pos != std::string::npos) {
773 safe_arg.insert(pos, 1, '\\');
774 prev_pos = pos + 2;
775 } else
776 break;
777 }
778 return safe_arg.c_str();
779}
780
Zachary Turner8cef4b02016-09-23 17:48:13 +0000781int64_t Args::StringToOptionEnum(llvm::StringRef s,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782 OptionEnumValueElement *enum_values,
783 int32_t fail_value, Error &error) {
Zachary Turner8cef4b02016-09-23 17:48:13 +0000784 error.Clear();
785 if (!enum_values) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 error.SetErrorString("invalid enumeration argument");
Zachary Turner8cef4b02016-09-23 17:48:13 +0000787 return fail_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 }
Zachary Turner8cef4b02016-09-23 17:48:13 +0000789
790 if (s.empty()) {
791 error.SetErrorString("empty enumeration string");
792 return fail_value;
793 }
794
795 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
796 llvm::StringRef this_enum(enum_values[i].string_value);
797 if (this_enum.startswith(s))
798 return enum_values[i].value;
799 }
800
801 StreamString strm;
802 strm.PutCString("invalid enumeration value, valid values are: ");
803 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
804 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
805 }
Zachary Turnerc1564272016-11-16 21:15:24 +0000806 error.SetErrorString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 return fail_value;
808}
809
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000810lldb::ScriptLanguage
811Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
812 bool *success_ptr) {
813 if (success_ptr)
814 *success_ptr = true;
815
816 if (s.equals_lower("python"))
817 return eScriptLanguagePython;
818 if (s.equals_lower("default"))
819 return eScriptLanguageDefault;
820 if (s.equals_lower("none"))
821 return eScriptLanguageNone;
822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 if (success_ptr)
824 *success_ptr = false;
825 return fail_value;
826}
827
828Error Args::StringToFormat(const char *s, lldb::Format &format,
829 size_t *byte_size_ptr) {
830 format = eFormatInvalid;
831 Error error;
832
833 if (s && s[0]) {
834 if (byte_size_ptr) {
835 if (isdigit(s[0])) {
836 char *format_char = nullptr;
837 unsigned long byte_size = ::strtoul(s, &format_char, 0);
838 if (byte_size != ULONG_MAX)
839 *byte_size_ptr = byte_size;
840 s = format_char;
841 } else
842 *byte_size_ptr = 0;
843 }
844
845 const bool partial_match_ok = true;
846 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
847 StreamString error_strm;
848 error_strm.Printf(
849 "Invalid format character or name '%s'. Valid values are:\n", s);
850 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
851 char format_char = FormatManager::GetFormatAsFormatChar(f);
852 if (format_char)
853 error_strm.Printf("'%c' or ", format_char);
854
855 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
856 error_strm.EOL();
857 }
858
859 if (byte_size_ptr)
860 error_strm.PutCString(
861 "An optional byte size can precede the format character.\n");
Zachary Turnerc1564272016-11-16 21:15:24 +0000862 error.SetErrorString(error_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 }
864
865 if (error.Fail())
866 return error;
867 } else {
868 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
869 }
870 return error;
871}
872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
874 lldb::Encoding fail_value) {
875 return llvm::StringSwitch<lldb::Encoding>(s)
876 .Case("uint", eEncodingUint)
877 .Case("sint", eEncodingSint)
878 .Case("ieee754", eEncodingIEEE754)
879 .Case("vector", eEncodingVector)
880 .Default(fail_value);
881}
882
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
884 if (s.empty())
885 return LLDB_INVALID_REGNUM;
886 uint32_t result = llvm::StringSwitch<uint32_t>(s)
887 .Case("pc", LLDB_REGNUM_GENERIC_PC)
888 .Case("sp", LLDB_REGNUM_GENERIC_SP)
889 .Case("fp", LLDB_REGNUM_GENERIC_FP)
890 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
891 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
892 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
893 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
894 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
895 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
896 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
897 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
898 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
899 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
900 .Default(LLDB_INVALID_REGNUM);
901 return result;
902}
903
Zachary Turner5c725f32016-09-19 21:56:59 +0000904void Args::AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
905 llvm::StringRef new_value) {
Todd Fiala36bf6a42016-09-22 16:00:01 +0000906 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907 return;
908
909 // Build the new entry.
Zachary Turner5c725f32016-09-19 21:56:59 +0000910 std::string var_string(env_var_name);
Todd Fiala36bf6a42016-09-22 16:00:01 +0000911 if (!new_value.empty()) {
912 var_string += "=";
913 var_string += new_value;
914 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915
Zachary Turner5c725f32016-09-19 21:56:59 +0000916 size_t index = 0;
917 if (ContainsEnvironmentVariable(env_var_name, &index)) {
918 ReplaceArgumentAtIndex(index, var_string);
919 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 }
921
922 // We didn't find it. Append it instead.
Zachary Turner5c725f32016-09-19 21:56:59 +0000923 AppendArgument(var_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924}
925
Zachary Turner5c725f32016-09-19 21:56:59 +0000926bool Args::ContainsEnvironmentVariable(llvm::StringRef env_var_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 size_t *argument_index) const {
928 // Validate args.
Zachary Turner5c725f32016-09-19 21:56:59 +0000929 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000930 return false;
931
932 // Check each arg to see if it matches the env var name.
Zachary Turner11eb9c62016-10-05 20:03:37 +0000933 for (auto arg : llvm::enumerate(m_entries)) {
Zachary Turner5c725f32016-09-19 21:56:59 +0000934 llvm::StringRef name, value;
Zachary Turner11eb9c62016-10-05 20:03:37 +0000935 std::tie(name, value) = arg.Value.ref.split('=');
936 if (name != env_var_name)
937 continue;
938
939 if (argument_index)
940 *argument_index = arg.Index;
941 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 }
943
944 // We didn't find a match.
945 return false;
946}
947
948size_t Args::FindArgumentIndexForOption(Option *long_options,
Zachary Turner11eb9c62016-10-05 20:03:37 +0000949 int long_options_index) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 char short_buffer[3];
951 char long_buffer[255];
952 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
953 long_options[long_options_index].val);
954 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
955 long_options[long_options_index].definition->long_option);
Zachary Turner11eb9c62016-10-05 20:03:37 +0000956
957 for (auto entry : llvm::enumerate(m_entries)) {
958 if (entry.Value.ref.startswith(short_buffer) ||
959 entry.Value.ref.startswith(long_buffer))
960 return entry.Index;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 }
962
Zachary Turner11eb9c62016-10-05 20:03:37 +0000963 return size_t(-1);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964}
965
966bool Args::IsPositionalArgument(const char *arg) {
967 if (arg == nullptr)
968 return false;
969
970 bool is_positional = true;
971 const char *cptr = arg;
972
973 if (cptr[0] == '%') {
974 ++cptr;
975 while (isdigit(cptr[0]))
976 ++cptr;
977 if (cptr[0] != '\0')
978 is_positional = false;
979 } else
980 is_positional = false;
981
982 return is_positional;
983}
984
Zachary Turnera4496982016-10-05 21:14:38 +0000985std::string Args::ParseAliasOptions(Options &options,
986 CommandReturnObject &result,
987 OptionArgVector *option_arg_vector,
988 llvm::StringRef raw_input_string) {
989 std::string result_string(raw_input_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 StreamString sstr;
991 int i;
992 Option *long_options = options.GetLongOptions();
993
994 if (long_options == nullptr) {
995 result.AppendError("invalid long options");
996 result.SetStatus(eReturnStatusFailed);
Zachary Turnera4496982016-10-05 21:14:38 +0000997 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 }
999
1000 for (i = 0; long_options[i].definition != nullptr; ++i) {
1001 if (long_options[i].flag == nullptr) {
1002 sstr << (char)long_options[i].val;
1003 switch (long_options[i].definition->option_has_arg) {
1004 default:
1005 case OptionParser::eNoArgument:
1006 break;
1007 case OptionParser::eRequiredArgument:
1008 sstr << ":";
1009 break;
1010 case OptionParser::eOptionalArgument:
1011 sstr << "::";
1012 break;
1013 }
1014 }
1015 }
1016
1017 std::unique_lock<std::mutex> lock;
1018 OptionParser::Prepare(lock);
Zachary Turner5c28c662016-10-03 23:20:36 +00001019 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 int val;
1021 while (1) {
1022 int long_options_index = -1;
Zachary Turnerc1564272016-11-16 21:15:24 +00001023 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1024 sstr.GetString(), long_options,
1025 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026
1027 if (val == -1)
1028 break;
1029
1030 if (val == '?') {
1031 result.AppendError("unknown or ambiguous option");
1032 result.SetStatus(eReturnStatusFailed);
1033 break;
1034 }
1035
1036 if (val == 0)
1037 continue;
1038
1039 options.OptionSeen(val);
1040
1041 // Look up the long option index
1042 if (long_options_index == -1) {
1043 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1044 long_options[j].val;
1045 ++j) {
1046 if (long_options[j].val == val) {
1047 long_options_index = j;
1048 break;
1049 }
1050 }
1051 }
1052
1053 // See if the option takes an argument, and see if one was supplied.
Zachary Turner5c28c662016-10-03 23:20:36 +00001054 if (long_options_index == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1056 result.SetStatus(eReturnStatusFailed);
Zachary Turnera4496982016-10-05 21:14:38 +00001057 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 }
1059
Zachary Turner5c28c662016-10-03 23:20:36 +00001060 StreamString option_str;
1061 option_str.Printf("-%c", val);
1062 const OptionDefinition *def = long_options[long_options_index].definition;
1063 int has_arg =
1064 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1065
1066 const char *option_arg = nullptr;
1067 switch (has_arg) {
1068 case OptionParser::eRequiredArgument:
1069 if (OptionParser::GetOptionArgument() == nullptr) {
1070 result.AppendErrorWithFormat(
1071 "Option '%s' is missing argument specifier.\n",
1072 option_str.GetData());
1073 result.SetStatus(eReturnStatusFailed);
Zachary Turnera4496982016-10-05 21:14:38 +00001074 return result_string;
Zachary Turner5c28c662016-10-03 23:20:36 +00001075 }
1076 LLVM_FALLTHROUGH;
1077 case OptionParser::eOptionalArgument:
1078 option_arg = OptionParser::GetOptionArgument();
1079 LLVM_FALLTHROUGH;
1080 case OptionParser::eNoArgument:
1081 break;
1082 default:
1083 result.AppendErrorWithFormat("error with options table; invalid value "
1084 "in has_arg field for option '%c'.\n",
1085 val);
1086 result.SetStatus(eReturnStatusFailed);
Zachary Turnera4496982016-10-05 21:14:38 +00001087 return result_string;
Zachary Turner5c28c662016-10-03 23:20:36 +00001088 }
1089 if (!option_arg)
1090 option_arg = "<no-argument>";
Zachary Turnerc1564272016-11-16 21:15:24 +00001091 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1092 option_arg);
Zachary Turner5c28c662016-10-03 23:20:36 +00001093
1094 // Find option in the argument list; also see if it was supposed to take
1095 // an argument and if one was supplied. Remove option (and argument, if
1096 // given) from the argument list. Also remove them from the
1097 // raw_input_string, if one was passed in.
1098 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
Zachary Turner11eb9c62016-10-05 20:03:37 +00001099 if (idx == size_t(-1))
1100 continue;
1101
Zachary Turnera4496982016-10-05 21:14:38 +00001102 if (!result_string.empty()) {
Zachary Turner2c84f902016-12-09 05:46:41 +00001103 auto tmp_arg = m_entries[idx].ref;
Zachary Turnera4496982016-10-05 21:14:38 +00001104 size_t pos = result_string.find(tmp_arg);
Zachary Turner11eb9c62016-10-05 20:03:37 +00001105 if (pos != std::string::npos)
Zachary Turner2c84f902016-12-09 05:46:41 +00001106 result_string.erase(pos, tmp_arg.size());
Zachary Turner11eb9c62016-10-05 20:03:37 +00001107 }
1108 ReplaceArgumentAtIndex(idx, llvm::StringRef());
1109 if ((long_options[long_options_index].definition->option_has_arg !=
1110 OptionParser::eNoArgument) &&
1111 (OptionParser::GetOptionArgument() != nullptr) &&
1112 (idx + 1 < GetArgumentCount()) &&
Zachary Turner2c84f902016-12-09 05:46:41 +00001113 (m_entries[idx + 1].ref == OptionParser::GetOptionArgument())) {
Zachary Turnera4496982016-10-05 21:14:38 +00001114 if (result_string.size() > 0) {
Zachary Turner2c84f902016-12-09 05:46:41 +00001115 auto tmp_arg = m_entries[idx + 1].ref;
Zachary Turnera4496982016-10-05 21:14:38 +00001116 size_t pos = result_string.find(tmp_arg);
Zachary Turner5c28c662016-10-03 23:20:36 +00001117 if (pos != std::string::npos)
Zachary Turner2c84f902016-12-09 05:46:41 +00001118 result_string.erase(pos, tmp_arg.size());
Zachary Turner5c28c662016-10-03 23:20:36 +00001119 }
Zachary Turner11eb9c62016-10-05 20:03:37 +00001120 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 }
Zachary Turnera4496982016-10-05 21:14:38 +00001123 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124}
1125
1126void Args::ParseArgsForCompletion(Options &options,
1127 OptionElementVector &option_element_vector,
1128 uint32_t cursor_index) {
1129 StreamString sstr;
1130 Option *long_options = options.GetLongOptions();
1131 option_element_vector.clear();
1132
1133 if (long_options == nullptr) {
1134 return;
1135 }
1136
1137 // Leading : tells getopt to return a : for a missing option argument AND
1138 // to suppress error messages.
1139
1140 sstr << ":";
1141 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1142 if (long_options[i].flag == nullptr) {
1143 sstr << (char)long_options[i].val;
1144 switch (long_options[i].definition->option_has_arg) {
1145 default:
1146 case OptionParser::eNoArgument:
1147 break;
1148 case OptionParser::eRequiredArgument:
1149 sstr << ":";
1150 break;
1151 case OptionParser::eOptionalArgument:
1152 sstr << "::";
1153 break;
1154 }
1155 }
1156 }
1157
1158 std::unique_lock<std::mutex> lock;
1159 OptionParser::Prepare(lock);
1160 OptionParser::EnableError(false);
1161
1162 int val;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001163 auto opt_defs = options.GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164
1165 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
Zachary Turner11eb9c62016-10-05 20:03:37 +00001166 // options to the front. So we have to build another Arg and pass that to
1167 // OptionParser::Parse so it doesn't change the one we have.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168
Zachary Turner11eb9c62016-10-05 20:03:37 +00001169 std::vector<char *> dummy_vec = m_argv;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170
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
Zachary Turnere706c1d2016-11-13 04:24:38 +00001178 val = OptionParser::Parse(dummy_vec.size() - 1, &dummy_vec[0],
1179 sstr.GetString(), long_options,
1180 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181
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}