blob: 997c0e1012b269d2855815e923d36f5e92094ac4 [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
Chris Lattner30fdc8d2010-06-08 16:52:2410// 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
Chris Lattner30fdc8d2010-06-08 16:52:2415#include "lldb/Core/Stream.h"
16#include "lldb/Core/StreamFile.h"
17#include "lldb/Core/StreamString.h"
Enrico Granata5548cb52013-01-28 23:47:2518#include "lldb/DataFormatters/FormatManager.h"
Vince Harron5275aaa2015-01-15 20:08:3519#include "lldb/Host/StringConvert.h"
Kate Stoneb9c1b512016-09-06 20:57:5020#include "lldb/Interpreter/Args.h"
Zachary Turnerd37221d2014-07-09 16:31:4921#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:2422#include "lldb/Interpreter/CommandReturnObject.h"
Kate Stoneb9c1b512016-09-06 20:57:5023#include "lldb/Interpreter/Options.h"
Greg Claytonb9d5df52012-12-06 22:49:1624#include "lldb/Target/Process.h"
Jason Molendab57e4a1b2013-11-04 09:33:3025#include "lldb/Target/StackFrame.h"
Greg Claytonb9d5df52012-12-06 22:49:1626#include "lldb/Target/Target.h"
Chris Lattner30fdc8d2010-06-08 16:52:2427
Zachary Turner54695a32016-08-29 19:58:1428#include "llvm/ADT/StringSwitch.h"
29
Chris Lattner30fdc8d2010-06-08 16:52:2430using namespace lldb;
31using namespace lldb_private;
32
Chris Lattner30fdc8d2010-06-08 16:52:2433//----------------------------------------------------------------------
34// Args constructor
35//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:5036Args::Args(llvm::StringRef command) : m_args(), m_argv(), m_args_quote_char() {
37 SetCommandString(command);
Chris Lattner30fdc8d2010-06-08 16:52:2438}
39
Chris Lattner30fdc8d2010-06-08 16:52:2440//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:4641// We have to be very careful on the copy constructor of this class
42// to make sure we copy all of the string values, but we can't copy the
Kate Stoneb9c1b512016-09-06 20:57:5043// rhs.m_argv into m_argv since it will point to the "const char *" c
Greg Clayton8b82f082011-04-12 05:54:4644// strings in rhs.m_args. We need to copy the string list and update our
Kate Stoneb9c1b512016-09-06 20:57:5045// own m_argv appropriately.
Greg Clayton8b82f082011-04-12 05:54:4646//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:5047Args::Args(const Args &rhs)
48 : m_args(rhs.m_args), m_argv(), m_args_quote_char(rhs.m_args_quote_char) {
49 UpdateArgvFromArgs();
50}
51
52//----------------------------------------------------------------------
53// We have to be very careful on the copy constructor of this class
54// to make sure we copy all of the string values, but we can't copy the
55// rhs.m_argv into m_argv since it will point to the "const char *" c
56// strings in rhs.m_args. We need to copy the string list and update our
57// own m_argv appropriately.
58//----------------------------------------------------------------------
59const Args &Args::operator=(const Args &rhs) {
60 // Make sure we aren't assigning to self
61 if (this != &rhs) {
62 m_args = rhs.m_args;
63 m_args_quote_char = rhs.m_args_quote_char;
Greg Clayton8b82f082011-04-12 05:54:4664 UpdateArgvFromArgs();
Kate Stoneb9c1b512016-09-06 20:57:5065 }
66 return *this;
Greg Clayton8b82f082011-04-12 05:54:4667}
68
69//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:2470// Destructor
71//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:5072Args::~Args() {}
73
74void Args::Dump(Stream &s, const char *label_name) const {
75 if (!label_name)
76 return;
77
78 const size_t argc = m_argv.size();
79 for (size_t i = 0; i < argc; ++i) {
80 s.Indent();
81 const char *arg_cstr = m_argv[i];
82 if (arg_cstr)
83 s.Printf("%s[%zi]=\"%s\"\n", label_name, i, arg_cstr);
84 else
85 s.Printf("%s[%zi]=NULL\n", label_name, i);
86 }
87 s.EOL();
Chris Lattner30fdc8d2010-06-08 16:52:2488}
89
Kate Stoneb9c1b512016-09-06 20:57:5090bool Args::GetCommandString(std::string &command) const {
91 command.clear();
92 const size_t argc = GetArgumentCount();
93 for (size_t i = 0; i < argc; ++i) {
94 if (i > 0)
95 command += ' ';
96 command += m_argv[i];
97 }
98 return argc > 0;
Chris Lattner30fdc8d2010-06-08 16:52:2499}
100
Kate Stoneb9c1b512016-09-06 20:57:50101bool Args::GetQuotedCommandString(std::string &command) const {
102 command.clear();
103 const size_t argc = GetArgumentCount();
104 for (size_t i = 0; i < argc; ++i) {
105 if (i > 0)
106 command.append(1, ' ');
107 char quote_char = GetArgumentQuoteCharAtIndex(i);
108 if (quote_char) {
109 command.append(1, quote_char);
110 command.append(m_argv[i]);
111 command.append(1, quote_char);
112 } else
113 command.append(m_argv[i]);
114 }
115 return argc > 0;
Caroline Tice2d5289d62010-12-10 00:26:54116}
117
Pavel Labath00b7f952015-03-02 12:46:22118// A helper function for argument parsing.
Kate Stoneb9c1b512016-09-06 20:57:50119// Parses the initial part of the first argument using normal double quote
120// rules:
121// backslash escapes the double quote and itself. The parsed string is appended
122// to the second
123// argument. The function returns the unparsed portion of the string, starting
124// at the closing
Pavel Labath00b7f952015-03-02 12:46:22125// quote.
Kate Stoneb9c1b512016-09-06 20:57:50126static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
127 std::string &result) {
128 // Inside double quotes, '\' and '"' are special.
129 static const char *k_escapable_characters = "\"\\";
130 while (true) {
131 // Skip over over regular characters and append them.
132 size_t regular = quoted.find_first_of(k_escapable_characters);
133 result += quoted.substr(0, regular);
134 quoted = quoted.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22135
Kate Stoneb9c1b512016-09-06 20:57:50136 // If we have reached the end of string or the closing quote, we're done.
137 if (quoted.empty() || quoted.front() == '"')
138 break;
Pavel Labath00b7f952015-03-02 12:46:22139
Kate Stoneb9c1b512016-09-06 20:57:50140 // We have found a backslash.
141 quoted = quoted.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22142
Kate Stoneb9c1b512016-09-06 20:57:50143 if (quoted.empty()) {
144 // A lone backslash at the end of string, let's just append it.
145 result += '\\';
146 break;
Pavel Labath00b7f952015-03-02 12:46:22147 }
148
Kate Stoneb9c1b512016-09-06 20:57:50149 // If the character after the backslash is not a whitelisted escapable
150 // character, we
151 // leave the character sequence untouched.
152 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
153 result += '\\';
154
155 result += quoted.front();
156 quoted = quoted.drop_front();
157 }
158
159 return quoted;
Pavel Labath00b7f952015-03-02 12:46:22160}
161
162// A helper function for SetCommandString.
Kate Stoneb9c1b512016-09-06 20:57:50163// Parses a single argument from the command string, processing quotes and
164// backslashes in a
165// shell-like manner. The parsed argument is appended to the m_args array. The
166// function returns
167// the unparsed portion of the string, starting at the first unqouted, unescaped
168// whitespace
Pavel Labath00b7f952015-03-02 12:46:22169// character.
Kate Stoneb9c1b512016-09-06 20:57:50170llvm::StringRef Args::ParseSingleArgument(llvm::StringRef command) {
171 // Argument can be split into multiple discontiguous pieces,
172 // for example:
173 // "Hello ""World"
174 // this would result in a single argument "Hello World" (without/
175 // the quotes) since the quotes would be removed and there is
176 // not space between the strings.
Pavel Labath00b7f952015-03-02 12:46:22177
Kate Stoneb9c1b512016-09-06 20:57:50178 std::string arg;
Pavel Labath00b7f952015-03-02 12:46:22179
Kate Stoneb9c1b512016-09-06 20:57:50180 // Since we can have multiple quotes that form a single command
181 // in a command like: "Hello "world'!' (which will make a single
182 // argument "Hello world!") we remember the first quote character
183 // we encounter and use that for the quote character.
184 char first_quote_char = '\0';
Pavel Labath00b7f952015-03-02 12:46:22185
Kate Stoneb9c1b512016-09-06 20:57:50186 bool arg_complete = false;
187 do {
188 // Skip over over regular characters and append them.
189 size_t regular = command.find_first_of(" \t\"'`\\");
190 arg += command.substr(0, regular);
191 command = command.substr(regular);
Pavel Labath00b7f952015-03-02 12:46:22192
Kate Stoneb9c1b512016-09-06 20:57:50193 if (command.empty())
194 break;
Pavel Labath00b7f952015-03-02 12:46:22195
Kate Stoneb9c1b512016-09-06 20:57:50196 char special = command.front();
197 command = command.drop_front();
198 switch (special) {
199 case '\\':
200 if (command.empty()) {
201 arg += '\\';
202 break;
203 }
204
205 // If the character after the backslash is not a whitelisted escapable
206 // character, we
207 // leave the character sequence untouched.
208 if (strchr(" \t\\'\"`", command.front()) == nullptr)
209 arg += '\\';
210
211 arg += command.front();
212 command = command.drop_front();
213
214 break;
215
216 case ' ':
217 case '\t':
218 // We are not inside any quotes, we just found a space after an
219 // argument. We are done.
220 arg_complete = true;
221 break;
222
223 case '"':
224 case '\'':
225 case '`':
226 // We found the start of a quote scope.
227 if (first_quote_char == '\0')
228 first_quote_char = special;
229
230 if (special == '"')
231 command = ParseDoubleQuotes(command, arg);
232 else {
233 // For single quotes, we simply skip ahead to the matching quote
234 // character
235 // (or the end of the string).
236 size_t quoted = command.find(special);
237 arg += command.substr(0, quoted);
238 command = command.substr(quoted);
239 }
240
241 // If we found a closing quote, skip it.
242 if (!command.empty())
Pavel Labath00b7f952015-03-02 12:46:22243 command = command.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22244
Kate Stoneb9c1b512016-09-06 20:57:50245 break;
246 }
247 } while (!arg_complete);
Pavel Labath00b7f952015-03-02 12:46:22248
Kate Stoneb9c1b512016-09-06 20:57:50249 m_args.push_back(arg);
250 m_args_quote_char.push_back(first_quote_char);
251 return command;
Chris Lattner30fdc8d2010-06-08 16:52:24252}
253
Kate Stoneb9c1b512016-09-06 20:57:50254void Args::SetCommandString(llvm::StringRef command) {
255 m_args.clear();
256 m_argv.clear();
257 m_args_quote_char.clear();
Greg Clayton6ad07dd2010-12-19 03:41:24258
Kate Stoneb9c1b512016-09-06 20:57:50259 static const char *k_space_separators = " \t";
260 command = command.ltrim(k_space_separators);
261 while (!command.empty()) {
262 command = ParseSingleArgument(command);
Pavel Labath00b7f952015-03-02 12:46:22263 command = command.ltrim(k_space_separators);
Kate Stoneb9c1b512016-09-06 20:57:50264 }
265
266 UpdateArgvFromArgs();
267}
268
269void Args::UpdateArgsAfterOptionParsing() {
270 // Now m_argv might be out of date with m_args, so we need to fix that
271 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
272 arg_sstr_collection::iterator args_pos;
273 arg_quote_char_collection::iterator quotes_pos;
274
275 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(),
276 quotes_pos = m_args_quote_char.begin();
277 argv_pos != argv_end && args_pos != m_args.end(); ++argv_pos) {
278 const char *argv_cstr = *argv_pos;
279 if (argv_cstr == nullptr)
280 break;
281
282 while (args_pos != m_args.end()) {
283 const char *args_cstr = args_pos->c_str();
284 if (args_cstr == argv_cstr) {
285 // We found the argument that matches the C string in the
286 // vector, so we can now look for the next one
287 ++args_pos;
288 ++quotes_pos;
289 break;
290 } else {
291 quotes_pos = m_args_quote_char.erase(quotes_pos);
292 args_pos = m_args.erase(args_pos);
293 }
Chris Lattner30fdc8d2010-06-08 16:52:24294 }
Kate Stoneb9c1b512016-09-06 20:57:50295 }
Pavel Labath00b7f952015-03-02 12:46:22296
Kate Stoneb9c1b512016-09-06 20:57:50297 if (args_pos != m_args.end())
298 m_args.erase(args_pos, m_args.end());
299
300 if (quotes_pos != m_args_quote_char.end())
301 m_args_quote_char.erase(quotes_pos, m_args_quote_char.end());
Chris Lattner30fdc8d2010-06-08 16:52:24302}
303
Kate Stoneb9c1b512016-09-06 20:57:50304void Args::UpdateArgvFromArgs() {
305 m_argv.clear();
306 arg_sstr_collection::const_iterator pos, end = m_args.end();
307 for (pos = m_args.begin(); pos != end; ++pos)
308 m_argv.push_back(pos->c_str());
309 m_argv.push_back(nullptr);
310 // Make sure we have enough arg quote chars in the array
311 if (m_args_quote_char.size() < m_args.size())
312 m_args_quote_char.resize(m_argv.size());
Chris Lattner30fdc8d2010-06-08 16:52:24313}
314
Kate Stoneb9c1b512016-09-06 20:57:50315size_t Args::GetArgumentCount() const {
316 if (m_argv.empty())
317 return 0;
318 return m_argv.size() - 1;
Chris Lattner30fdc8d2010-06-08 16:52:24319}
320
Kate Stoneb9c1b512016-09-06 20:57:50321const char *Args::GetArgumentAtIndex(size_t idx) const {
322 if (idx < m_argv.size())
323 return m_argv[idx];
324 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24325}
326
Kate Stoneb9c1b512016-09-06 20:57:50327char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
328 if (idx < m_args_quote_char.size())
329 return m_args_quote_char[idx];
330 return '\0';
Chris Lattner30fdc8d2010-06-08 16:52:24331}
332
Kate Stoneb9c1b512016-09-06 20:57:50333char **Args::GetArgumentVector() {
334 if (!m_argv.empty())
335 return const_cast<char **>(&m_argv[0]);
336 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24337}
338
Kate Stoneb9c1b512016-09-06 20:57:50339const char **Args::GetConstArgumentVector() const {
340 if (!m_argv.empty())
341 return const_cast<const char **>(&m_argv[0]);
342 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24343}
344
Kate Stoneb9c1b512016-09-06 20:57:50345void Args::Shift() {
346 // Don't pop the last NULL terminator from the argv array
347 if (m_argv.size() > 1) {
348 m_argv.erase(m_argv.begin());
349 m_args.pop_front();
350 if (!m_args_quote_char.empty())
351 m_args_quote_char.erase(m_args_quote_char.begin());
352 }
Chris Lattner30fdc8d2010-06-08 16:52:24353}
354
Kate Stoneb9c1b512016-09-06 20:57:50355const char *Args::Unshift(const char *arg_cstr, char quote_char) {
356 m_args.push_front(arg_cstr);
357 m_argv.insert(m_argv.begin(), m_args.front().c_str());
358 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
359 return GetArgumentAtIndex(0);
Chris Lattner30fdc8d2010-06-08 16:52:24360}
361
Kate Stoneb9c1b512016-09-06 20:57:50362void Args::AppendArguments(const Args &rhs) {
363 const size_t rhs_argc = rhs.GetArgumentCount();
364 for (size_t i = 0; i < rhs_argc; ++i)
365 AppendArgument(rhs.GetArgumentAtIndex(i),
366 rhs.GetArgumentQuoteCharAtIndex(i));
Chris Lattner30fdc8d2010-06-08 16:52:24367}
368
Kate Stoneb9c1b512016-09-06 20:57:50369void Args::AppendArguments(const char **argv) {
370 if (argv) {
371 for (uint32_t i = 0; argv[i]; ++i)
372 AppendArgument(argv[i]);
373 }
Chris Lattner30fdc8d2010-06-08 16:52:24374}
375
Kate Stoneb9c1b512016-09-06 20:57:50376const char *Args::AppendArgument(const char *arg_cstr, char quote_char) {
377 return InsertArgumentAtIndex(GetArgumentCount(), arg_cstr, quote_char);
Greg Clayton982c9762011-11-03 21:22:33378}
379
Kate Stoneb9c1b512016-09-06 20:57:50380const char *Args::InsertArgumentAtIndex(size_t idx, const char *arg_cstr,
381 char quote_char) {
382 // Since we are using a std::list to hold onto the copied C string and
383 // we don't have direct access to the elements, we have to iterate to
384 // find the value.
385 arg_sstr_collection::iterator pos, end = m_args.end();
386 size_t i = idx;
387 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
388 --i;
389
390 pos = m_args.insert(pos, arg_cstr);
391
392 if (idx >= m_args_quote_char.size()) {
393 m_args_quote_char.resize(idx + 1);
394 m_args_quote_char[idx] = quote_char;
395 } else
396 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
397
398 UpdateArgvFromArgs();
399 return GetArgumentAtIndex(idx);
Chris Lattner30fdc8d2010-06-08 16:52:24400}
401
Kate Stoneb9c1b512016-09-06 20:57:50402const char *Args::ReplaceArgumentAtIndex(size_t idx, const char *arg_cstr,
403 char quote_char) {
404 // Since we are using a std::list to hold onto the copied C string and
405 // we don't have direct access to the elements, we have to iterate to
406 // find the value.
407 arg_sstr_collection::iterator pos, end = m_args.end();
408 size_t i = idx;
409 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
410 --i;
Chris Lattner30fdc8d2010-06-08 16:52:24411
Kate Stoneb9c1b512016-09-06 20:57:50412 if (pos != end) {
413 pos->assign(arg_cstr);
414 assert(idx < m_argv.size() - 1);
415 m_argv[idx] = pos->c_str();
Greg Clayton6ad07dd2010-12-19 03:41:24416 if (idx >= m_args_quote_char.size())
Kate Stoneb9c1b512016-09-06 20:57:50417 m_args_quote_char.resize(idx + 1);
418 m_args_quote_char[idx] = quote_char;
Chris Lattner30fdc8d2010-06-08 16:52:24419 return GetArgumentAtIndex(idx);
Kate Stoneb9c1b512016-09-06 20:57:50420 }
421 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24422}
423
Kate Stoneb9c1b512016-09-06 20:57:50424void Args::DeleteArgumentAtIndex(size_t idx) {
425 // Since we are using a std::list to hold onto the copied C string and
426 // we don't have direct access to the elements, we have to iterate to
427 // find the value.
428 arg_sstr_collection::iterator pos, end = m_args.end();
429 size_t i = idx;
430 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
431 --i;
Chris Lattner30fdc8d2010-06-08 16:52:24432
Kate Stoneb9c1b512016-09-06 20:57:50433 if (pos != end) {
434 m_args.erase(pos);
435 assert(idx < m_argv.size() - 1);
436 m_argv.erase(m_argv.begin() + idx);
437 if (idx < m_args_quote_char.size())
438 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
439 }
Chris Lattner30fdc8d2010-06-08 16:52:24440}
441
Kate Stoneb9c1b512016-09-06 20:57:50442void Args::SetArguments(size_t argc, const char **argv) {
443 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
444 // no need to clear it here.
445 m_args.clear();
446 m_args_quote_char.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24447
Kate Stoneb9c1b512016-09-06 20:57:50448 // First copy each string
449 for (size_t i = 0; i < argc; ++i) {
450 m_args.push_back(argv[i]);
451 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
452 m_args_quote_char.push_back(argv[i][0]);
453 else
454 m_args_quote_char.push_back('\0');
455 }
456
457 UpdateArgvFromArgs();
Chris Lattner30fdc8d2010-06-08 16:52:24458}
459
Kate Stoneb9c1b512016-09-06 20:57:50460void Args::SetArguments(const char **argv) {
461 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
462 // no need to clear it here.
463 m_args.clear();
464 m_args_quote_char.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24465
Kate Stoneb9c1b512016-09-06 20:57:50466 if (argv) {
Chris Lattner30fdc8d2010-06-08 16:52:24467 // First copy each string
Kate Stoneb9c1b512016-09-06 20:57:50468 for (size_t i = 0; argv[i]; ++i) {
469 m_args.push_back(argv[i]);
470 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
471 m_args_quote_char.push_back(argv[i][0]);
472 else
473 m_args_quote_char.push_back('\0');
Chris Lattner30fdc8d2010-06-08 16:52:24474 }
Kate Stoneb9c1b512016-09-06 20:57:50475 }
Chris Lattner30fdc8d2010-06-08 16:52:24476
Kate Stoneb9c1b512016-09-06 20:57:50477 UpdateArgvFromArgs();
Chris Lattner30fdc8d2010-06-08 16:52:24478}
479
Kate Stoneb9c1b512016-09-06 20:57:50480Error Args::ParseOptions(Options &options, ExecutionContext *execution_context,
481 PlatformSP platform_sp, bool require_validation) {
482 StreamString sstr;
483 Error error;
484 Option *long_options = options.GetLongOptions();
485 if (long_options == nullptr) {
486 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24487 return error;
Kate Stoneb9c1b512016-09-06 20:57:50488 }
Chris Lattner30fdc8d2010-06-08 16:52:24489
Kate Stoneb9c1b512016-09-06 20:57:50490 for (int i = 0; long_options[i].definition != nullptr; ++i) {
491 if (long_options[i].flag == nullptr) {
492 if (isprint8(long_options[i].val)) {
493 sstr << (char)long_options[i].val;
494 switch (long_options[i].definition->option_has_arg) {
Tamas Berghammer89d3f092015-09-02 10:35:27495 default:
Kate Stoneb9c1b512016-09-06 20:57:50496 case OptionParser::eNoArgument:
497 break;
498 case OptionParser::eRequiredArgument:
499 sstr << ':';
500 break;
501 case OptionParser::eOptionalArgument:
502 sstr << "::";
503 break;
504 }
505 }
Tamas Berghammer89d3f092015-09-02 10:35:27506 }
Kate Stoneb9c1b512016-09-06 20:57:50507 }
508 std::unique_lock<std::mutex> lock;
509 OptionParser::Prepare(lock);
510 int val;
511 while (1) {
512 int long_options_index = -1;
513 val =
514 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
515 sstr.GetData(), long_options, &long_options_index);
516 if (val == -1)
517 break;
Tamas Berghammer89d3f092015-09-02 10:35:27518
Kate Stoneb9c1b512016-09-06 20:57:50519 // Did we get an error?
520 if (val == '?') {
521 error.SetErrorStringWithFormat("unknown or ambiguous option");
522 break;
Tamas Berghammer89d3f092015-09-02 10:35:27523 }
Kate Stoneb9c1b512016-09-06 20:57:50524 // The option auto-set itself
525 if (val == 0)
526 continue;
527
528 ((Options *)&options)->OptionSeen(val);
529
530 // Lookup the long option index
531 if (long_options_index == -1) {
532 for (int i = 0; long_options[i].definition || long_options[i].flag ||
533 long_options[i].val;
534 ++i) {
535 if (long_options[i].val == val) {
536 long_options_index = i;
537 break;
538 }
539 }
540 }
541 // Call the callback with the option
542 if (long_options_index >= 0 &&
543 long_options[long_options_index].definition) {
544 const OptionDefinition *def = long_options[long_options_index].definition;
545
546 if (!platform_sp) {
547 // User did not pass in an explicit platform. Try to grab
548 // from the execution context.
549 TargetSP target_sp =
550 execution_context ? execution_context->GetTargetSP() : TargetSP();
551 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
552 }
553 OptionValidator *validator = def->validator;
554
555 if (!platform_sp && require_validation) {
556 // Caller requires validation but we cannot validate as we
557 // don't have the mandatory platform against which to
558 // validate.
559 error.SetErrorString("cannot validate options: "
560 "no platform available");
561 return error;
562 }
563
564 bool validation_failed = false;
565 if (platform_sp) {
566 // Ensure we have an execution context, empty or not.
567 ExecutionContext dummy_context;
568 ExecutionContext *exe_ctx_p =
569 execution_context ? execution_context : &dummy_context;
570 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
571 validation_failed = true;
572 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
573 def->long_option,
574 def->validator->LongConditionString());
575 }
576 }
577
578 // As long as validation didn't fail, we set the option value.
579 if (!validation_failed)
580 error = options.SetOptionValue(
581 long_options_index,
582 (def->option_has_arg == OptionParser::eNoArgument)
583 ? nullptr
584 : OptionParser::GetOptionArgument(),
585 execution_context);
586 } else {
587 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
588 }
589 if (error.Fail())
590 break;
591 }
592
593 // Update our ARGV now that get options has consumed all the options
594 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
595 UpdateArgsAfterOptionParsing();
596 return error;
Tamas Berghammer89d3f092015-09-02 10:35:27597}
598
Kate Stoneb9c1b512016-09-06 20:57:50599void Args::Clear() {
600 m_args.clear();
601 m_argv.clear();
602 m_args_quote_char.clear();
603}
604
605lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
606 const char *s, lldb::addr_t fail_value,
607 Error *error_ptr) {
608 bool error_set = false;
609 if (s && s[0]) {
610 char *end = nullptr;
611 lldb::addr_t addr = ::strtoull(s, &end, 0);
612 if (*end == '\0') {
613 if (error_ptr)
614 error_ptr->Clear();
615 return addr; // All characters were used, return the result
616 }
617 // Try base 16 with no prefix...
618 addr = ::strtoull(s, &end, 16);
619 if (*end == '\0') {
620 if (error_ptr)
621 error_ptr->Clear();
622 return addr; // All characters were used, return the result
623 }
624
625 if (exe_ctx) {
626 Target *target = exe_ctx->GetTargetPtr();
627 if (target) {
628 lldb::ValueObjectSP valobj_sp;
629 EvaluateExpressionOptions options;
630 options.SetCoerceToId(false);
631 options.SetUnwindOnError(true);
632 options.SetKeepInMemory(false);
633 options.SetTryAllThreads(true);
634
635 ExpressionResults expr_result = target->EvaluateExpression(
636 s, exe_ctx->GetFramePtr(), valobj_sp, options);
637
638 bool success = false;
639 if (expr_result == eExpressionCompleted) {
640 if (valobj_sp)
641 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
642 valobj_sp->GetDynamicValueType(), true);
643 // Get the address to watch.
644 if (valobj_sp)
645 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
646 if (success) {
647 if (error_ptr)
648 error_ptr->Clear();
649 return addr;
650 } else {
651 if (error_ptr) {
652 error_set = true;
653 error_ptr->SetErrorStringWithFormat(
654 "address expression \"%s\" resulted in a value whose type "
655 "can't be converted to an address: %s",
656 s, valobj_sp->GetTypeName().GetCString());
657 }
658 }
659
660 } else {
661 // Since the compiler can't handle things like "main + 12" we should
662 // try to do this for now. The compiler doesn't like adding offsets
663 // to function pointer types.
664 static RegularExpression g_symbol_plus_offset_regex(
665 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$");
666 RegularExpression::Match regex_match(3);
667 if (g_symbol_plus_offset_regex.Execute(s, &regex_match)) {
668 uint64_t offset = 0;
669 bool add = true;
670 std::string name;
671 std::string str;
672 if (regex_match.GetMatchAtIndex(s, 1, name)) {
673 if (regex_match.GetMatchAtIndex(s, 2, str)) {
674 add = str[0] == '+';
675
676 if (regex_match.GetMatchAtIndex(s, 3, str)) {
677 offset = StringConvert::ToUInt64(str.c_str(), 0, 0, &success);
678
679 if (success) {
680 Error error;
681 addr = StringToAddress(exe_ctx, name.c_str(),
682 LLDB_INVALID_ADDRESS, &error);
683 if (addr != LLDB_INVALID_ADDRESS) {
684 if (add)
685 return addr + offset;
686 else
687 return addr - offset;
688 }
689 }
690 }
691 }
692 }
693 }
694
695 if (error_ptr) {
696 error_set = true;
697 error_ptr->SetErrorStringWithFormat(
698 "address expression \"%s\" evaluation failed", s);
699 }
700 }
701 }
702 }
703 }
704 if (error_ptr) {
705 if (!error_set)
706 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
707 s);
708 }
709 return fail_value;
710}
711
712const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
713 bool return_null_if_empty) {
714 static const char *k_white_space = " \t\v";
715 if (!s.empty()) {
716 if (leading) {
717 size_t pos = s.find_first_not_of(k_white_space);
718 if (pos == std::string::npos)
719 s.clear();
720 else if (pos > 0)
721 s.erase(0, pos);
722 }
723
724 if (trailing) {
725 size_t rpos = s.find_last_not_of(k_white_space);
726 if (rpos != std::string::npos && rpos + 1 < s.size())
727 s.erase(rpos + 1);
728 }
729 }
730 if (return_null_if_empty && s.empty())
731 return nullptr;
732 return s.c_str();
733}
734
735bool Args::StringToBoolean(const char *s, bool fail_value, bool *success_ptr) {
736 if (!s)
737 return fail_value;
738 return Args::StringToBoolean(llvm::StringRef(s), fail_value, success_ptr);
739}
740
741bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
742 bool *success_ptr) {
743 ref = ref.trim();
744 if (ref.equals_lower("false") || ref.equals_lower("off") ||
745 ref.equals_lower("no") || ref.equals_lower("0")) {
746 if (success_ptr)
747 *success_ptr = true;
748 return false;
749 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
750 ref.equals_lower("yes") || ref.equals_lower("1")) {
751 if (success_ptr)
752 *success_ptr = true;
753 return true;
754 }
755 if (success_ptr)
756 *success_ptr = false;
757 return fail_value;
758}
759
760char Args::StringToChar(const char *s, char fail_value, bool *success_ptr) {
761 bool success = false;
762 char result = fail_value;
763
764 if (s) {
765 size_t length = strlen(s);
766 if (length == 1) {
767 success = true;
768 result = s[0];
769 }
770 }
771 if (success_ptr)
772 *success_ptr = success;
773 return result;
774}
775
776const char *Args::StringToVersion(const char *s, uint32_t &major,
777 uint32_t &minor, uint32_t &update) {
778 major = UINT32_MAX;
779 minor = UINT32_MAX;
780 update = UINT32_MAX;
781
782 if (s && s[0]) {
783 char *pos = nullptr;
784 unsigned long uval32 = ::strtoul(s, &pos, 0);
785 if (pos == s)
786 return s;
787 major = uval32;
788 if (*pos == '\0') {
789 return pos; // Decoded major and got end of string
790 } else if (*pos == '.') {
791 const char *minor_cstr = pos + 1;
792 uval32 = ::strtoul(minor_cstr, &pos, 0);
793 if (pos == minor_cstr)
794 return pos; // Didn't get any digits for the minor version...
795 minor = uval32;
796 if (*pos == '.') {
797 const char *update_cstr = pos + 1;
798 uval32 = ::strtoul(update_cstr, &pos, 0);
799 if (pos == update_cstr)
800 return pos;
801 update = uval32;
802 }
803 return pos;
804 }
805 }
806 return nullptr;
807}
808
809const char *Args::GetShellSafeArgument(const FileSpec &shell,
810 const char *unsafe_arg,
811 std::string &safe_arg) {
812 struct ShellDescriptor {
813 ConstString m_basename;
814 const char *m_escapables;
815 };
816
817 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
818 {ConstString("tcsh"), " '\"<>()&$"},
819 {ConstString("sh"), " '\"<>()&"}};
820
821 // safe minimal set
822 const char *escapables = " '\"";
823
824 if (auto basename = shell.GetFilename()) {
825 for (const auto &Shell : g_Shells) {
826 if (Shell.m_basename == basename) {
827 escapables = Shell.m_escapables;
828 break;
829 }
830 }
831 }
832
833 safe_arg.assign(unsafe_arg);
834 size_t prev_pos = 0;
835 while (prev_pos < safe_arg.size()) {
836 // Escape spaces and quotes
837 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
838 if (pos != std::string::npos) {
839 safe_arg.insert(pos, 1, '\\');
840 prev_pos = pos + 2;
841 } else
842 break;
843 }
844 return safe_arg.c_str();
845}
846
847int64_t Args::StringToOptionEnum(const char *s,
848 OptionEnumValueElement *enum_values,
849 int32_t fail_value, Error &error) {
850 if (enum_values) {
851 if (s && s[0]) {
852 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
853 if (strstr(enum_values[i].string_value, s) ==
854 enum_values[i].string_value) {
855 error.Clear();
856 return enum_values[i].value;
857 }
858 }
859 }
860
861 StreamString strm;
862 strm.PutCString("invalid enumeration value, valid values are: ");
863 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
864 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
865 }
866 error.SetErrorString(strm.GetData());
867 } else {
868 error.SetErrorString("invalid enumeration argument");
869 }
870 return fail_value;
871}
872
873ScriptLanguage Args::StringToScriptLanguage(const char *s,
874 ScriptLanguage fail_value,
875 bool *success_ptr) {
876 if (s && s[0]) {
877 if ((::strcasecmp(s, "python") == 0) ||
878 (::strcasecmp(s, "default") == 0 &&
879 eScriptLanguagePython == eScriptLanguageDefault)) {
880 if (success_ptr)
881 *success_ptr = true;
882 return eScriptLanguagePython;
883 }
884 if (::strcasecmp(s, "none")) {
885 if (success_ptr)
886 *success_ptr = true;
887 return eScriptLanguageNone;
888 }
889 }
890 if (success_ptr)
891 *success_ptr = false;
892 return fail_value;
893}
894
895Error Args::StringToFormat(const char *s, lldb::Format &format,
896 size_t *byte_size_ptr) {
897 format = eFormatInvalid;
898 Error error;
899
900 if (s && s[0]) {
901 if (byte_size_ptr) {
902 if (isdigit(s[0])) {
903 char *format_char = nullptr;
904 unsigned long byte_size = ::strtoul(s, &format_char, 0);
905 if (byte_size != ULONG_MAX)
906 *byte_size_ptr = byte_size;
907 s = format_char;
908 } else
909 *byte_size_ptr = 0;
910 }
911
912 const bool partial_match_ok = true;
913 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
914 StreamString error_strm;
915 error_strm.Printf(
916 "Invalid format character or name '%s'. Valid values are:\n", s);
917 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
918 char format_char = FormatManager::GetFormatAsFormatChar(f);
919 if (format_char)
920 error_strm.Printf("'%c' or ", format_char);
921
922 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
923 error_strm.EOL();
924 }
925
926 if (byte_size_ptr)
927 error_strm.PutCString(
928 "An optional byte size can precede the format character.\n");
929 error.SetErrorString(error_strm.GetString().c_str());
930 }
931
932 if (error.Fail())
933 return error;
934 } else {
935 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
936 }
937 return error;
938}
939
940lldb::Encoding Args::StringToEncoding(const char *s,
941 lldb::Encoding fail_value) {
942 if (!s)
943 return fail_value;
944 return StringToEncoding(llvm::StringRef(s), fail_value);
945}
946
947lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
948 lldb::Encoding fail_value) {
949 return llvm::StringSwitch<lldb::Encoding>(s)
950 .Case("uint", eEncodingUint)
951 .Case("sint", eEncodingSint)
952 .Case("ieee754", eEncodingIEEE754)
953 .Case("vector", eEncodingVector)
954 .Default(fail_value);
955}
956
957uint32_t Args::StringToGenericRegister(const char *s) {
958 if (!s)
959 return LLDB_INVALID_REGNUM;
960 return StringToGenericRegister(llvm::StringRef(s));
961}
962
963uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
964 if (s.empty())
965 return LLDB_INVALID_REGNUM;
966 uint32_t result = llvm::StringSwitch<uint32_t>(s)
967 .Case("pc", LLDB_REGNUM_GENERIC_PC)
968 .Case("sp", LLDB_REGNUM_GENERIC_SP)
969 .Case("fp", LLDB_REGNUM_GENERIC_FP)
970 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
971 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
972 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
973 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
974 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
975 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
976 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
977 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
978 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
979 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
980 .Default(LLDB_INVALID_REGNUM);
981 return result;
982}
983
984void Args::LongestCommonPrefix(std::string &common_prefix) {
985 arg_sstr_collection::iterator pos, end = m_args.end();
986 pos = m_args.begin();
987 if (pos == end)
988 common_prefix.clear();
989 else
990 common_prefix = (*pos);
991
992 for (++pos; pos != end; ++pos) {
993 size_t new_size = (*pos).size();
994
995 // First trim common_prefix if it is longer than the current element:
996 if (common_prefix.size() > new_size)
997 common_prefix.erase(new_size);
998
999 // Then trim it at the first disparity:
1000
1001 for (size_t i = 0; i < common_prefix.size(); i++) {
1002 if ((*pos)[i] != common_prefix[i]) {
1003 common_prefix.erase(i);
1004 break;
1005 }
1006 }
1007
1008 // If we've emptied the common prefix, we're done.
1009 if (common_prefix.empty())
1010 break;
1011 }
1012}
1013
1014void Args::AddOrReplaceEnvironmentVariable(const char *env_var_name,
1015 const char *new_value) {
1016 if (!env_var_name || !new_value)
1017 return;
1018
1019 // Build the new entry.
1020 StreamString stream;
1021 stream << env_var_name;
1022 stream << '=';
1023 stream << new_value;
1024 stream.Flush();
1025
1026 // Find the environment variable if present and replace it.
1027 for (size_t i = 0; i < GetArgumentCount(); ++i) {
1028 // Get the env var value.
1029 const char *arg_value = GetArgumentAtIndex(i);
1030 if (!arg_value)
1031 continue;
1032
1033 // Find the name of the env var: before the first =.
1034 auto equal_p = strchr(arg_value, '=');
1035 if (!equal_p)
1036 continue;
1037
1038 // Check if the name matches the given env_var_name.
1039 if (strncmp(env_var_name, arg_value, equal_p - arg_value) == 0) {
1040 ReplaceArgumentAtIndex(i, stream.GetString().c_str());
1041 return;
1042 }
1043 }
1044
1045 // We didn't find it. Append it instead.
1046 AppendArgument(stream.GetString().c_str());
1047}
1048
1049bool Args::ContainsEnvironmentVariable(const char *env_var_name,
1050 size_t *argument_index) const {
1051 // Validate args.
1052 if (!env_var_name)
1053 return false;
1054
1055 // Check each arg to see if it matches the env var name.
1056 for (size_t i = 0; i < GetArgumentCount(); ++i) {
1057 // Get the arg value.
1058 const char *argument_value = GetArgumentAtIndex(i);
1059 if (!argument_value)
1060 continue;
1061
1062 // Check if we are the "{env_var_name}={env_var_value}" style.
1063 const char *equal_p = strchr(argument_value, '=');
1064 if (equal_p) {
1065 if (strncmp(env_var_name, argument_value, equal_p - argument_value) ==
1066 0) {
1067 // We matched.
1068 if (argument_index)
1069 *argument_index = i;
1070 return true;
1071 }
1072 } else {
1073 // We're a simple {env_var_name}-style entry.
1074 if (strcmp(argument_value, env_var_name) == 0) {
1075 // We matched.
1076 if (argument_index)
1077 *argument_index = i;
1078 return true;
1079 }
1080 }
1081 }
1082
1083 // We didn't find a match.
1084 return false;
1085}
1086
1087size_t Args::FindArgumentIndexForOption(Option *long_options,
1088 int long_options_index) {
1089 char short_buffer[3];
1090 char long_buffer[255];
1091 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
1092 long_options[long_options_index].val);
1093 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
1094 long_options[long_options_index].definition->long_option);
1095 size_t end = GetArgumentCount();
1096 size_t idx = 0;
1097 while (idx < end) {
1098 if ((::strncmp(GetArgumentAtIndex(idx), short_buffer,
1099 strlen(short_buffer)) == 0) ||
1100 (::strncmp(GetArgumentAtIndex(idx), long_buffer, strlen(long_buffer)) ==
1101 0)) {
1102 return idx;
1103 }
1104 ++idx;
1105 }
1106
1107 return end;
1108}
1109
1110bool Args::IsPositionalArgument(const char *arg) {
1111 if (arg == nullptr)
1112 return false;
1113
1114 bool is_positional = true;
1115 const char *cptr = arg;
1116
1117 if (cptr[0] == '%') {
1118 ++cptr;
1119 while (isdigit(cptr[0]))
1120 ++cptr;
1121 if (cptr[0] != '\0')
1122 is_positional = false;
1123 } else
1124 is_positional = false;
1125
1126 return is_positional;
1127}
1128
1129void Args::ParseAliasOptions(Options &options, CommandReturnObject &result,
1130 OptionArgVector *option_arg_vector,
1131 std::string &raw_input_string) {
1132 StreamString sstr;
1133 int i;
1134 Option *long_options = options.GetLongOptions();
1135
1136 if (long_options == nullptr) {
1137 result.AppendError("invalid long options");
1138 result.SetStatus(eReturnStatusFailed);
1139 return;
1140 }
1141
1142 for (i = 0; long_options[i].definition != nullptr; ++i) {
1143 if (long_options[i].flag == nullptr) {
1144 sstr << (char)long_options[i].val;
1145 switch (long_options[i].definition->option_has_arg) {
1146 default:
1147 case OptionParser::eNoArgument:
1148 break;
1149 case OptionParser::eRequiredArgument:
1150 sstr << ":";
1151 break;
1152 case OptionParser::eOptionalArgument:
1153 sstr << "::";
1154 break;
1155 }
1156 }
1157 }
1158
1159 std::unique_lock<std::mutex> lock;
1160 OptionParser::Prepare(lock);
1161 int val;
1162 while (1) {
1163 int long_options_index = -1;
1164 val =
1165 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1166 sstr.GetData(), long_options, &long_options_index);
1167
1168 if (val == -1)
1169 break;
1170
1171 if (val == '?') {
1172 result.AppendError("unknown or ambiguous option");
1173 result.SetStatus(eReturnStatusFailed);
1174 break;
1175 }
1176
1177 if (val == 0)
1178 continue;
1179
1180 options.OptionSeen(val);
1181
1182 // Look up the long option index
1183 if (long_options_index == -1) {
1184 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1185 long_options[j].val;
1186 ++j) {
1187 if (long_options[j].val == val) {
1188 long_options_index = j;
1189 break;
1190 }
1191 }
1192 }
1193
1194 // See if the option takes an argument, and see if one was supplied.
1195 if (long_options_index >= 0) {
1196 StreamString option_str;
1197 option_str.Printf("-%c", val);
1198 const OptionDefinition *def = long_options[long_options_index].definition;
1199 int has_arg =
1200 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1201
1202 switch (has_arg) {
1203 case OptionParser::eNoArgument:
1204 option_arg_vector->push_back(OptionArgPair(
1205 std::string(option_str.GetData()),
1206 OptionArgValue(OptionParser::eNoArgument, "<no-argument>")));
1207 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1208 break;
1209 case OptionParser::eRequiredArgument:
1210 if (OptionParser::GetOptionArgument() != nullptr) {
1211 option_arg_vector->push_back(OptionArgPair(
1212 std::string(option_str.GetData()),
1213 OptionArgValue(OptionParser::eRequiredArgument,
1214 std::string(OptionParser::GetOptionArgument()))));
1215 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1216 } else {
1217 result.AppendErrorWithFormat(
1218 "Option '%s' is missing argument specifier.\n",
1219 option_str.GetData());
1220 result.SetStatus(eReturnStatusFailed);
1221 }
1222 break;
1223 case OptionParser::eOptionalArgument:
1224 if (OptionParser::GetOptionArgument() != nullptr) {
1225 option_arg_vector->push_back(OptionArgPair(
1226 std::string(option_str.GetData()),
1227 OptionArgValue(OptionParser::eOptionalArgument,
1228 std::string(OptionParser::GetOptionArgument()))));
1229 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1230 } else {
1231 option_arg_vector->push_back(
1232 OptionArgPair(std::string(option_str.GetData()),
1233 OptionArgValue(OptionParser::eOptionalArgument,
1234 "<no-argument>")));
1235 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1236 }
1237 break;
1238 default:
1239 result.AppendErrorWithFormat("error with options table; invalid value "
1240 "in has_arg field for option '%c'.\n",
1241 val);
1242 result.SetStatus(eReturnStatusFailed);
1243 break;
1244 }
1245 } else {
1246 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1247 result.SetStatus(eReturnStatusFailed);
1248 }
1249
1250 if (long_options_index >= 0) {
1251 // Find option in the argument list; also see if it was supposed to take
1252 // an argument and if one was
1253 // supplied. Remove option (and argument, if given) from the argument
1254 // list. Also remove them from
1255 // the raw_input_string, if one was passed in.
1256 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
1257 if (idx < GetArgumentCount()) {
1258 if (raw_input_string.size() > 0) {
1259 const char *tmp_arg = GetArgumentAtIndex(idx);
1260 size_t pos = raw_input_string.find(tmp_arg);
1261 if (pos != std::string::npos)
1262 raw_input_string.erase(pos, strlen(tmp_arg));
1263 }
1264 ReplaceArgumentAtIndex(idx, "");
1265 if ((long_options[long_options_index].definition->option_has_arg !=
1266 OptionParser::eNoArgument) &&
1267 (OptionParser::GetOptionArgument() != nullptr) &&
1268 (idx + 1 < GetArgumentCount()) &&
1269 (strcmp(OptionParser::GetOptionArgument(),
1270 GetArgumentAtIndex(idx + 1)) == 0)) {
1271 if (raw_input_string.size() > 0) {
1272 const char *tmp_arg = GetArgumentAtIndex(idx + 1);
1273 size_t pos = raw_input_string.find(tmp_arg);
1274 if (pos != std::string::npos)
1275 raw_input_string.erase(pos, strlen(tmp_arg));
1276 }
1277 ReplaceArgumentAtIndex(idx + 1, "");
1278 }
1279 }
1280 }
1281
1282 if (!result.Succeeded())
1283 break;
1284 }
1285}
1286
1287void Args::ParseArgsForCompletion(Options &options,
1288 OptionElementVector &option_element_vector,
1289 uint32_t cursor_index) {
1290 StreamString sstr;
1291 Option *long_options = options.GetLongOptions();
1292 option_element_vector.clear();
1293
1294 if (long_options == nullptr) {
1295 return;
1296 }
1297
1298 // Leading : tells getopt to return a : for a missing option argument AND
1299 // to suppress error messages.
1300
1301 sstr << ":";
1302 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1303 if (long_options[i].flag == nullptr) {
1304 sstr << (char)long_options[i].val;
1305 switch (long_options[i].definition->option_has_arg) {
1306 default:
1307 case OptionParser::eNoArgument:
1308 break;
1309 case OptionParser::eRequiredArgument:
1310 sstr << ":";
1311 break;
1312 case OptionParser::eOptionalArgument:
1313 sstr << "::";
1314 break;
1315 }
1316 }
1317 }
1318
1319 std::unique_lock<std::mutex> lock;
1320 OptionParser::Prepare(lock);
1321 OptionParser::EnableError(false);
1322
1323 int val;
1324 const OptionDefinition *opt_defs = options.GetDefinitions();
1325
1326 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
1327 // options to the front.
1328 // So we have to build another Arg and pass that to OptionParser::Parse so it
1329 // doesn't
1330 // change the one we have.
1331
1332 std::vector<const char *> dummy_vec(
1333 GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
1334
1335 bool failed_once = false;
1336 uint32_t dash_dash_pos = -1;
1337
1338 while (1) {
1339 bool missing_argument = false;
1340 int long_options_index = -1;
1341
1342 val = OptionParser::Parse(
1343 dummy_vec.size() - 1, const_cast<char *const *>(&dummy_vec.front()),
1344 sstr.GetData(), long_options, &long_options_index);
1345
1346 if (val == -1) {
1347 // When we're completing a "--" which is the last option on line,
1348 if (failed_once)
1349 break;
1350
1351 failed_once = true;
1352
1353 // If this is a bare "--" we mark it as such so we can complete it
1354 // successfully later.
1355 // Handling the "--" is a little tricky, since that may mean end of
1356 // options or arguments, or the
1357 // user might want to complete options by long name. I make this work by
1358 // checking whether the
1359 // cursor is in the "--" argument, and if so I assume we're completing the
1360 // long option, otherwise
1361 // I let it pass to OptionParser::Parse which will terminate the option
1362 // parsing.
1363 // Note, in either case we continue parsing the line so we can figure out
1364 // what other options
1365 // were passed. This will be useful when we come to restricting
1366 // completions based on what other
1367 // options we've seen on the line.
1368
1369 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1370 dummy_vec.size() - 1 &&
1371 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1372 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1373 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1374 cursor_index) {
1375 option_element_vector.push_back(
1376 OptionArgElement(OptionArgElement::eBareDoubleDash,
1377 OptionParser::GetOptionIndex() - 1,
1378 OptionArgElement::eBareDoubleDash));
1379 continue;
1380 } else
1381 break;
1382 } else
1383 break;
1384 } else if (val == '?') {
1385 option_element_vector.push_back(
1386 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1387 OptionParser::GetOptionIndex() - 1,
1388 OptionArgElement::eUnrecognizedArg));
1389 continue;
1390 } else if (val == 0) {
1391 continue;
1392 } else if (val == ':') {
1393 // This is a missing argument.
1394 val = OptionParser::GetOptionErrorCause();
1395 missing_argument = true;
1396 }
1397
1398 ((Options *)&options)->OptionSeen(val);
1399
1400 // Look up the long option index
1401 if (long_options_index == -1) {
1402 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1403 long_options[j].val;
1404 ++j) {
1405 if (long_options[j].val == val) {
1406 long_options_index = j;
1407 break;
1408 }
1409 }
1410 }
1411
1412 // See if the option takes an argument, and see if one was supplied.
1413 if (long_options_index >= 0) {
1414 int opt_defs_index = -1;
1415 for (int i = 0;; i++) {
1416 if (opt_defs[i].short_option == 0)
1417 break;
1418 else if (opt_defs[i].short_option == val) {
1419 opt_defs_index = i;
1420 break;
1421 }
1422 }
1423
1424 const OptionDefinition *def = long_options[long_options_index].definition;
1425 int has_arg =
1426 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1427 switch (has_arg) {
1428 case OptionParser::eNoArgument:
1429 option_element_vector.push_back(OptionArgElement(
1430 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1431 break;
1432 case OptionParser::eRequiredArgument:
1433 if (OptionParser::GetOptionArgument() != nullptr) {
1434 int arg_index;
1435 if (missing_argument)
1436 arg_index = -1;
1437 else
1438 arg_index = OptionParser::GetOptionIndex() - 1;
1439
1440 option_element_vector.push_back(OptionArgElement(
1441 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1442 } else {
1443 option_element_vector.push_back(OptionArgElement(
1444 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1445 }
1446 break;
1447 case OptionParser::eOptionalArgument:
1448 if (OptionParser::GetOptionArgument() != nullptr) {
1449 option_element_vector.push_back(OptionArgElement(
1450 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1451 OptionParser::GetOptionIndex() - 1));
1452 } else {
1453 option_element_vector.push_back(OptionArgElement(
1454 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1455 OptionParser::GetOptionIndex() - 1));
1456 }
1457 break;
1458 default:
1459 // The options table is messed up. Here we'll just continue
1460 option_element_vector.push_back(
1461 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1462 OptionParser::GetOptionIndex() - 1,
1463 OptionArgElement::eUnrecognizedArg));
1464 break;
1465 }
1466 } else {
1467 option_element_vector.push_back(
1468 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1469 OptionParser::GetOptionIndex() - 1,
1470 OptionArgElement::eUnrecognizedArg));
1471 }
1472 }
1473
1474 // Finally we have to handle the case where the cursor index points at a
1475 // single "-". We want to mark that in
1476 // the option_element_vector, but only if it is not after the "--". But it
1477 // turns out that OptionParser::Parse just ignores
1478 // an isolated "-". So we have to look it up by hand here. We only care if
1479 // it is AT the cursor position.
1480 // Note, a single quoted dash is not the same as a single dash...
1481
1482 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1483 cursor_index < dash_dash_pos) &&
1484 m_args_quote_char[cursor_index] == '\0' &&
1485 strcmp(GetArgumentAtIndex(cursor_index), "-") == 0) {
1486 option_element_vector.push_back(
1487 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1488 OptionArgElement::eBareDash));
1489 }
1490}
1491
1492void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1493 dst.clear();
1494 if (src) {
1495 for (const char *p = src; *p != '\0'; ++p) {
1496 size_t non_special_chars = ::strcspn(p, "\\");
1497 if (non_special_chars > 0) {
1498 dst.append(p, non_special_chars);
1499 p += non_special_chars;
1500 if (*p == '\0')
1501 break;
1502 }
1503
1504 if (*p == '\\') {
1505 ++p; // skip the slash
1506 switch (*p) {
1507 case 'a':
1508 dst.append(1, '\a');
1509 break;
1510 case 'b':
1511 dst.append(1, '\b');
1512 break;
1513 case 'f':
1514 dst.append(1, '\f');
1515 break;
1516 case 'n':
1517 dst.append(1, '\n');
1518 break;
1519 case 'r':
1520 dst.append(1, '\r');
1521 break;
1522 case 't':
1523 dst.append(1, '\t');
1524 break;
1525 case 'v':
1526 dst.append(1, '\v');
1527 break;
1528 case '\\':
1529 dst.append(1, '\\');
1530 break;
1531 case '\'':
1532 dst.append(1, '\'');
1533 break;
1534 case '"':
1535 dst.append(1, '"');
1536 break;
1537 case '0':
1538 // 1 to 3 octal chars
1539 {
1540 // Make a string that can hold onto the initial zero char,
1541 // up to 3 octal digits, and a terminating NULL.
1542 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1543
1544 int i;
1545 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1546 oct_str[i] = p[i];
1547
1548 // We don't want to consume the last octal character since
1549 // the main for loop will do this for us, so we advance p by
1550 // one less than i (even if i is zero)
1551 p += i - 1;
1552 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1553 if (octal_value <= UINT8_MAX) {
1554 dst.append(1, (char)octal_value);
1555 }
1556 }
1557 break;
1558
1559 case 'x':
1560 // hex number in the format
1561 if (isxdigit(p[1])) {
1562 ++p; // Skip the 'x'
1563
1564 // Make a string that can hold onto two hex chars plus a
1565 // NULL terminator
1566 char hex_str[3] = {*p, '\0', '\0'};
1567 if (isxdigit(p[1])) {
1568 ++p; // Skip the first of the two hex chars
1569 hex_str[1] = *p;
1570 }
1571
1572 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1573 if (hex_value <= UINT8_MAX)
1574 dst.append(1, (char)hex_value);
1575 } else {
1576 dst.append(1, 'x');
1577 }
1578 break;
1579
1580 default:
1581 // Just desensitize any other character by just printing what
1582 // came after the '\'
1583 dst.append(1, *p);
1584 break;
1585 }
1586 }
1587 }
1588 }
1589}
1590
1591void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1592 dst.clear();
1593 if (src) {
1594 for (const char *p = src; *p != '\0'; ++p) {
1595 if (isprint8(*p))
1596 dst.append(1, *p);
1597 else {
1598 switch (*p) {
1599 case '\a':
1600 dst.append("\\a");
1601 break;
1602 case '\b':
1603 dst.append("\\b");
1604 break;
1605 case '\f':
1606 dst.append("\\f");
1607 break;
1608 case '\n':
1609 dst.append("\\n");
1610 break;
1611 case '\r':
1612 dst.append("\\r");
1613 break;
1614 case '\t':
1615 dst.append("\\t");
1616 break;
1617 case '\v':
1618 dst.append("\\v");
1619 break;
1620 case '\'':
1621 dst.append("\\'");
1622 break;
1623 case '"':
1624 dst.append("\\\"");
1625 break;
1626 case '\\':
1627 dst.append("\\\\");
1628 break;
1629 default: {
1630 // Just encode as octal
1631 dst.append("\\0");
1632 char octal_str[32];
1633 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1634 dst.append(octal_str);
1635 } break;
1636 }
1637 }
1638 }
1639 }
1640}
1641
1642std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1643 char quote_char) {
1644 const char *chars_to_escape = nullptr;
1645 switch (quote_char) {
1646 case '\0':
1647 chars_to_escape = " \t\\'\"`";
1648 break;
1649 case '\'':
1650 chars_to_escape = "";
1651 break;
1652 case '"':
1653 chars_to_escape = "$\"`\\";
1654 break;
1655 default:
1656 assert(false && "Unhandled quote character");
1657 }
1658
1659 std::string res;
1660 res.reserve(arg.size());
1661 for (char c : arg) {
1662 if (::strchr(chars_to_escape, c))
1663 res.push_back('\\');
1664 res.push_back(c);
1665 }
1666 return res;
1667}