blob: 0edb9bcd02b75a59305ab2087c907ba61e447dbb [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
Eli Friedman5661f922010-06-09 10:59:23 +000011#include <cstdlib>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C++ Includes
13// Other libraries and framework includes
14// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015#include "lldb/Core/Stream.h"
16#include "lldb/Core/StreamFile.h"
17#include "lldb/Core/StreamString.h"
Enrico Granata5548cb52013-01-28 23:47:25 +000018#include "lldb/DataFormatters/FormatManager.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000019#include "lldb/Host/StringConvert.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "lldb/Interpreter/Args.h"
Zachary Turnerd37221d2014-07-09 16:31:49 +000021#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Interpreter/CommandReturnObject.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000023#include "lldb/Interpreter/Options.h"
Greg Claytonb9d5df52012-12-06 22:49:16 +000024#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000025#include "lldb/Target/StackFrame.h"
Greg Claytonb9d5df52012-12-06 22:49:16 +000026#include "lldb/Target/Target.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027
Zachary Turner54695a32016-08-29 19:58:14 +000028#include "llvm/ADT/StringSwitch.h"
29
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030using namespace lldb;
31using namespace lldb_private;
32
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033//----------------------------------------------------------------------
34// Args constructor
35//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000036Args::Args(llvm::StringRef command) : m_args(), m_argv(), m_args_quote_char() {
37 SetCommandString(command);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038}
39
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000041// 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:50 +000043// rhs.m_argv into m_argv since it will point to the "const char *" c
Greg Clayton8b82f082011-04-12 05:54:46 +000044// strings in rhs.m_args. We need to copy the string list and update our
Kate Stoneb9c1b512016-09-06 20:57:50 +000045// own m_argv appropriately.
Greg Clayton8b82f082011-04-12 05:54:46 +000046//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000047Args::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:46 +000064 UpdateArgvFromArgs();
Kate Stoneb9c1b512016-09-06 20:57:50 +000065 }
66 return *this;
Greg Clayton8b82f082011-04-12 05:54:46 +000067}
68
69//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070// Destructor
71//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000072Args::~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:24 +000088}
89
Kate Stoneb9c1b512016-09-06 20:57:50 +000090bool 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:24 +000099}
100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101bool 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 Tice2d5289d2010-12-10 00:26:54 +0000116}
117
Pavel Labath00b7f952015-03-02 12:46:22 +0000118// A helper function for argument parsing.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119// 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:22 +0000125// quote.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126static 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:22 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 // 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:22 +0000139
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 // We have found a backslash.
141 quoted = quoted.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 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:22 +0000147 }
148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 // 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:22 +0000160}
161
162// A helper function for SetCommandString.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163// 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:22 +0000169// character.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170llvm::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:22 +0000177
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178 std::string arg;
Pavel Labath00b7f952015-03-02 12:46:22 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 // 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:22 +0000185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 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:22 +0000192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 if (command.empty())
194 break;
Pavel Labath00b7f952015-03-02 12:46:22 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 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:22 +0000243 command = command.drop_front();
Pavel Labath00b7f952015-03-02 12:46:22 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 break;
246 }
247 } while (!arg_complete);
Pavel Labath00b7f952015-03-02 12:46:22 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 m_args.push_back(arg);
250 m_args_quote_char.push_back(first_quote_char);
251 return command;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000252}
253
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254void 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:24 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 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:22 +0000263 command = command.ltrim(k_space_separators);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 }
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:24 +0000294 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 }
Pavel Labath00b7f952015-03-02 12:46:22 +0000296
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 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:24 +0000302}
303
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304void 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:24 +0000313}
314
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315size_t Args::GetArgumentCount() const {
316 if (m_argv.empty())
317 return 0;
318 return m_argv.size() - 1;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319}
320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321const 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:24 +0000325}
326
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327char 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:24 +0000331}
332
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333char **Args::GetArgumentVector() {
334 if (!m_argv.empty())
335 return const_cast<char **>(&m_argv[0]);
336 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337}
338
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339const 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:24 +0000343}
344
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345void 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:24 +0000353}
354
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355const 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:24 +0000360}
361
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362void 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:24 +0000367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369void 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:24 +0000374}
375
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376const char *Args::AppendArgument(const char *arg_cstr, char quote_char) {
377 return InsertArgumentAtIndex(GetArgumentCount(), arg_cstr, quote_char);
Greg Clayton982c9762011-11-03 21:22:33 +0000378}
379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380const 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:24 +0000400}
401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402const 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:24 +0000411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 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:24 +0000416 if (idx >= m_args_quote_char.size())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 m_args_quote_char.resize(idx + 1);
418 m_args_quote_char[idx] = quote_char;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000419 return GetArgumentAtIndex(idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 }
421 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422}
423
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424void 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:24 +0000432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 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:24 +0000440}
441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442void 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:24 +0000447
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 // 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:24 +0000458}
459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460void 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:24 +0000465
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 if (argv) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000467 // First copy each string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 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:24 +0000474 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000476
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 UpdateArgvFromArgs();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000478}
479
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480Error 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:24 +0000487 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 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:27 +0000495 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 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:27 +0000506 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 }
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:27 +0000518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 // Did we get an error?
520 if (val == '?') {
521 error.SetErrorStringWithFormat("unknown or ambiguous option");
522 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 // 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:27 +0000597}
598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599void 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
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000735bool Args::StringToBoolean(const char *s, bool fail_value,
736 bool *success_ptr) {
737 return StringToBoolean(llvm::StringRef(s ? s : ""), fail_value, success_ptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738}
739
740bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
741 bool *success_ptr) {
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000742 if (success_ptr)
743 *success_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 ref = ref.trim();
745 if (ref.equals_lower("false") || ref.equals_lower("off") ||
746 ref.equals_lower("no") || ref.equals_lower("0")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 return false;
748 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
749 ref.equals_lower("yes") || ref.equals_lower("1")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 return true;
751 }
752 if (success_ptr)
753 *success_ptr = false;
754 return fail_value;
755}
756
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000757char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 if (success_ptr)
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000759 *success_ptr = false;
760 if (s.size() != 1)
761 return fail_value;
762
763 if (success_ptr)
764 *success_ptr = true;
765 return s[0];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766}
767
768const char *Args::StringToVersion(const char *s, uint32_t &major,
769 uint32_t &minor, uint32_t &update) {
770 major = UINT32_MAX;
771 minor = UINT32_MAX;
772 update = UINT32_MAX;
773
774 if (s && s[0]) {
775 char *pos = nullptr;
776 unsigned long uval32 = ::strtoul(s, &pos, 0);
777 if (pos == s)
778 return s;
779 major = uval32;
780 if (*pos == '\0') {
781 return pos; // Decoded major and got end of string
782 } else if (*pos == '.') {
783 const char *minor_cstr = pos + 1;
784 uval32 = ::strtoul(minor_cstr, &pos, 0);
785 if (pos == minor_cstr)
786 return pos; // Didn't get any digits for the minor version...
787 minor = uval32;
788 if (*pos == '.') {
789 const char *update_cstr = pos + 1;
790 uval32 = ::strtoul(update_cstr, &pos, 0);
791 if (pos == update_cstr)
792 return pos;
793 update = uval32;
794 }
795 return pos;
796 }
797 }
798 return nullptr;
799}
800
801const char *Args::GetShellSafeArgument(const FileSpec &shell,
802 const char *unsafe_arg,
803 std::string &safe_arg) {
804 struct ShellDescriptor {
805 ConstString m_basename;
806 const char *m_escapables;
807 };
808
809 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
810 {ConstString("tcsh"), " '\"<>()&$"},
811 {ConstString("sh"), " '\"<>()&"}};
812
813 // safe minimal set
814 const char *escapables = " '\"";
815
816 if (auto basename = shell.GetFilename()) {
817 for (const auto &Shell : g_Shells) {
818 if (Shell.m_basename == basename) {
819 escapables = Shell.m_escapables;
820 break;
821 }
822 }
823 }
824
825 safe_arg.assign(unsafe_arg);
826 size_t prev_pos = 0;
827 while (prev_pos < safe_arg.size()) {
828 // Escape spaces and quotes
829 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
830 if (pos != std::string::npos) {
831 safe_arg.insert(pos, 1, '\\');
832 prev_pos = pos + 2;
833 } else
834 break;
835 }
836 return safe_arg.c_str();
837}
838
839int64_t Args::StringToOptionEnum(const char *s,
840 OptionEnumValueElement *enum_values,
841 int32_t fail_value, Error &error) {
842 if (enum_values) {
843 if (s && s[0]) {
844 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
845 if (strstr(enum_values[i].string_value, s) ==
846 enum_values[i].string_value) {
847 error.Clear();
848 return enum_values[i].value;
849 }
850 }
851 }
852
853 StreamString strm;
854 strm.PutCString("invalid enumeration value, valid values are: ");
855 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
856 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
857 }
858 error.SetErrorString(strm.GetData());
859 } else {
860 error.SetErrorString("invalid enumeration argument");
861 }
862 return fail_value;
863}
864
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000865lldb::ScriptLanguage
866Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
867 bool *success_ptr) {
868 if (success_ptr)
869 *success_ptr = true;
870
871 if (s.equals_lower("python"))
872 return eScriptLanguagePython;
873 if (s.equals_lower("default"))
874 return eScriptLanguageDefault;
875 if (s.equals_lower("none"))
876 return eScriptLanguageNone;
877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 if (success_ptr)
879 *success_ptr = false;
880 return fail_value;
881}
882
883Error Args::StringToFormat(const char *s, lldb::Format &format,
884 size_t *byte_size_ptr) {
885 format = eFormatInvalid;
886 Error error;
887
888 if (s && s[0]) {
889 if (byte_size_ptr) {
890 if (isdigit(s[0])) {
891 char *format_char = nullptr;
892 unsigned long byte_size = ::strtoul(s, &format_char, 0);
893 if (byte_size != ULONG_MAX)
894 *byte_size_ptr = byte_size;
895 s = format_char;
896 } else
897 *byte_size_ptr = 0;
898 }
899
900 const bool partial_match_ok = true;
901 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
902 StreamString error_strm;
903 error_strm.Printf(
904 "Invalid format character or name '%s'. Valid values are:\n", s);
905 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
906 char format_char = FormatManager::GetFormatAsFormatChar(f);
907 if (format_char)
908 error_strm.Printf("'%c' or ", format_char);
909
910 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
911 error_strm.EOL();
912 }
913
914 if (byte_size_ptr)
915 error_strm.PutCString(
916 "An optional byte size can precede the format character.\n");
917 error.SetErrorString(error_strm.GetString().c_str());
918 }
919
920 if (error.Fail())
921 return error;
922 } else {
923 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
924 }
925 return error;
926}
927
928lldb::Encoding Args::StringToEncoding(const char *s,
929 lldb::Encoding fail_value) {
930 if (!s)
931 return fail_value;
932 return StringToEncoding(llvm::StringRef(s), fail_value);
933}
934
935lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
936 lldb::Encoding fail_value) {
937 return llvm::StringSwitch<lldb::Encoding>(s)
938 .Case("uint", eEncodingUint)
939 .Case("sint", eEncodingSint)
940 .Case("ieee754", eEncodingIEEE754)
941 .Case("vector", eEncodingVector)
942 .Default(fail_value);
943}
944
945uint32_t Args::StringToGenericRegister(const char *s) {
946 if (!s)
947 return LLDB_INVALID_REGNUM;
948 return StringToGenericRegister(llvm::StringRef(s));
949}
950
951uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
952 if (s.empty())
953 return LLDB_INVALID_REGNUM;
954 uint32_t result = llvm::StringSwitch<uint32_t>(s)
955 .Case("pc", LLDB_REGNUM_GENERIC_PC)
956 .Case("sp", LLDB_REGNUM_GENERIC_SP)
957 .Case("fp", LLDB_REGNUM_GENERIC_FP)
958 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
959 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
960 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
961 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
962 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
963 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
964 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
965 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
966 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
967 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
968 .Default(LLDB_INVALID_REGNUM);
969 return result;
970}
971
972void Args::LongestCommonPrefix(std::string &common_prefix) {
973 arg_sstr_collection::iterator pos, end = m_args.end();
974 pos = m_args.begin();
975 if (pos == end)
976 common_prefix.clear();
977 else
978 common_prefix = (*pos);
979
980 for (++pos; pos != end; ++pos) {
981 size_t new_size = (*pos).size();
982
983 // First trim common_prefix if it is longer than the current element:
984 if (common_prefix.size() > new_size)
985 common_prefix.erase(new_size);
986
987 // Then trim it at the first disparity:
988
989 for (size_t i = 0; i < common_prefix.size(); i++) {
990 if ((*pos)[i] != common_prefix[i]) {
991 common_prefix.erase(i);
992 break;
993 }
994 }
995
996 // If we've emptied the common prefix, we're done.
997 if (common_prefix.empty())
998 break;
999 }
1000}
1001
1002void Args::AddOrReplaceEnvironmentVariable(const char *env_var_name,
1003 const char *new_value) {
1004 if (!env_var_name || !new_value)
1005 return;
1006
1007 // Build the new entry.
1008 StreamString stream;
1009 stream << env_var_name;
1010 stream << '=';
1011 stream << new_value;
1012 stream.Flush();
1013
1014 // Find the environment variable if present and replace it.
1015 for (size_t i = 0; i < GetArgumentCount(); ++i) {
1016 // Get the env var value.
1017 const char *arg_value = GetArgumentAtIndex(i);
1018 if (!arg_value)
1019 continue;
1020
1021 // Find the name of the env var: before the first =.
1022 auto equal_p = strchr(arg_value, '=');
1023 if (!equal_p)
1024 continue;
1025
1026 // Check if the name matches the given env_var_name.
1027 if (strncmp(env_var_name, arg_value, equal_p - arg_value) == 0) {
1028 ReplaceArgumentAtIndex(i, stream.GetString().c_str());
1029 return;
1030 }
1031 }
1032
1033 // We didn't find it. Append it instead.
1034 AppendArgument(stream.GetString().c_str());
1035}
1036
1037bool Args::ContainsEnvironmentVariable(const char *env_var_name,
1038 size_t *argument_index) const {
1039 // Validate args.
1040 if (!env_var_name)
1041 return false;
1042
1043 // Check each arg to see if it matches the env var name.
1044 for (size_t i = 0; i < GetArgumentCount(); ++i) {
1045 // Get the arg value.
1046 const char *argument_value = GetArgumentAtIndex(i);
1047 if (!argument_value)
1048 continue;
1049
1050 // Check if we are the "{env_var_name}={env_var_value}" style.
1051 const char *equal_p = strchr(argument_value, '=');
1052 if (equal_p) {
1053 if (strncmp(env_var_name, argument_value, equal_p - argument_value) ==
1054 0) {
1055 // We matched.
1056 if (argument_index)
1057 *argument_index = i;
1058 return true;
1059 }
1060 } else {
1061 // We're a simple {env_var_name}-style entry.
1062 if (strcmp(argument_value, env_var_name) == 0) {
1063 // We matched.
1064 if (argument_index)
1065 *argument_index = i;
1066 return true;
1067 }
1068 }
1069 }
1070
1071 // We didn't find a match.
1072 return false;
1073}
1074
1075size_t Args::FindArgumentIndexForOption(Option *long_options,
1076 int long_options_index) {
1077 char short_buffer[3];
1078 char long_buffer[255];
1079 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
1080 long_options[long_options_index].val);
1081 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
1082 long_options[long_options_index].definition->long_option);
1083 size_t end = GetArgumentCount();
1084 size_t idx = 0;
1085 while (idx < end) {
1086 if ((::strncmp(GetArgumentAtIndex(idx), short_buffer,
1087 strlen(short_buffer)) == 0) ||
1088 (::strncmp(GetArgumentAtIndex(idx), long_buffer, strlen(long_buffer)) ==
1089 0)) {
1090 return idx;
1091 }
1092 ++idx;
1093 }
1094
1095 return end;
1096}
1097
1098bool Args::IsPositionalArgument(const char *arg) {
1099 if (arg == nullptr)
1100 return false;
1101
1102 bool is_positional = true;
1103 const char *cptr = arg;
1104
1105 if (cptr[0] == '%') {
1106 ++cptr;
1107 while (isdigit(cptr[0]))
1108 ++cptr;
1109 if (cptr[0] != '\0')
1110 is_positional = false;
1111 } else
1112 is_positional = false;
1113
1114 return is_positional;
1115}
1116
1117void Args::ParseAliasOptions(Options &options, CommandReturnObject &result,
1118 OptionArgVector *option_arg_vector,
1119 std::string &raw_input_string) {
1120 StreamString sstr;
1121 int i;
1122 Option *long_options = options.GetLongOptions();
1123
1124 if (long_options == nullptr) {
1125 result.AppendError("invalid long options");
1126 result.SetStatus(eReturnStatusFailed);
1127 return;
1128 }
1129
1130 for (i = 0; long_options[i].definition != nullptr; ++i) {
1131 if (long_options[i].flag == nullptr) {
1132 sstr << (char)long_options[i].val;
1133 switch (long_options[i].definition->option_has_arg) {
1134 default:
1135 case OptionParser::eNoArgument:
1136 break;
1137 case OptionParser::eRequiredArgument:
1138 sstr << ":";
1139 break;
1140 case OptionParser::eOptionalArgument:
1141 sstr << "::";
1142 break;
1143 }
1144 }
1145 }
1146
1147 std::unique_lock<std::mutex> lock;
1148 OptionParser::Prepare(lock);
1149 int val;
1150 while (1) {
1151 int long_options_index = -1;
1152 val =
1153 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1154 sstr.GetData(), long_options, &long_options_index);
1155
1156 if (val == -1)
1157 break;
1158
1159 if (val == '?') {
1160 result.AppendError("unknown or ambiguous option");
1161 result.SetStatus(eReturnStatusFailed);
1162 break;
1163 }
1164
1165 if (val == 0)
1166 continue;
1167
1168 options.OptionSeen(val);
1169
1170 // Look up the long option index
1171 if (long_options_index == -1) {
1172 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1173 long_options[j].val;
1174 ++j) {
1175 if (long_options[j].val == val) {
1176 long_options_index = j;
1177 break;
1178 }
1179 }
1180 }
1181
1182 // See if the option takes an argument, and see if one was supplied.
1183 if (long_options_index >= 0) {
1184 StreamString option_str;
1185 option_str.Printf("-%c", val);
1186 const OptionDefinition *def = long_options[long_options_index].definition;
1187 int has_arg =
1188 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1189
1190 switch (has_arg) {
1191 case OptionParser::eNoArgument:
1192 option_arg_vector->push_back(OptionArgPair(
1193 std::string(option_str.GetData()),
1194 OptionArgValue(OptionParser::eNoArgument, "<no-argument>")));
1195 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1196 break;
1197 case OptionParser::eRequiredArgument:
1198 if (OptionParser::GetOptionArgument() != nullptr) {
1199 option_arg_vector->push_back(OptionArgPair(
1200 std::string(option_str.GetData()),
1201 OptionArgValue(OptionParser::eRequiredArgument,
1202 std::string(OptionParser::GetOptionArgument()))));
1203 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1204 } else {
1205 result.AppendErrorWithFormat(
1206 "Option '%s' is missing argument specifier.\n",
1207 option_str.GetData());
1208 result.SetStatus(eReturnStatusFailed);
1209 }
1210 break;
1211 case OptionParser::eOptionalArgument:
1212 if (OptionParser::GetOptionArgument() != nullptr) {
1213 option_arg_vector->push_back(OptionArgPair(
1214 std::string(option_str.GetData()),
1215 OptionArgValue(OptionParser::eOptionalArgument,
1216 std::string(OptionParser::GetOptionArgument()))));
1217 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1218 } else {
1219 option_arg_vector->push_back(
1220 OptionArgPair(std::string(option_str.GetData()),
1221 OptionArgValue(OptionParser::eOptionalArgument,
1222 "<no-argument>")));
1223 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1224 }
1225 break;
1226 default:
1227 result.AppendErrorWithFormat("error with options table; invalid value "
1228 "in has_arg field for option '%c'.\n",
1229 val);
1230 result.SetStatus(eReturnStatusFailed);
1231 break;
1232 }
1233 } else {
1234 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1235 result.SetStatus(eReturnStatusFailed);
1236 }
1237
1238 if (long_options_index >= 0) {
1239 // Find option in the argument list; also see if it was supposed to take
1240 // an argument and if one was
1241 // supplied. Remove option (and argument, if given) from the argument
1242 // list. Also remove them from
1243 // the raw_input_string, if one was passed in.
1244 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
1245 if (idx < GetArgumentCount()) {
1246 if (raw_input_string.size() > 0) {
1247 const char *tmp_arg = GetArgumentAtIndex(idx);
1248 size_t pos = raw_input_string.find(tmp_arg);
1249 if (pos != std::string::npos)
1250 raw_input_string.erase(pos, strlen(tmp_arg));
1251 }
1252 ReplaceArgumentAtIndex(idx, "");
1253 if ((long_options[long_options_index].definition->option_has_arg !=
1254 OptionParser::eNoArgument) &&
1255 (OptionParser::GetOptionArgument() != nullptr) &&
1256 (idx + 1 < GetArgumentCount()) &&
1257 (strcmp(OptionParser::GetOptionArgument(),
1258 GetArgumentAtIndex(idx + 1)) == 0)) {
1259 if (raw_input_string.size() > 0) {
1260 const char *tmp_arg = GetArgumentAtIndex(idx + 1);
1261 size_t pos = raw_input_string.find(tmp_arg);
1262 if (pos != std::string::npos)
1263 raw_input_string.erase(pos, strlen(tmp_arg));
1264 }
1265 ReplaceArgumentAtIndex(idx + 1, "");
1266 }
1267 }
1268 }
1269
1270 if (!result.Succeeded())
1271 break;
1272 }
1273}
1274
1275void Args::ParseArgsForCompletion(Options &options,
1276 OptionElementVector &option_element_vector,
1277 uint32_t cursor_index) {
1278 StreamString sstr;
1279 Option *long_options = options.GetLongOptions();
1280 option_element_vector.clear();
1281
1282 if (long_options == nullptr) {
1283 return;
1284 }
1285
1286 // Leading : tells getopt to return a : for a missing option argument AND
1287 // to suppress error messages.
1288
1289 sstr << ":";
1290 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1291 if (long_options[i].flag == nullptr) {
1292 sstr << (char)long_options[i].val;
1293 switch (long_options[i].definition->option_has_arg) {
1294 default:
1295 case OptionParser::eNoArgument:
1296 break;
1297 case OptionParser::eRequiredArgument:
1298 sstr << ":";
1299 break;
1300 case OptionParser::eOptionalArgument:
1301 sstr << "::";
1302 break;
1303 }
1304 }
1305 }
1306
1307 std::unique_lock<std::mutex> lock;
1308 OptionParser::Prepare(lock);
1309 OptionParser::EnableError(false);
1310
1311 int val;
1312 const OptionDefinition *opt_defs = options.GetDefinitions();
1313
1314 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
1315 // options to the front.
1316 // So we have to build another Arg and pass that to OptionParser::Parse so it
1317 // doesn't
1318 // change the one we have.
1319
1320 std::vector<const char *> dummy_vec(
1321 GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
1322
1323 bool failed_once = false;
1324 uint32_t dash_dash_pos = -1;
1325
1326 while (1) {
1327 bool missing_argument = false;
1328 int long_options_index = -1;
1329
1330 val = OptionParser::Parse(
1331 dummy_vec.size() - 1, const_cast<char *const *>(&dummy_vec.front()),
1332 sstr.GetData(), long_options, &long_options_index);
1333
1334 if (val == -1) {
1335 // When we're completing a "--" which is the last option on line,
1336 if (failed_once)
1337 break;
1338
1339 failed_once = true;
1340
1341 // If this is a bare "--" we mark it as such so we can complete it
1342 // successfully later.
1343 // Handling the "--" is a little tricky, since that may mean end of
1344 // options or arguments, or the
1345 // user might want to complete options by long name. I make this work by
1346 // checking whether the
1347 // cursor is in the "--" argument, and if so I assume we're completing the
1348 // long option, otherwise
1349 // I let it pass to OptionParser::Parse which will terminate the option
1350 // parsing.
1351 // Note, in either case we continue parsing the line so we can figure out
1352 // what other options
1353 // were passed. This will be useful when we come to restricting
1354 // completions based on what other
1355 // options we've seen on the line.
1356
1357 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1358 dummy_vec.size() - 1 &&
1359 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1360 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1361 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1362 cursor_index) {
1363 option_element_vector.push_back(
1364 OptionArgElement(OptionArgElement::eBareDoubleDash,
1365 OptionParser::GetOptionIndex() - 1,
1366 OptionArgElement::eBareDoubleDash));
1367 continue;
1368 } else
1369 break;
1370 } else
1371 break;
1372 } else if (val == '?') {
1373 option_element_vector.push_back(
1374 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1375 OptionParser::GetOptionIndex() - 1,
1376 OptionArgElement::eUnrecognizedArg));
1377 continue;
1378 } else if (val == 0) {
1379 continue;
1380 } else if (val == ':') {
1381 // This is a missing argument.
1382 val = OptionParser::GetOptionErrorCause();
1383 missing_argument = true;
1384 }
1385
1386 ((Options *)&options)->OptionSeen(val);
1387
1388 // Look up the long option index
1389 if (long_options_index == -1) {
1390 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1391 long_options[j].val;
1392 ++j) {
1393 if (long_options[j].val == val) {
1394 long_options_index = j;
1395 break;
1396 }
1397 }
1398 }
1399
1400 // See if the option takes an argument, and see if one was supplied.
1401 if (long_options_index >= 0) {
1402 int opt_defs_index = -1;
1403 for (int i = 0;; i++) {
1404 if (opt_defs[i].short_option == 0)
1405 break;
1406 else if (opt_defs[i].short_option == val) {
1407 opt_defs_index = i;
1408 break;
1409 }
1410 }
1411
1412 const OptionDefinition *def = long_options[long_options_index].definition;
1413 int has_arg =
1414 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1415 switch (has_arg) {
1416 case OptionParser::eNoArgument:
1417 option_element_vector.push_back(OptionArgElement(
1418 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1419 break;
1420 case OptionParser::eRequiredArgument:
1421 if (OptionParser::GetOptionArgument() != nullptr) {
1422 int arg_index;
1423 if (missing_argument)
1424 arg_index = -1;
1425 else
1426 arg_index = OptionParser::GetOptionIndex() - 1;
1427
1428 option_element_vector.push_back(OptionArgElement(
1429 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1430 } else {
1431 option_element_vector.push_back(OptionArgElement(
1432 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1433 }
1434 break;
1435 case OptionParser::eOptionalArgument:
1436 if (OptionParser::GetOptionArgument() != nullptr) {
1437 option_element_vector.push_back(OptionArgElement(
1438 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1439 OptionParser::GetOptionIndex() - 1));
1440 } else {
1441 option_element_vector.push_back(OptionArgElement(
1442 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1443 OptionParser::GetOptionIndex() - 1));
1444 }
1445 break;
1446 default:
1447 // The options table is messed up. Here we'll just continue
1448 option_element_vector.push_back(
1449 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1450 OptionParser::GetOptionIndex() - 1,
1451 OptionArgElement::eUnrecognizedArg));
1452 break;
1453 }
1454 } else {
1455 option_element_vector.push_back(
1456 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1457 OptionParser::GetOptionIndex() - 1,
1458 OptionArgElement::eUnrecognizedArg));
1459 }
1460 }
1461
1462 // Finally we have to handle the case where the cursor index points at a
1463 // single "-". We want to mark that in
1464 // the option_element_vector, but only if it is not after the "--". But it
1465 // turns out that OptionParser::Parse just ignores
1466 // an isolated "-". So we have to look it up by hand here. We only care if
1467 // it is AT the cursor position.
1468 // Note, a single quoted dash is not the same as a single dash...
1469
1470 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1471 cursor_index < dash_dash_pos) &&
1472 m_args_quote_char[cursor_index] == '\0' &&
1473 strcmp(GetArgumentAtIndex(cursor_index), "-") == 0) {
1474 option_element_vector.push_back(
1475 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1476 OptionArgElement::eBareDash));
1477 }
1478}
1479
1480void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1481 dst.clear();
1482 if (src) {
1483 for (const char *p = src; *p != '\0'; ++p) {
1484 size_t non_special_chars = ::strcspn(p, "\\");
1485 if (non_special_chars > 0) {
1486 dst.append(p, non_special_chars);
1487 p += non_special_chars;
1488 if (*p == '\0')
1489 break;
1490 }
1491
1492 if (*p == '\\') {
1493 ++p; // skip the slash
1494 switch (*p) {
1495 case 'a':
1496 dst.append(1, '\a');
1497 break;
1498 case 'b':
1499 dst.append(1, '\b');
1500 break;
1501 case 'f':
1502 dst.append(1, '\f');
1503 break;
1504 case 'n':
1505 dst.append(1, '\n');
1506 break;
1507 case 'r':
1508 dst.append(1, '\r');
1509 break;
1510 case 't':
1511 dst.append(1, '\t');
1512 break;
1513 case 'v':
1514 dst.append(1, '\v');
1515 break;
1516 case '\\':
1517 dst.append(1, '\\');
1518 break;
1519 case '\'':
1520 dst.append(1, '\'');
1521 break;
1522 case '"':
1523 dst.append(1, '"');
1524 break;
1525 case '0':
1526 // 1 to 3 octal chars
1527 {
1528 // Make a string that can hold onto the initial zero char,
1529 // up to 3 octal digits, and a terminating NULL.
1530 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1531
1532 int i;
1533 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1534 oct_str[i] = p[i];
1535
1536 // We don't want to consume the last octal character since
1537 // the main for loop will do this for us, so we advance p by
1538 // one less than i (even if i is zero)
1539 p += i - 1;
1540 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1541 if (octal_value <= UINT8_MAX) {
1542 dst.append(1, (char)octal_value);
1543 }
1544 }
1545 break;
1546
1547 case 'x':
1548 // hex number in the format
1549 if (isxdigit(p[1])) {
1550 ++p; // Skip the 'x'
1551
1552 // Make a string that can hold onto two hex chars plus a
1553 // NULL terminator
1554 char hex_str[3] = {*p, '\0', '\0'};
1555 if (isxdigit(p[1])) {
1556 ++p; // Skip the first of the two hex chars
1557 hex_str[1] = *p;
1558 }
1559
1560 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1561 if (hex_value <= UINT8_MAX)
1562 dst.append(1, (char)hex_value);
1563 } else {
1564 dst.append(1, 'x');
1565 }
1566 break;
1567
1568 default:
1569 // Just desensitize any other character by just printing what
1570 // came after the '\'
1571 dst.append(1, *p);
1572 break;
1573 }
1574 }
1575 }
1576 }
1577}
1578
1579void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1580 dst.clear();
1581 if (src) {
1582 for (const char *p = src; *p != '\0'; ++p) {
1583 if (isprint8(*p))
1584 dst.append(1, *p);
1585 else {
1586 switch (*p) {
1587 case '\a':
1588 dst.append("\\a");
1589 break;
1590 case '\b':
1591 dst.append("\\b");
1592 break;
1593 case '\f':
1594 dst.append("\\f");
1595 break;
1596 case '\n':
1597 dst.append("\\n");
1598 break;
1599 case '\r':
1600 dst.append("\\r");
1601 break;
1602 case '\t':
1603 dst.append("\\t");
1604 break;
1605 case '\v':
1606 dst.append("\\v");
1607 break;
1608 case '\'':
1609 dst.append("\\'");
1610 break;
1611 case '"':
1612 dst.append("\\\"");
1613 break;
1614 case '\\':
1615 dst.append("\\\\");
1616 break;
1617 default: {
1618 // Just encode as octal
1619 dst.append("\\0");
1620 char octal_str[32];
1621 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1622 dst.append(octal_str);
1623 } break;
1624 }
1625 }
1626 }
1627 }
1628}
1629
1630std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1631 char quote_char) {
1632 const char *chars_to_escape = nullptr;
1633 switch (quote_char) {
1634 case '\0':
1635 chars_to_escape = " \t\\'\"`";
1636 break;
1637 case '\'':
1638 chars_to_escape = "";
1639 break;
1640 case '"':
1641 chars_to_escape = "$\"`\\";
1642 break;
1643 default:
1644 assert(false && "Unhandled quote character");
1645 }
1646
1647 std::string res;
1648 res.reserve(arg.size());
1649 for (char c : arg) {
1650 if (::strchr(chars_to_escape, c))
1651 res.push_back('\\');
1652 res.push_back(c);
1653 }
1654 return res;
1655}