blob: 07e5191f898aac1b347741a5c8305e8f49e69f8c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:241//===-- 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:2311#include <cstdlib>
Chris Lattner30fdc8d2010-06-08 16:52:2412// C++ Includes
13// Other libraries and framework includes
14// Project includes
Enrico Granata5548cb52013-01-28 23:47:2515#include "lldb/DataFormatters/FormatManager.h"
Zachary Turner3eb2b442017-03-22 23:33:1616#include "lldb/Host/OptionParser.h"
Kate Stoneb9c1b512016-09-06 20:57:5017#include "lldb/Interpreter/Args.h"
Zachary Turnerd37221d2014-07-09 16:31:4918#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:2419#include "lldb/Interpreter/CommandReturnObject.h"
Kate Stoneb9c1b512016-09-06 20:57:5020#include "lldb/Interpreter/Options.h"
Greg Claytonb9d5df52012-12-06 22:49:1621#include "lldb/Target/Target.h"
Zachary Turnerbf9a7732017-02-02 21:39:5022#include "lldb/Utility/Stream.h"
23#include "lldb/Utility/StreamString.h"
Chris Lattner30fdc8d2010-06-08 16:52:2424
Zachary Turner11eb9c62016-10-05 20:03:3725#include "llvm/ADT/STLExtras.h"
Zachary Turner691405b2016-10-03 22:51:0926#include "llvm/ADT/StringExtras.h"
Zachary Turner54695a32016-08-29 19:58:1427#include "llvm/ADT/StringSwitch.h"
28
Chris Lattner30fdc8d2010-06-08 16:52:2429using namespace lldb;
30using namespace lldb_private;
31
Caroline Tice2d5289d62010-12-10 00:26:5432
Pavel Labath00b7f952015-03-02 12:46:2233// A helper function for argument parsing.
Kate Stoneb9c1b512016-09-06 20:57:5034// Parses the initial part of the first argument using normal double quote
35// rules:
36// backslash escapes the double quote and itself. The parsed string is appended
37// to the second
38// argument. The function returns the unparsed portion of the string, starting
39// at the closing
Pavel Labath00b7f952015-03-02 12:46:2240// quote.
Kate Stoneb9c1b512016-09-06 20:57:5041static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
42 std::string &result) {
43 // Inside double quotes, '\' and '"' are special.
44 static const char *k_escapable_characters = "\"\\";
45 while (true) {
46 // Skip over over regular characters and append them.
47 size_t regular = quoted.find_first_of(k_escapable_characters);
48 result += quoted.substr(0, regular);
49 quoted = quoted.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:2250
Kate Stoneb9c1b512016-09-06 20:57:5051 // If we have reached the end of string or the closing quote, we're done.
52 if (quoted.empty() || quoted.front() == '"')
53 break;
Pavel Labath00b7f952015-03-02 12:46:2254
Kate Stoneb9c1b512016-09-06 20:57:5055 // We have found a backslash.
56 quoted = quoted.drop_front();
Pavel Labath00b7f952015-03-02 12:46:2257
Kate Stoneb9c1b512016-09-06 20:57:5058 if (quoted.empty()) {
59 // A lone backslash at the end of string, let's just append it.
60 result += '\\';
61 break;
Pavel Labath00b7f952015-03-02 12:46:2262 }
63
Kate Stoneb9c1b512016-09-06 20:57:5064 // If the character after the backslash is not a whitelisted escapable
65 // character, we
66 // leave the character sequence untouched.
67 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
68 result += '\\';
69
70 result += quoted.front();
71 quoted = quoted.drop_front();
72 }
73
74 return quoted;
Pavel Labath00b7f952015-03-02 12:46:2275}
76
Zachary Turner691405b2016-10-03 22:51:0977static size_t ArgvToArgc(const char **argv) {
78 if (!argv)
79 return 0;
80 size_t count = 0;
81 while (*argv++)
82 ++count;
83 return count;
84}
Pavel Labath00b7f952015-03-02 12:46:2285
Zachary Turner691405b2016-10-03 22:51:0986// A helper function for SetCommandString. Parses a single argument from the
87// command string, processing quotes and backslashes in a shell-like manner.
88// The function returns a tuple consisting of the parsed argument, the quote
89// char used, and the unparsed portion of the string starting at the first
90// unqouted, unescaped whitespace character.
91static std::tuple<std::string, char, llvm::StringRef>
92ParseSingleArgument(llvm::StringRef command) {
93 // Argument can be split into multiple discontiguous pieces, for example:
94 // "Hello ""World"
95 // this would result in a single argument "Hello World" (without the quotes)
96 // since the quotes would be removed and there is not space between the
97 // strings.
Kate Stoneb9c1b512016-09-06 20:57:5098 std::string arg;
Pavel Labath00b7f952015-03-02 12:46:2299
Kate Stoneb9c1b512016-09-06 20:57:50100 // Since we can have multiple quotes that form a single command
101 // in a command like: "Hello "world'!' (which will make a single
102 // argument "Hello world!") we remember the first quote character
103 // we encounter and use that for the quote character.
104 char first_quote_char = '\0';
Pavel Labath00b7f952015-03-02 12:46:22105
Kate Stoneb9c1b512016-09-06 20:57:50106 bool arg_complete = false;
107 do {
108 // Skip over over regular characters and append them.
109 size_t regular = command.find_first_of(" \t\"'`\\");
110 arg += command.substr(0, regular);
111 command = command.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22112
Kate Stoneb9c1b512016-09-06 20:57:50113 if (command.empty())
114 break;
Pavel Labath00b7f952015-03-02 12:46:22115
Kate Stoneb9c1b512016-09-06 20:57:50116 char special = command.front();
117 command = command.drop_front();
118 switch (special) {
119 case '\\':
120 if (command.empty()) {
121 arg += '\\';
122 break;
123 }
124
125 // If the character after the backslash is not a whitelisted escapable
126 // character, we
127 // leave the character sequence untouched.
128 if (strchr(" \t\\'\"`", command.front()) == nullptr)
129 arg += '\\';
130
131 arg += command.front();
132 command = command.drop_front();
133
134 break;
135
136 case ' ':
137 case '\t':
138 // We are not inside any quotes, we just found a space after an
139 // argument. We are done.
140 arg_complete = true;
141 break;
142
143 case '"':
144 case '\'':
145 case '`':
146 // We found the start of a quote scope.
147 if (first_quote_char == '\0')
148 first_quote_char = special;
149
150 if (special == '"')
151 command = ParseDoubleQuotes(command, arg);
152 else {
153 // For single quotes, we simply skip ahead to the matching quote
154 // character
155 // (or the end of the string).
156 size_t quoted = command.find(special);
157 arg += command.substr(0, quoted);
158 command = command.substr(quoted);
159 }
160
161 // If we found a closing quote, skip it.
162 if (!command.empty())
Pavel Labath00b7f952015-03-02 12:46:22163 command = command.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22164
Kate Stoneb9c1b512016-09-06 20:57:50165 break;
166 }
167 } while (!arg_complete);
Pavel Labath00b7f952015-03-02 12:46:22168
Zachary Turner691405b2016-10-03 22:51:09169 return std::make_tuple(arg, first_quote_char, command);
Chris Lattner30fdc8d2010-06-08 16:52:24170}
171
Zachary Turner691405b2016-10-03 22:51:09172Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
173 size_t size = str.size();
174 ptr.reset(new char[size + 1]);
Greg Clayton6ad07dd2010-12-19 03:41:24175
Zachary Turner691405b2016-10-03 22:51:09176 ::memcpy(data(), str.data() ? str.data() : "", size);
177 ptr[size] = 0;
178 ref = llvm::StringRef(c_str(), size);
179}
180
181//----------------------------------------------------------------------
182// Args constructor
183//----------------------------------------------------------------------
184Args::Args(llvm::StringRef command) { SetCommandString(command); }
185
186Args::Args(const Args &rhs) { *this = rhs; }
187
Pavel Labathc58a80f2017-12-11 14:22:30188Args::Args(const StringList &list) : Args() {
189 for(size_t i = 0; i < list.GetSize(); ++i)
190 AppendArgument(list[i]);
191}
192
Zachary Turner691405b2016-10-03 22:51:09193Args &Args::operator=(const Args &rhs) {
194 Clear();
195
196 m_argv.clear();
197 m_entries.clear();
198 for (auto &entry : rhs.m_entries) {
199 m_entries.emplace_back(entry.ref, entry.quote);
200 m_argv.push_back(m_entries.back().data());
201 }
202 m_argv.push_back(nullptr);
203 return *this;
204}
205
206//----------------------------------------------------------------------
207// Destructor
208//----------------------------------------------------------------------
209Args::~Args() {}
210
211void Args::Dump(Stream &s, const char *label_name) const {
212 if (!label_name)
213 return;
214
215 int i = 0;
216 for (auto &entry : m_entries) {
217 s.Indent();
Luke Drummond63dea592016-12-22 19:15:07218 s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
Zachary Turner691405b2016-10-03 22:51:09219 }
Luke Drummond63dea592016-12-22 19:15:07220 s.Format("{0}[{1}]=NULL\n", label_name, i);
Zachary Turner691405b2016-10-03 22:51:09221 s.EOL();
222}
223
224bool Args::GetCommandString(std::string &command) const {
225 command.clear();
226
227 for (size_t i = 0; i < m_entries.size(); ++i) {
228 if (i > 0)
229 command += ' ';
230 command += m_entries[i].ref;
Kate Stoneb9c1b512016-09-06 20:57:50231 }
232
Zachary Turner691405b2016-10-03 22:51:09233 return !m_entries.empty();
Kate Stoneb9c1b512016-09-06 20:57:50234}
235
Zachary Turner691405b2016-10-03 22:51:09236bool Args::GetQuotedCommandString(std::string &command) const {
237 command.clear();
Kate Stoneb9c1b512016-09-06 20:57:50238
Zachary Turner691405b2016-10-03 22:51:09239 for (size_t i = 0; i < m_entries.size(); ++i) {
240 if (i > 0)
241 command += ' ';
Kate Stoneb9c1b512016-09-06 20:57:50242
Zachary Turner691405b2016-10-03 22:51:09243 if (m_entries[i].quote) {
244 command += m_entries[i].quote;
245 command += m_entries[i].ref;
246 command += m_entries[i].quote;
247 } else {
248 command += m_entries[i].ref;
Chris Lattner30fdc8d2010-06-08 16:52:24249 }
Kate Stoneb9c1b512016-09-06 20:57:50250 }
Pavel Labath00b7f952015-03-02 12:46:22251
Zachary Turner691405b2016-10-03 22:51:09252 return !m_entries.empty();
Chris Lattner30fdc8d2010-06-08 16:52:24253}
254
Zachary Turner691405b2016-10-03 22:51:09255void Args::SetCommandString(llvm::StringRef command) {
256 Clear();
Kate Stoneb9c1b512016-09-06 20:57:50257 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09258
259 static const char *k_space_separators = " \t";
260 command = command.ltrim(k_space_separators);
261 std::string arg;
262 char quote;
263 while (!command.empty()) {
264 std::tie(arg, quote, command) = ParseSingleArgument(command);
265 m_entries.emplace_back(arg, quote);
266 m_argv.push_back(m_entries.back().data());
267 command = command.ltrim(k_space_separators);
268 }
Kate Stoneb9c1b512016-09-06 20:57:50269 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24270}
271
Zachary Turner691405b2016-10-03 22:51:09272void Args::UpdateArgsAfterOptionParsing() {
273 assert(!m_argv.empty());
274 assert(m_argv.back() == nullptr);
275
276 // Now m_argv might be out of date with m_entries, so we need to fix that.
277 // This happens because getopt_long_only may permute the order of the
278 // arguments in argv, so we need to re-order the quotes and the refs array
279 // to match.
Zachary Turner5a8ad4592016-10-05 17:07:34280 for (size_t i = 0; i < m_argv.size() - 1; ++i) {
Zachary Turner691405b2016-10-03 22:51:09281 const char *argv = m_argv[i];
282 auto pos =
283 std::find_if(m_entries.begin() + i, m_entries.end(),
284 [argv](const ArgEntry &D) { return D.c_str() == argv; });
285 assert(pos != m_entries.end());
286 size_t distance = std::distance(m_entries.begin(), pos);
287 if (i == distance)
288 continue;
289
290 assert(distance > i);
291
292 std::swap(m_entries[i], m_entries[distance]);
293 assert(m_entries[i].ref.data() == m_argv[i]);
294 }
295 m_entries.resize(m_argv.size() - 1);
Chris Lattner30fdc8d2010-06-08 16:52:24296}
297
Zachary Turner691405b2016-10-03 22:51:09298size_t Args::GetArgumentCount() const { return m_entries.size(); }
299
Kate Stoneb9c1b512016-09-06 20:57:50300const char *Args::GetArgumentAtIndex(size_t idx) const {
301 if (idx < m_argv.size())
302 return m_argv[idx];
303 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24304}
305
Kate Stoneb9c1b512016-09-06 20:57:50306char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
Zachary Turner691405b2016-10-03 22:51:09307 if (idx < m_entries.size())
308 return m_entries[idx].quote;
Kate Stoneb9c1b512016-09-06 20:57:50309 return '\0';
Chris Lattner30fdc8d2010-06-08 16:52:24310}
311
Kate Stoneb9c1b512016-09-06 20:57:50312char **Args::GetArgumentVector() {
Zachary Turner691405b2016-10-03 22:51:09313 assert(!m_argv.empty());
314 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
315 // when argv or envp is null. So the code below is actually wrong. However,
316 // other code in LLDB depends on it being null. The code has been acting this
317 // way for some time, so it makes sense to leave it this way until someone
318 // has the time to come along and fix it.
319 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24320}
321
Kate Stoneb9c1b512016-09-06 20:57:50322const char **Args::GetConstArgumentVector() const {
Zachary Turner691405b2016-10-03 22:51:09323 assert(!m_argv.empty());
324 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
325 : nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24326}
327
Kate Stoneb9c1b512016-09-06 20:57:50328void Args::Shift() {
329 // Don't pop the last NULL terminator from the argv array
Zachary Turner691405b2016-10-03 22:51:09330 if (m_entries.empty())
331 return;
332 m_argv.erase(m_argv.begin());
333 m_entries.erase(m_entries.begin());
Chris Lattner30fdc8d2010-06-08 16:52:24334}
335
Justin Bogner812101d2016-10-17 06:17:56336void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
337 InsertArgumentAtIndex(0, arg_str, quote_char);
Chris Lattner30fdc8d2010-06-08 16:52:24338}
339
Kate Stoneb9c1b512016-09-06 20:57:50340void Args::AppendArguments(const Args &rhs) {
Zachary Turner691405b2016-10-03 22:51:09341 assert(m_argv.size() == m_entries.size() + 1);
342 assert(m_argv.back() == nullptr);
343 m_argv.pop_back();
344 for (auto &entry : rhs.m_entries) {
345 m_entries.emplace_back(entry.ref, entry.quote);
346 m_argv.push_back(m_entries.back().data());
347 }
348 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24349}
350
Kate Stoneb9c1b512016-09-06 20:57:50351void Args::AppendArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09352 size_t argc = ArgvToArgc(argv);
353
354 assert(m_argv.size() == m_entries.size() + 1);
355 assert(m_argv.back() == nullptr);
356 m_argv.pop_back();
Zachary Turner5a8ad4592016-10-05 17:07:34357 for (auto arg : llvm::makeArrayRef(argv, argc)) {
358 m_entries.emplace_back(arg, '\0');
Zachary Turner691405b2016-10-03 22:51:09359 m_argv.push_back(m_entries.back().data());
Kate Stoneb9c1b512016-09-06 20:57:50360 }
Zachary Turner691405b2016-10-03 22:51:09361
362 m_argv.push_back(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24363}
364
Justin Bogner812101d2016-10-17 06:17:56365void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
366 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
Greg Clayton982c9762011-11-03 21:22:33367}
368
Justin Bogner812101d2016-10-17 06:17:56369void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
370 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09371 assert(m_argv.size() == m_entries.size() + 1);
372 assert(m_argv.back() == nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50373
Zachary Turner691405b2016-10-03 22:51:09374 if (idx > m_entries.size())
Justin Bogner812101d2016-10-17 06:17:56375 return;
Zachary Turner691405b2016-10-03 22:51:09376 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
377 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
Chris Lattner30fdc8d2010-06-08 16:52:24378}
379
Justin Bogner812101d2016-10-17 06:17:56380void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
381 char quote_char) {
Zachary Turner691405b2016-10-03 22:51:09382 assert(m_argv.size() == m_entries.size() + 1);
383 assert(m_argv.back() == nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24384
Zachary Turner691405b2016-10-03 22:51:09385 if (idx >= m_entries.size())
Justin Bogner812101d2016-10-17 06:17:56386 return;
Zachary Turner691405b2016-10-03 22:51:09387
388 if (arg_str.size() > m_entries[idx].ref.size()) {
389 m_entries[idx] = ArgEntry(arg_str, quote_char);
390 m_argv[idx] = m_entries[idx].data();
391 } else {
392 const char *src_data = arg_str.data() ? arg_str.data() : "";
393 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
394 m_entries[idx].ptr[arg_str.size()] = 0;
395 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
Kate Stoneb9c1b512016-09-06 20:57:50396 }
Chris Lattner30fdc8d2010-06-08 16:52:24397}
398
Kate Stoneb9c1b512016-09-06 20:57:50399void Args::DeleteArgumentAtIndex(size_t idx) {
Zachary Turner691405b2016-10-03 22:51:09400 if (idx >= m_entries.size())
401 return;
Chris Lattner30fdc8d2010-06-08 16:52:24402
Zachary Turner691405b2016-10-03 22:51:09403 m_argv.erase(m_argv.begin() + idx);
404 m_entries.erase(m_entries.begin() + idx);
Chris Lattner30fdc8d2010-06-08 16:52:24405}
406
Kate Stoneb9c1b512016-09-06 20:57:50407void Args::SetArguments(size_t argc, const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09408 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24409
Zachary Turner691405b2016-10-03 22:51:09410 auto args = llvm::makeArrayRef(argv, argc);
411 m_entries.resize(argc);
412 m_argv.resize(argc + 1);
Zachary Turner5a8ad4592016-10-05 17:07:34413 for (size_t i = 0; i < args.size(); ++i) {
Zachary Turner691405b2016-10-03 22:51:09414 char quote =
415 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
416 ? args[i][0]
417 : '\0';
418
419 m_entries[i] = ArgEntry(args[i], quote);
420 m_argv[i] = m_entries[i].data();
Kate Stoneb9c1b512016-09-06 20:57:50421 }
Chris Lattner30fdc8d2010-06-08 16:52:24422}
423
Kate Stoneb9c1b512016-09-06 20:57:50424void Args::SetArguments(const char **argv) {
Zachary Turner691405b2016-10-03 22:51:09425 SetArguments(ArgvToArgc(argv), argv);
Chris Lattner30fdc8d2010-06-08 16:52:24426}
427
Zachary Turner97206d52017-05-12 04:51:55428Status Args::ParseOptions(Options &options, ExecutionContext *execution_context,
429 PlatformSP platform_sp, bool require_validation) {
Kate Stoneb9c1b512016-09-06 20:57:50430 StreamString sstr;
Zachary Turner97206d52017-05-12 04:51:55431 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50432 Option *long_options = options.GetLongOptions();
433 if (long_options == nullptr) {
434 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24435 return error;
Kate Stoneb9c1b512016-09-06 20:57:50436 }
Chris Lattner30fdc8d2010-06-08 16:52:24437
Kate Stoneb9c1b512016-09-06 20:57:50438 for (int i = 0; long_options[i].definition != nullptr; ++i) {
439 if (long_options[i].flag == nullptr) {
440 if (isprint8(long_options[i].val)) {
441 sstr << (char)long_options[i].val;
442 switch (long_options[i].definition->option_has_arg) {
Tamas Berghammer89d3f092015-09-02 10:35:27443 default:
Kate Stoneb9c1b512016-09-06 20:57:50444 case OptionParser::eNoArgument:
445 break;
446 case OptionParser::eRequiredArgument:
447 sstr << ':';
448 break;
449 case OptionParser::eOptionalArgument:
450 sstr << "::";
451 break;
452 }
453 }
Tamas Berghammer89d3f092015-09-02 10:35:27454 }
Kate Stoneb9c1b512016-09-06 20:57:50455 }
456 std::unique_lock<std::mutex> lock;
457 OptionParser::Prepare(lock);
458 int val;
459 while (1) {
460 int long_options_index = -1;
Zachary Turnere706c1d2016-11-13 04:24:38461 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
462 sstr.GetString(), long_options,
463 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:50464 if (val == -1)
465 break;
Tamas Berghammer89d3f092015-09-02 10:35:27466
Kate Stoneb9c1b512016-09-06 20:57:50467 // Did we get an error?
468 if (val == '?') {
469 error.SetErrorStringWithFormat("unknown or ambiguous option");
470 break;
Tamas Berghammer89d3f092015-09-02 10:35:27471 }
Kate Stoneb9c1b512016-09-06 20:57:50472 // The option auto-set itself
473 if (val == 0)
474 continue;
475
476 ((Options *)&options)->OptionSeen(val);
477
478 // Lookup the long option index
479 if (long_options_index == -1) {
480 for (int i = 0; long_options[i].definition || long_options[i].flag ||
481 long_options[i].val;
482 ++i) {
483 if (long_options[i].val == val) {
484 long_options_index = i;
485 break;
486 }
487 }
488 }
489 // Call the callback with the option
490 if (long_options_index >= 0 &&
491 long_options[long_options_index].definition) {
492 const OptionDefinition *def = long_options[long_options_index].definition;
493
494 if (!platform_sp) {
495 // User did not pass in an explicit platform. Try to grab
496 // from the execution context.
497 TargetSP target_sp =
498 execution_context ? execution_context->GetTargetSP() : TargetSP();
499 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
500 }
501 OptionValidator *validator = def->validator;
502
503 if (!platform_sp && require_validation) {
504 // Caller requires validation but we cannot validate as we
505 // don't have the mandatory platform against which to
506 // validate.
507 error.SetErrorString("cannot validate options: "
508 "no platform available");
509 return error;
510 }
511
512 bool validation_failed = false;
513 if (platform_sp) {
514 // Ensure we have an execution context, empty or not.
515 ExecutionContext dummy_context;
516 ExecutionContext *exe_ctx_p =
517 execution_context ? execution_context : &dummy_context;
518 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
519 validation_failed = true;
520 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
521 def->long_option,
522 def->validator->LongConditionString());
523 }
524 }
525
526 // As long as validation didn't fail, we set the option value.
527 if (!validation_failed)
528 error = options.SetOptionValue(
529 long_options_index,
530 (def->option_has_arg == OptionParser::eNoArgument)
531 ? nullptr
532 : OptionParser::GetOptionArgument(),
533 execution_context);
534 } else {
535 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
536 }
537 if (error.Fail())
538 break;
539 }
540
541 // Update our ARGV now that get options has consumed all the options
542 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
543 UpdateArgsAfterOptionParsing();
544 return error;
Tamas Berghammer89d3f092015-09-02 10:35:27545}
546
Kate Stoneb9c1b512016-09-06 20:57:50547void Args::Clear() {
Zachary Turner691405b2016-10-03 22:51:09548 m_entries.clear();
Kate Stoneb9c1b512016-09-06 20:57:50549 m_argv.clear();
Zachary Turner691405b2016-10-03 22:51:09550 m_argv.push_back(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50551}
552
553lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
Zachary Turnerc5d7df92016-11-08 04:52:16554 llvm::StringRef s, lldb::addr_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55555 Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50556 bool error_set = false;
Zachary Turnerc5d7df92016-11-08 04:52:16557 if (s.empty()) {
558 if (error_ptr)
559 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
560 s.str().c_str());
561 return fail_value;
562 }
Zachary Turner95eae422016-09-21 16:01:28563
Zachary Turnerc5d7df92016-11-08 04:52:16564 llvm::StringRef sref = s;
565
566 lldb::addr_t addr = LLDB_INVALID_ADDRESS;
567 if (!s.getAsInteger(0, addr)) {
568 if (error_ptr)
569 error_ptr->Clear();
570 return addr;
571 }
572
573 // Try base 16 with no prefix...
574 if (!s.getAsInteger(16, addr)) {
575 if (error_ptr)
576 error_ptr->Clear();
577 return addr;
578 }
579
580 Target *target = nullptr;
581 if (!exe_ctx || !(target = exe_ctx->GetTargetPtr())) {
582 if (error_ptr)
583 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
584 s.str().c_str());
585 return fail_value;
586 }
587
588 lldb::ValueObjectSP valobj_sp;
589 EvaluateExpressionOptions options;
590 options.SetCoerceToId(false);
591 options.SetUnwindOnError(true);
592 options.SetKeepInMemory(false);
593 options.SetTryAllThreads(true);
594
595 ExpressionResults expr_result =
596 target->EvaluateExpression(s, exe_ctx->GetFramePtr(), valobj_sp, options);
597
598 bool success = false;
599 if (expr_result == eExpressionCompleted) {
600 if (valobj_sp)
601 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
602 valobj_sp->GetDynamicValueType(), true);
603 // Get the address to watch.
604 if (valobj_sp)
605 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
606 if (success) {
Kate Stoneb9c1b512016-09-06 20:57:50607 if (error_ptr)
608 error_ptr->Clear();
Zachary Turnerc5d7df92016-11-08 04:52:16609 return addr;
610 } else {
611 if (error_ptr) {
612 error_set = true;
613 error_ptr->SetErrorStringWithFormat(
614 "address expression \"%s\" resulted in a value whose type "
615 "can't be converted to an address: %s",
Zachary Turnercb3c9f62016-11-08 22:23:50616 s.str().c_str(), valobj_sp->GetTypeName().GetCString());
Zachary Turnerc5d7df92016-11-08 04:52:16617 }
Kate Stoneb9c1b512016-09-06 20:57:50618 }
619
Zachary Turnerc5d7df92016-11-08 04:52:16620 } else {
621 // Since the compiler can't handle things like "main + 12" we should
622 // try to do this for now. The compiler doesn't like adding offsets
623 // to function pointer types.
624 static RegularExpression g_symbol_plus_offset_regex(
625 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
626 RegularExpression::Match regex_match(3);
627 if (g_symbol_plus_offset_regex.Execute(sref, &regex_match)) {
628 uint64_t offset = 0;
629 bool add = true;
630 std::string name;
631 std::string str;
632 if (regex_match.GetMatchAtIndex(s, 1, name)) {
633 if (regex_match.GetMatchAtIndex(s, 2, str)) {
634 add = str[0] == '+';
Kate Stoneb9c1b512016-09-06 20:57:50635
Zachary Turnerc5d7df92016-11-08 04:52:16636 if (regex_match.GetMatchAtIndex(s, 3, str)) {
Zachary Turner3eb2b442017-03-22 23:33:16637 if (!llvm::StringRef(str).getAsInteger(0, offset)) {
Zachary Turner97206d52017-05-12 04:51:55638 Status error;
Zachary Turnerc5d7df92016-11-08 04:52:16639 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:50646 }
647 }
648 }
Kate Stoneb9c1b512016-09-06 20:57:50649 }
650 }
651 }
Zachary Turnerc5d7df92016-11-08 04:52:16652
653 if (error_ptr) {
654 error_set = true;
655 error_ptr->SetErrorStringWithFormat(
Zachary Turnercb3c9f62016-11-08 22:23:50656 "address expression \"%s\" evaluation failed", s.str().c_str());
Zachary Turnerc5d7df92016-11-08 04:52:16657 }
Kate Stoneb9c1b512016-09-06 20:57:50658 }
Zachary Turnerc5d7df92016-11-08 04:52:16659
Kate Stoneb9c1b512016-09-06 20:57:50660 if (error_ptr) {
661 if (!error_set)
662 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
Zachary Turnercb3c9f62016-11-08 22:23:50663 s.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50664 }
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:50691bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
692 bool *success_ptr) {
Zachary Turner7b2e5a32016-09-16 19:09:12693 if (success_ptr)
694 *success_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50695 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:50698 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:50701 return true;
702 }
703 if (success_ptr)
704 *success_ptr = false;
705 return fail_value;
706}
707
Zachary Turner7b2e5a32016-09-16 19:09:12708char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50709 if (success_ptr)
Zachary Turner7b2e5a32016-09-16 19:09:12710 *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:50717}
718
Zachary Turner6fa7681b2016-09-17 02:00:02719bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
720 uint32_t &minor, uint32_t &update) {
Kate Stoneb9c1b512016-09-06 20:57:50721 major = UINT32_MAX;
722 minor = UINT32_MAX;
723 update = UINT32_MAX;
724
Zachary Turner6fa7681b2016-09-17 02:00:02725 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:50740}
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:13780int64_t Args::StringToOptionEnum(llvm::StringRef s,
Kate Stoneb9c1b512016-09-06 20:57:50781 OptionEnumValueElement *enum_values,
Zachary Turner97206d52017-05-12 04:51:55782 int32_t fail_value, Status &error) {
Zachary Turner8cef4b02016-09-23 17:48:13783 error.Clear();
784 if (!enum_values) {
Kate Stoneb9c1b512016-09-06 20:57:50785 error.SetErrorString("invalid enumeration argument");
Zachary Turner8cef4b02016-09-23 17:48:13786 return fail_value;
Kate Stoneb9c1b512016-09-06 20:57:50787 }
Zachary Turner8cef4b02016-09-23 17:48:13788
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:24805 error.SetErrorString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50806 return fail_value;
807}
808
Zachary Turner7b2e5a32016-09-16 19:09:12809lldb::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:50822 if (success_ptr)
823 *success_ptr = false;
824 return fail_value;
825}
826
Zachary Turner97206d52017-05-12 04:51:55827Status Args::StringToFormat(const char *s, lldb::Format &format,
828 size_t *byte_size_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50829 format = eFormatInvalid;
Zachary Turner97206d52017-05-12 04:51:55830 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50831
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:24861 error.SetErrorString(error_strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50862 }
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:50872lldb::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:50882uint32_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:59903void Args::AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
904 llvm::StringRef new_value) {
Todd Fiala36bf6a42016-09-22 16:00:01905 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50906 return;
907
908 // Build the new entry.
Zachary Turner5c725f32016-09-19 21:56:59909 std::string var_string(env_var_name);
Todd Fiala36bf6a42016-09-22 16:00:01910 if (!new_value.empty()) {
911 var_string += "=";
912 var_string += new_value;
913 }
Kate Stoneb9c1b512016-09-06 20:57:50914
Zachary Turner5c725f32016-09-19 21:56:59915 size_t index = 0;
916 if (ContainsEnvironmentVariable(env_var_name, &index)) {
917 ReplaceArgumentAtIndex(index, var_string);
918 return;
Kate Stoneb9c1b512016-09-06 20:57:50919 }
920
921 // We didn't find it. Append it instead.
Zachary Turner5c725f32016-09-19 21:56:59922 AppendArgument(var_string);
Kate Stoneb9c1b512016-09-06 20:57:50923}
924
Zachary Turner5c725f32016-09-19 21:56:59925bool Args::ContainsEnvironmentVariable(llvm::StringRef env_var_name,
Kate Stoneb9c1b512016-09-06 20:57:50926 size_t *argument_index) const {
927 // Validate args.
Zachary Turner5c725f32016-09-19 21:56:59928 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50929 return false;
930
931 // Check each arg to see if it matches the env var name.
Zachary Turner11eb9c62016-10-05 20:03:37932 for (auto arg : llvm::enumerate(m_entries)) {
Zachary Turner5c725f32016-09-19 21:56:59933 llvm::StringRef name, value;
Zachary Turner4eb84492017-03-13 17:12:12934 std::tie(name, value) = arg.value().ref.split('=');
Zachary Turner11eb9c62016-10-05 20:03:37935 if (name != env_var_name)
936 continue;
937
938 if (argument_index)
Zachary Turner4eb84492017-03-13 17:12:12939 *argument_index = arg.index();
Zachary Turner11eb9c62016-10-05 20:03:37940 return true;
Kate Stoneb9c1b512016-09-06 20:57:50941 }
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:37948 int long_options_index) const {
Kate Stoneb9c1b512016-09-06 20:57:50949 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:37955
956 for (auto entry : llvm::enumerate(m_entries)) {
Zachary Turner4eb84492017-03-13 17:12:12957 if (entry.value().ref.startswith(short_buffer) ||
958 entry.value().ref.startswith(long_buffer))
959 return entry.index();
Kate Stoneb9c1b512016-09-06 20:57:50960 }
961
Zachary Turner11eb9c62016-10-05 20:03:37962 return size_t(-1);
Kate Stoneb9c1b512016-09-06 20:57:50963}
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:38984std::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:50989 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:38996 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:50997 }
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:361018 result.SetStatus(eReturnStatusSuccessFinishNoResult);
Kate Stoneb9c1b512016-09-06 20:57:501019 int val;
1020 while (1) {
1021 int long_options_index = -1;
Zachary Turnerc1564272016-11-16 21:15:241022 val = OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1023 sstr.GetString(), long_options,
1024 &long_options_index);
Kate Stoneb9c1b512016-09-06 20:57:501025
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:361053 if (long_options_index == -1) {
Kate Stoneb9c1b512016-09-06 20:57:501054 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1055 result.SetStatus(eReturnStatusFailed);
Zachary Turnera4496982016-10-05 21:14:381056 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:501057 }
1058
Zachary Turner5c28c662016-10-03 23:20:361059 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:381073 return result_string;
Zachary Turner5c28c662016-10-03 23:20:361074 }
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:381086 return result_string;
Zachary Turner5c28c662016-10-03 23:20:361087 }
1088 if (!option_arg)
1089 option_arg = "<no-argument>";
Zachary Turnerc1564272016-11-16 21:15:241090 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1091 option_arg);
Zachary Turner5c28c662016-10-03 23:20:361092
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:371098 if (idx == size_t(-1))
1099 continue;
1100
Zachary Turnera4496982016-10-05 21:14:381101 if (!result_string.empty()) {
Zachary Turner2c84f902016-12-09 05:46:411102 auto tmp_arg = m_entries[idx].ref;
Zachary Turnera4496982016-10-05 21:14:381103 size_t pos = result_string.find(tmp_arg);
Zachary Turner11eb9c62016-10-05 20:03:371104 if (pos != std::string::npos)
Zachary Turner2c84f902016-12-09 05:46:411105 result_string.erase(pos, tmp_arg.size());
Zachary Turner11eb9c62016-10-05 20:03:371106 }
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:411112 (m_entries[idx + 1].ref == OptionParser::GetOptionArgument())) {
Zachary Turnera4496982016-10-05 21:14:381113 if (result_string.size() > 0) {
Zachary Turner2c84f902016-12-09 05:46:411114 auto tmp_arg = m_entries[idx + 1].ref;
Zachary Turnera4496982016-10-05 21:14:381115 size_t pos = result_string.find(tmp_arg);
Zachary Turner5c28c662016-10-03 23:20:361116 if (pos != std::string::npos)
Zachary Turner2c84f902016-12-09 05:46:411117 result_string.erase(pos, tmp_arg.size());
Zachary Turner5c28c662016-10-03 23:20:361118 }
Zachary Turner11eb9c62016-10-05 20:03:371119 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:501120 }
Kate Stoneb9c1b512016-09-06 20:57:501121 }
Zachary Turnera4496982016-10-05 21:14:381122 return result_string;
Kate Stoneb9c1b512016-09-06 20:57:501123}
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:551162 auto opt_defs = options.GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:501163
1164 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
Zachary Turner11eb9c62016-10-05 20:03:371165 // 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:501167
Zachary Turner11eb9c62016-10-05 20:03:371168 std::vector<char *> dummy_vec = m_argv;
Kate Stoneb9c1b512016-09-06 20:57:501169
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:381177 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:501180
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:551250 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:501255 }
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:091315 const ArgEntry &cursor = m_entries[cursor_index];
Kate Stoneb9c1b512016-09-06 20:57:501316 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1317 cursor_index < dash_dash_pos) &&
Zachary Turner691405b2016-10-03 22:51:091318 cursor.quote == '\0' && cursor.ref == "-") {
Kate Stoneb9c1b512016-09-06 20:57:501319 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}