blob: 52fb9572399cf4135a9819c359bf43b9f44cae55 [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
Zachary Turner5c725f32016-09-19 21:56:59 +0000355llvm::StringRef Args::Unshift(llvm::StringRef arg_str, char quote_char) {
356 m_args.push_front(arg_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 m_argv.insert(m_argv.begin(), m_args.front().c_str());
358 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
Zachary Turner5c725f32016-09-19 21:56:59 +0000359 return llvm::StringRef::withNullAsEmpty(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)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000365 AppendArgument(llvm::StringRef(rhs.GetArgumentAtIndex(i)),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 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)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000372 AppendArgument(llvm::StringRef::withNullAsEmpty(argv[i]));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374}
375
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000376llvm::StringRef Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
377 return InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
Greg Clayton982c9762011-11-03 21:22:33 +0000378}
379
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000380llvm::StringRef Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
381 char quote_char) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 // 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
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000390 pos = m_args.insert(pos, arg_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391
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
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000402llvm::StringRef Args::ReplaceArgumentAtIndex(size_t idx,
403 llvm::StringRef arg_str,
404 char quote_char) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 // Since we are using a std::list to hold onto the copied C string and
406 // we don't have direct access to the elements, we have to iterate to
407 // find the value.
408 arg_sstr_collection::iterator pos, end = m_args.end();
409 size_t i = idx;
410 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
411 --i;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 if (pos != end) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000414 pos->assign(arg_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 assert(idx < m_argv.size() - 1);
416 m_argv[idx] = pos->c_str();
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000417 if (idx >= m_args_quote_char.size())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 m_args_quote_char.resize(idx + 1);
419 m_args_quote_char[idx] = quote_char;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420 return GetArgumentAtIndex(idx);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 }
Zachary Turner40377802016-09-21 22:33:30 +0000422 return llvm::StringRef();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423}
424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425void Args::DeleteArgumentAtIndex(size_t idx) {
426 // Since we are using a std::list to hold onto the copied C string and
427 // we don't have direct access to the elements, we have to iterate to
428 // find the value.
429 arg_sstr_collection::iterator pos, end = m_args.end();
430 size_t i = idx;
431 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
432 --i;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 if (pos != end) {
435 m_args.erase(pos);
436 assert(idx < m_argv.size() - 1);
437 m_argv.erase(m_argv.begin() + idx);
438 if (idx < m_args_quote_char.size())
439 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
440 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000441}
442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443void Args::SetArguments(size_t argc, const char **argv) {
444 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
445 // no need to clear it here.
446 m_args.clear();
447 m_args_quote_char.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448
Kate Stoneb9c1b512016-09-06 20:57:50 +0000449 // First copy each string
450 for (size_t i = 0; i < argc; ++i) {
451 m_args.push_back(argv[i]);
452 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
453 m_args_quote_char.push_back(argv[i][0]);
454 else
455 m_args_quote_char.push_back('\0');
456 }
457
458 UpdateArgvFromArgs();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459}
460
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461void Args::SetArguments(const char **argv) {
462 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
463 // no need to clear it here.
464 m_args.clear();
465 m_args_quote_char.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 if (argv) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000468 // First copy each string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 for (size_t i = 0; argv[i]; ++i) {
470 m_args.push_back(argv[i]);
471 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
472 m_args_quote_char.push_back(argv[i][0]);
473 else
474 m_args_quote_char.push_back('\0');
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000475 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 UpdateArgvFromArgs();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000479}
480
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481Error Args::ParseOptions(Options &options, ExecutionContext *execution_context,
482 PlatformSP platform_sp, bool require_validation) {
483 StreamString sstr;
484 Error error;
485 Option *long_options = options.GetLongOptions();
486 if (long_options == nullptr) {
487 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 for (int i = 0; long_options[i].definition != nullptr; ++i) {
492 if (long_options[i].flag == nullptr) {
493 if (isprint8(long_options[i].val)) {
494 sstr << (char)long_options[i].val;
495 switch (long_options[i].definition->option_has_arg) {
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000496 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 case OptionParser::eNoArgument:
498 break;
499 case OptionParser::eRequiredArgument:
500 sstr << ':';
501 break;
502 case OptionParser::eOptionalArgument:
503 sstr << "::";
504 break;
505 }
506 }
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000507 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 }
509 std::unique_lock<std::mutex> lock;
510 OptionParser::Prepare(lock);
511 int val;
512 while (1) {
513 int long_options_index = -1;
514 val =
515 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
516 sstr.GetData(), long_options, &long_options_index);
517 if (val == -1)
518 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 // Did we get an error?
521 if (val == '?') {
522 error.SetErrorStringWithFormat("unknown or ambiguous option");
523 break;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000524 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 // The option auto-set itself
526 if (val == 0)
527 continue;
528
529 ((Options *)&options)->OptionSeen(val);
530
531 // Lookup the long option index
532 if (long_options_index == -1) {
533 for (int i = 0; long_options[i].definition || long_options[i].flag ||
534 long_options[i].val;
535 ++i) {
536 if (long_options[i].val == val) {
537 long_options_index = i;
538 break;
539 }
540 }
541 }
542 // Call the callback with the option
543 if (long_options_index >= 0 &&
544 long_options[long_options_index].definition) {
545 const OptionDefinition *def = long_options[long_options_index].definition;
546
547 if (!platform_sp) {
548 // User did not pass in an explicit platform. Try to grab
549 // from the execution context.
550 TargetSP target_sp =
551 execution_context ? execution_context->GetTargetSP() : TargetSP();
552 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
553 }
554 OptionValidator *validator = def->validator;
555
556 if (!platform_sp && require_validation) {
557 // Caller requires validation but we cannot validate as we
558 // don't have the mandatory platform against which to
559 // validate.
560 error.SetErrorString("cannot validate options: "
561 "no platform available");
562 return error;
563 }
564
565 bool validation_failed = false;
566 if (platform_sp) {
567 // Ensure we have an execution context, empty or not.
568 ExecutionContext dummy_context;
569 ExecutionContext *exe_ctx_p =
570 execution_context ? execution_context : &dummy_context;
571 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
572 validation_failed = true;
573 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
574 def->long_option,
575 def->validator->LongConditionString());
576 }
577 }
578
579 // As long as validation didn't fail, we set the option value.
580 if (!validation_failed)
581 error = options.SetOptionValue(
582 long_options_index,
583 (def->option_has_arg == OptionParser::eNoArgument)
584 ? nullptr
585 : OptionParser::GetOptionArgument(),
586 execution_context);
587 } else {
588 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
589 }
590 if (error.Fail())
591 break;
592 }
593
594 // Update our ARGV now that get options has consumed all the options
595 m_argv.erase(m_argv.begin(), m_argv.begin() + OptionParser::GetOptionIndex());
596 UpdateArgsAfterOptionParsing();
597 return error;
Tamas Berghammer89d3f092015-09-02 10:35:27 +0000598}
599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600void Args::Clear() {
601 m_args.clear();
602 m_argv.clear();
603 m_args_quote_char.clear();
604}
605
606lldb::addr_t Args::StringToAddress(const ExecutionContext *exe_ctx,
607 const char *s, lldb::addr_t fail_value,
608 Error *error_ptr) {
609 bool error_set = false;
610 if (s && s[0]) {
Zachary Turner95eae422016-09-21 16:01:28 +0000611 llvm::StringRef sref = s;
612
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 char *end = nullptr;
614 lldb::addr_t addr = ::strtoull(s, &end, 0);
615 if (*end == '\0') {
616 if (error_ptr)
617 error_ptr->Clear();
618 return addr; // All characters were used, return the result
619 }
620 // Try base 16 with no prefix...
621 addr = ::strtoull(s, &end, 16);
622 if (*end == '\0') {
623 if (error_ptr)
624 error_ptr->Clear();
625 return addr; // All characters were used, return the result
626 }
627
628 if (exe_ctx) {
629 Target *target = exe_ctx->GetTargetPtr();
630 if (target) {
631 lldb::ValueObjectSP valobj_sp;
632 EvaluateExpressionOptions options;
633 options.SetCoerceToId(false);
634 options.SetUnwindOnError(true);
635 options.SetKeepInMemory(false);
636 options.SetTryAllThreads(true);
637
638 ExpressionResults expr_result = target->EvaluateExpression(
639 s, exe_ctx->GetFramePtr(), valobj_sp, options);
640
641 bool success = false;
642 if (expr_result == eExpressionCompleted) {
643 if (valobj_sp)
644 valobj_sp = valobj_sp->GetQualifiedRepresentationIfAvailable(
645 valobj_sp->GetDynamicValueType(), true);
646 // Get the address to watch.
647 if (valobj_sp)
648 addr = valobj_sp->GetValueAsUnsigned(fail_value, &success);
649 if (success) {
650 if (error_ptr)
651 error_ptr->Clear();
652 return addr;
653 } else {
654 if (error_ptr) {
655 error_set = true;
656 error_ptr->SetErrorStringWithFormat(
657 "address expression \"%s\" resulted in a value whose type "
658 "can't be converted to an address: %s",
659 s, valobj_sp->GetTypeName().GetCString());
660 }
661 }
662
663 } else {
664 // Since the compiler can't handle things like "main + 12" we should
665 // try to do this for now. The compiler doesn't like adding offsets
666 // to function pointer types.
Zachary Turner95eae422016-09-21 16:01:28 +0000667 static RegularExpression g_symbol_plus_offset_regex(llvm::StringRef(
668 "^(.*)([-\\+])[[:space:]]*(0x[0-9A-Fa-f]+|[0-9]+)[[:space:]]*$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 RegularExpression::Match regex_match(3);
Zachary Turner95eae422016-09-21 16:01:28 +0000670 if (g_symbol_plus_offset_regex.Execute(sref, &regex_match)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 uint64_t offset = 0;
672 bool add = true;
673 std::string name;
674 std::string str;
675 if (regex_match.GetMatchAtIndex(s, 1, name)) {
676 if (regex_match.GetMatchAtIndex(s, 2, str)) {
677 add = str[0] == '+';
678
679 if (regex_match.GetMatchAtIndex(s, 3, str)) {
680 offset = StringConvert::ToUInt64(str.c_str(), 0, 0, &success);
681
682 if (success) {
683 Error error;
684 addr = StringToAddress(exe_ctx, name.c_str(),
685 LLDB_INVALID_ADDRESS, &error);
686 if (addr != LLDB_INVALID_ADDRESS) {
687 if (add)
688 return addr + offset;
689 else
690 return addr - offset;
691 }
692 }
693 }
694 }
695 }
696 }
697
698 if (error_ptr) {
699 error_set = true;
700 error_ptr->SetErrorStringWithFormat(
701 "address expression \"%s\" evaluation failed", s);
702 }
703 }
704 }
705 }
706 }
707 if (error_ptr) {
708 if (!error_set)
709 error_ptr->SetErrorStringWithFormat("invalid address expression \"%s\"",
710 s);
711 }
712 return fail_value;
713}
714
715const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
716 bool return_null_if_empty) {
717 static const char *k_white_space = " \t\v";
718 if (!s.empty()) {
719 if (leading) {
720 size_t pos = s.find_first_not_of(k_white_space);
721 if (pos == std::string::npos)
722 s.clear();
723 else if (pos > 0)
724 s.erase(0, pos);
725 }
726
727 if (trailing) {
728 size_t rpos = s.find_last_not_of(k_white_space);
729 if (rpos != std::string::npos && rpos + 1 < s.size())
730 s.erase(rpos + 1);
731 }
732 }
733 if (return_null_if_empty && s.empty())
734 return nullptr;
735 return s.c_str();
736}
737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738bool Args::StringToBoolean(llvm::StringRef ref, bool fail_value,
739 bool *success_ptr) {
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000740 if (success_ptr)
741 *success_ptr = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 ref = ref.trim();
743 if (ref.equals_lower("false") || ref.equals_lower("off") ||
744 ref.equals_lower("no") || ref.equals_lower("0")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 return false;
746 } else if (ref.equals_lower("true") || ref.equals_lower("on") ||
747 ref.equals_lower("yes") || ref.equals_lower("1")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748 return true;
749 }
750 if (success_ptr)
751 *success_ptr = false;
752 return fail_value;
753}
754
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000755char Args::StringToChar(llvm::StringRef s, char fail_value, bool *success_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 if (success_ptr)
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000757 *success_ptr = false;
758 if (s.size() != 1)
759 return fail_value;
760
761 if (success_ptr)
762 *success_ptr = true;
763 return s[0];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764}
765
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000766bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
767 uint32_t &minor, uint32_t &update) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 major = UINT32_MAX;
769 minor = UINT32_MAX;
770 update = UINT32_MAX;
771
Zachary Turner6fa7681b2016-09-17 02:00:02 +0000772 if (string.empty())
773 return false;
774
775 llvm::StringRef major_str, minor_str, update_str;
776
777 std::tie(major_str, minor_str) = string.split('.');
778 std::tie(minor_str, update_str) = minor_str.split('.');
779 if (major_str.getAsInteger(10, major))
780 return false;
781 if (!minor_str.empty() && minor_str.getAsInteger(10, minor))
782 return false;
783 if (!update_str.empty() && update_str.getAsInteger(10, update))
784 return false;
785
786 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787}
788
789const char *Args::GetShellSafeArgument(const FileSpec &shell,
790 const char *unsafe_arg,
791 std::string &safe_arg) {
792 struct ShellDescriptor {
793 ConstString m_basename;
794 const char *m_escapables;
795 };
796
797 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
798 {ConstString("tcsh"), " '\"<>()&$"},
799 {ConstString("sh"), " '\"<>()&"}};
800
801 // safe minimal set
802 const char *escapables = " '\"";
803
804 if (auto basename = shell.GetFilename()) {
805 for (const auto &Shell : g_Shells) {
806 if (Shell.m_basename == basename) {
807 escapables = Shell.m_escapables;
808 break;
809 }
810 }
811 }
812
813 safe_arg.assign(unsafe_arg);
814 size_t prev_pos = 0;
815 while (prev_pos < safe_arg.size()) {
816 // Escape spaces and quotes
817 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
818 if (pos != std::string::npos) {
819 safe_arg.insert(pos, 1, '\\');
820 prev_pos = pos + 2;
821 } else
822 break;
823 }
824 return safe_arg.c_str();
825}
826
Zachary Turner8cef4b02016-09-23 17:48:13 +0000827int64_t Args::StringToOptionEnum(llvm::StringRef s,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 OptionEnumValueElement *enum_values,
829 int32_t fail_value, Error &error) {
Zachary Turner8cef4b02016-09-23 17:48:13 +0000830 error.Clear();
831 if (!enum_values) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 error.SetErrorString("invalid enumeration argument");
Zachary Turner8cef4b02016-09-23 17:48:13 +0000833 return fail_value;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 }
Zachary Turner8cef4b02016-09-23 17:48:13 +0000835
836 if (s.empty()) {
837 error.SetErrorString("empty enumeration string");
838 return fail_value;
839 }
840
841 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
842 llvm::StringRef this_enum(enum_values[i].string_value);
843 if (this_enum.startswith(s))
844 return enum_values[i].value;
845 }
846
847 StreamString strm;
848 strm.PutCString("invalid enumeration value, valid values are: ");
849 for (int i = 0; enum_values[i].string_value != nullptr; i++) {
850 strm.Printf("%s\"%s\"", i > 0 ? ", " : "", enum_values[i].string_value);
851 }
852 error.SetErrorString(strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 return fail_value;
854}
855
Zachary Turner7b2e5a32016-09-16 19:09:12 +0000856lldb::ScriptLanguage
857Args::StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
858 bool *success_ptr) {
859 if (success_ptr)
860 *success_ptr = true;
861
862 if (s.equals_lower("python"))
863 return eScriptLanguagePython;
864 if (s.equals_lower("default"))
865 return eScriptLanguageDefault;
866 if (s.equals_lower("none"))
867 return eScriptLanguageNone;
868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 if (success_ptr)
870 *success_ptr = false;
871 return fail_value;
872}
873
874Error Args::StringToFormat(const char *s, lldb::Format &format,
875 size_t *byte_size_ptr) {
876 format = eFormatInvalid;
877 Error error;
878
879 if (s && s[0]) {
880 if (byte_size_ptr) {
881 if (isdigit(s[0])) {
882 char *format_char = nullptr;
883 unsigned long byte_size = ::strtoul(s, &format_char, 0);
884 if (byte_size != ULONG_MAX)
885 *byte_size_ptr = byte_size;
886 s = format_char;
887 } else
888 *byte_size_ptr = 0;
889 }
890
891 const bool partial_match_ok = true;
892 if (!FormatManager::GetFormatFromCString(s, partial_match_ok, format)) {
893 StreamString error_strm;
894 error_strm.Printf(
895 "Invalid format character or name '%s'. Valid values are:\n", s);
896 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
897 char format_char = FormatManager::GetFormatAsFormatChar(f);
898 if (format_char)
899 error_strm.Printf("'%c' or ", format_char);
900
901 error_strm.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
902 error_strm.EOL();
903 }
904
905 if (byte_size_ptr)
906 error_strm.PutCString(
907 "An optional byte size can precede the format character.\n");
908 error.SetErrorString(error_strm.GetString().c_str());
909 }
910
911 if (error.Fail())
912 return error;
913 } else {
914 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
915 }
916 return error;
917}
918
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
920 lldb::Encoding fail_value) {
921 return llvm::StringSwitch<lldb::Encoding>(s)
922 .Case("uint", eEncodingUint)
923 .Case("sint", eEncodingSint)
924 .Case("ieee754", eEncodingIEEE754)
925 .Case("vector", eEncodingVector)
926 .Default(fail_value);
927}
928
Kate Stoneb9c1b512016-09-06 20:57:50 +0000929uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
930 if (s.empty())
931 return LLDB_INVALID_REGNUM;
932 uint32_t result = llvm::StringSwitch<uint32_t>(s)
933 .Case("pc", LLDB_REGNUM_GENERIC_PC)
934 .Case("sp", LLDB_REGNUM_GENERIC_SP)
935 .Case("fp", LLDB_REGNUM_GENERIC_FP)
936 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
937 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
938 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
939 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
940 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
941 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
942 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
943 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
944 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
945 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
946 .Default(LLDB_INVALID_REGNUM);
947 return result;
948}
949
950void Args::LongestCommonPrefix(std::string &common_prefix) {
951 arg_sstr_collection::iterator pos, end = m_args.end();
952 pos = m_args.begin();
953 if (pos == end)
954 common_prefix.clear();
955 else
956 common_prefix = (*pos);
957
958 for (++pos; pos != end; ++pos) {
959 size_t new_size = (*pos).size();
960
961 // First trim common_prefix if it is longer than the current element:
962 if (common_prefix.size() > new_size)
963 common_prefix.erase(new_size);
964
965 // Then trim it at the first disparity:
966
967 for (size_t i = 0; i < common_prefix.size(); i++) {
968 if ((*pos)[i] != common_prefix[i]) {
969 common_prefix.erase(i);
970 break;
971 }
972 }
973
974 // If we've emptied the common prefix, we're done.
975 if (common_prefix.empty())
976 break;
977 }
978}
979
Zachary Turner5c725f32016-09-19 21:56:59 +0000980void Args::AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
981 llvm::StringRef new_value) {
Todd Fiala36bf6a42016-09-22 16:00:01 +0000982 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 return;
984
985 // Build the new entry.
Zachary Turner5c725f32016-09-19 21:56:59 +0000986 std::string var_string(env_var_name);
Todd Fiala36bf6a42016-09-22 16:00:01 +0000987 if (!new_value.empty()) {
988 var_string += "=";
989 var_string += new_value;
990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991
Zachary Turner5c725f32016-09-19 21:56:59 +0000992 size_t index = 0;
993 if (ContainsEnvironmentVariable(env_var_name, &index)) {
994 ReplaceArgumentAtIndex(index, var_string);
995 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 }
997
998 // We didn't find it. Append it instead.
Zachary Turner5c725f32016-09-19 21:56:59 +0000999 AppendArgument(var_string);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000}
1001
Zachary Turner5c725f32016-09-19 21:56:59 +00001002bool Args::ContainsEnvironmentVariable(llvm::StringRef env_var_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 size_t *argument_index) const {
1004 // Validate args.
Zachary Turner5c725f32016-09-19 21:56:59 +00001005 if (env_var_name.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 return false;
1007
1008 // Check each arg to see if it matches the env var name.
1009 for (size_t i = 0; i < GetArgumentCount(); ++i) {
Todd Fiala150aa322016-09-22 00:59:23 +00001010 auto arg_value = llvm::StringRef::withNullAsEmpty(GetArgumentAtIndex(i));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011
Zachary Turner5c725f32016-09-19 21:56:59 +00001012 llvm::StringRef name, value;
1013 std::tie(name, value) = arg_value.split('=');
Todd Fiala36bf6a42016-09-22 16:00:01 +00001014 if (name == env_var_name) {
Zachary Turner5c725f32016-09-19 21:56:59 +00001015 if (argument_index)
1016 *argument_index = i;
1017 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 }
1019 }
1020
1021 // We didn't find a match.
1022 return false;
1023}
1024
1025size_t Args::FindArgumentIndexForOption(Option *long_options,
1026 int long_options_index) {
1027 char short_buffer[3];
1028 char long_buffer[255];
1029 ::snprintf(short_buffer, sizeof(short_buffer), "-%c",
1030 long_options[long_options_index].val);
1031 ::snprintf(long_buffer, sizeof(long_buffer), "--%s",
1032 long_options[long_options_index].definition->long_option);
1033 size_t end = GetArgumentCount();
1034 size_t idx = 0;
1035 while (idx < end) {
1036 if ((::strncmp(GetArgumentAtIndex(idx), short_buffer,
1037 strlen(short_buffer)) == 0) ||
1038 (::strncmp(GetArgumentAtIndex(idx), long_buffer, strlen(long_buffer)) ==
1039 0)) {
1040 return idx;
1041 }
1042 ++idx;
1043 }
1044
1045 return end;
1046}
1047
1048bool Args::IsPositionalArgument(const char *arg) {
1049 if (arg == nullptr)
1050 return false;
1051
1052 bool is_positional = true;
1053 const char *cptr = arg;
1054
1055 if (cptr[0] == '%') {
1056 ++cptr;
1057 while (isdigit(cptr[0]))
1058 ++cptr;
1059 if (cptr[0] != '\0')
1060 is_positional = false;
1061 } else
1062 is_positional = false;
1063
1064 return is_positional;
1065}
1066
1067void Args::ParseAliasOptions(Options &options, CommandReturnObject &result,
1068 OptionArgVector *option_arg_vector,
1069 std::string &raw_input_string) {
1070 StreamString sstr;
1071 int i;
1072 Option *long_options = options.GetLongOptions();
1073
1074 if (long_options == nullptr) {
1075 result.AppendError("invalid long options");
1076 result.SetStatus(eReturnStatusFailed);
1077 return;
1078 }
1079
1080 for (i = 0; long_options[i].definition != nullptr; ++i) {
1081 if (long_options[i].flag == nullptr) {
1082 sstr << (char)long_options[i].val;
1083 switch (long_options[i].definition->option_has_arg) {
1084 default:
1085 case OptionParser::eNoArgument:
1086 break;
1087 case OptionParser::eRequiredArgument:
1088 sstr << ":";
1089 break;
1090 case OptionParser::eOptionalArgument:
1091 sstr << "::";
1092 break;
1093 }
1094 }
1095 }
1096
1097 std::unique_lock<std::mutex> lock;
1098 OptionParser::Prepare(lock);
1099 int val;
1100 while (1) {
1101 int long_options_index = -1;
1102 val =
1103 OptionParser::Parse(GetArgumentCount(), GetArgumentVector(),
1104 sstr.GetData(), long_options, &long_options_index);
1105
1106 if (val == -1)
1107 break;
1108
1109 if (val == '?') {
1110 result.AppendError("unknown or ambiguous option");
1111 result.SetStatus(eReturnStatusFailed);
1112 break;
1113 }
1114
1115 if (val == 0)
1116 continue;
1117
1118 options.OptionSeen(val);
1119
1120 // Look up the long option index
1121 if (long_options_index == -1) {
1122 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1123 long_options[j].val;
1124 ++j) {
1125 if (long_options[j].val == val) {
1126 long_options_index = j;
1127 break;
1128 }
1129 }
1130 }
1131
1132 // See if the option takes an argument, and see if one was supplied.
1133 if (long_options_index >= 0) {
1134 StreamString option_str;
1135 option_str.Printf("-%c", val);
1136 const OptionDefinition *def = long_options[long_options_index].definition;
1137 int has_arg =
1138 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1139
1140 switch (has_arg) {
1141 case OptionParser::eNoArgument:
1142 option_arg_vector->push_back(OptionArgPair(
1143 std::string(option_str.GetData()),
1144 OptionArgValue(OptionParser::eNoArgument, "<no-argument>")));
1145 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1146 break;
1147 case OptionParser::eRequiredArgument:
1148 if (OptionParser::GetOptionArgument() != nullptr) {
1149 option_arg_vector->push_back(OptionArgPair(
1150 std::string(option_str.GetData()),
1151 OptionArgValue(OptionParser::eRequiredArgument,
1152 std::string(OptionParser::GetOptionArgument()))));
1153 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1154 } else {
1155 result.AppendErrorWithFormat(
1156 "Option '%s' is missing argument specifier.\n",
1157 option_str.GetData());
1158 result.SetStatus(eReturnStatusFailed);
1159 }
1160 break;
1161 case OptionParser::eOptionalArgument:
1162 if (OptionParser::GetOptionArgument() != nullptr) {
1163 option_arg_vector->push_back(OptionArgPair(
1164 std::string(option_str.GetData()),
1165 OptionArgValue(OptionParser::eOptionalArgument,
1166 std::string(OptionParser::GetOptionArgument()))));
1167 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1168 } else {
1169 option_arg_vector->push_back(
1170 OptionArgPair(std::string(option_str.GetData()),
1171 OptionArgValue(OptionParser::eOptionalArgument,
1172 "<no-argument>")));
1173 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1174 }
1175 break;
1176 default:
1177 result.AppendErrorWithFormat("error with options table; invalid value "
1178 "in has_arg field for option '%c'.\n",
1179 val);
1180 result.SetStatus(eReturnStatusFailed);
1181 break;
1182 }
1183 } else {
1184 result.AppendErrorWithFormat("Invalid option with value '%c'.\n", val);
1185 result.SetStatus(eReturnStatusFailed);
1186 }
1187
1188 if (long_options_index >= 0) {
1189 // Find option in the argument list; also see if it was supposed to take
1190 // an argument and if one was
1191 // supplied. Remove option (and argument, if given) from the argument
1192 // list. Also remove them from
1193 // the raw_input_string, if one was passed in.
1194 size_t idx = FindArgumentIndexForOption(long_options, long_options_index);
1195 if (idx < GetArgumentCount()) {
1196 if (raw_input_string.size() > 0) {
1197 const char *tmp_arg = GetArgumentAtIndex(idx);
1198 size_t pos = raw_input_string.find(tmp_arg);
1199 if (pos != std::string::npos)
1200 raw_input_string.erase(pos, strlen(tmp_arg));
1201 }
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001202 ReplaceArgumentAtIndex(idx, llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 if ((long_options[long_options_index].definition->option_has_arg !=
1204 OptionParser::eNoArgument) &&
1205 (OptionParser::GetOptionArgument() != nullptr) &&
1206 (idx + 1 < GetArgumentCount()) &&
1207 (strcmp(OptionParser::GetOptionArgument(),
1208 GetArgumentAtIndex(idx + 1)) == 0)) {
1209 if (raw_input_string.size() > 0) {
1210 const char *tmp_arg = GetArgumentAtIndex(idx + 1);
1211 size_t pos = raw_input_string.find(tmp_arg);
1212 if (pos != std::string::npos)
1213 raw_input_string.erase(pos, strlen(tmp_arg));
1214 }
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001215 ReplaceArgumentAtIndex(idx + 1, llvm::StringRef());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 }
1217 }
1218 }
1219
1220 if (!result.Succeeded())
1221 break;
1222 }
1223}
1224
1225void Args::ParseArgsForCompletion(Options &options,
1226 OptionElementVector &option_element_vector,
1227 uint32_t cursor_index) {
1228 StreamString sstr;
1229 Option *long_options = options.GetLongOptions();
1230 option_element_vector.clear();
1231
1232 if (long_options == nullptr) {
1233 return;
1234 }
1235
1236 // Leading : tells getopt to return a : for a missing option argument AND
1237 // to suppress error messages.
1238
1239 sstr << ":";
1240 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1241 if (long_options[i].flag == nullptr) {
1242 sstr << (char)long_options[i].val;
1243 switch (long_options[i].definition->option_has_arg) {
1244 default:
1245 case OptionParser::eNoArgument:
1246 break;
1247 case OptionParser::eRequiredArgument:
1248 sstr << ":";
1249 break;
1250 case OptionParser::eOptionalArgument:
1251 sstr << "::";
1252 break;
1253 }
1254 }
1255 }
1256
1257 std::unique_lock<std::mutex> lock;
1258 OptionParser::Prepare(lock);
1259 OptionParser::EnableError(false);
1260
1261 int val;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001262 auto opt_defs = options.GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263
1264 // Fooey... OptionParser::Parse permutes the GetArgumentVector to move the
1265 // options to the front.
1266 // So we have to build another Arg and pass that to OptionParser::Parse so it
1267 // doesn't
1268 // change the one we have.
1269
1270 std::vector<const char *> dummy_vec(
1271 GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
1272
1273 bool failed_once = false;
1274 uint32_t dash_dash_pos = -1;
1275
1276 while (1) {
1277 bool missing_argument = false;
1278 int long_options_index = -1;
1279
1280 val = OptionParser::Parse(
1281 dummy_vec.size() - 1, const_cast<char *const *>(&dummy_vec.front()),
1282 sstr.GetData(), long_options, &long_options_index);
1283
1284 if (val == -1) {
1285 // When we're completing a "--" which is the last option on line,
1286 if (failed_once)
1287 break;
1288
1289 failed_once = true;
1290
1291 // If this is a bare "--" we mark it as such so we can complete it
1292 // successfully later.
1293 // Handling the "--" is a little tricky, since that may mean end of
1294 // options or arguments, or the
1295 // user might want to complete options by long name. I make this work by
1296 // checking whether the
1297 // cursor is in the "--" argument, and if so I assume we're completing the
1298 // long option, otherwise
1299 // I let it pass to OptionParser::Parse which will terminate the option
1300 // parsing.
1301 // Note, in either case we continue parsing the line so we can figure out
1302 // what other options
1303 // were passed. This will be useful when we come to restricting
1304 // completions based on what other
1305 // options we've seen on the line.
1306
1307 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1308 dummy_vec.size() - 1 &&
1309 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1310 dash_dash_pos = OptionParser::GetOptionIndex() - 1;
1311 if (static_cast<size_t>(OptionParser::GetOptionIndex() - 1) ==
1312 cursor_index) {
1313 option_element_vector.push_back(
1314 OptionArgElement(OptionArgElement::eBareDoubleDash,
1315 OptionParser::GetOptionIndex() - 1,
1316 OptionArgElement::eBareDoubleDash));
1317 continue;
1318 } else
1319 break;
1320 } else
1321 break;
1322 } else if (val == '?') {
1323 option_element_vector.push_back(
1324 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1325 OptionParser::GetOptionIndex() - 1,
1326 OptionArgElement::eUnrecognizedArg));
1327 continue;
1328 } else if (val == 0) {
1329 continue;
1330 } else if (val == ':') {
1331 // This is a missing argument.
1332 val = OptionParser::GetOptionErrorCause();
1333 missing_argument = true;
1334 }
1335
1336 ((Options *)&options)->OptionSeen(val);
1337
1338 // Look up the long option index
1339 if (long_options_index == -1) {
1340 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1341 long_options[j].val;
1342 ++j) {
1343 if (long_options[j].val == val) {
1344 long_options_index = j;
1345 break;
1346 }
1347 }
1348 }
1349
1350 // See if the option takes an argument, and see if one was supplied.
1351 if (long_options_index >= 0) {
1352 int opt_defs_index = -1;
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001353 for (size_t i = 0; i < opt_defs.size(); i++) {
1354 if (opt_defs[i].short_option != val)
1355 continue;
1356 opt_defs_index = i;
1357 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 }
1359
1360 const OptionDefinition *def = long_options[long_options_index].definition;
1361 int has_arg =
1362 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1363 switch (has_arg) {
1364 case OptionParser::eNoArgument:
1365 option_element_vector.push_back(OptionArgElement(
1366 opt_defs_index, OptionParser::GetOptionIndex() - 1, 0));
1367 break;
1368 case OptionParser::eRequiredArgument:
1369 if (OptionParser::GetOptionArgument() != nullptr) {
1370 int arg_index;
1371 if (missing_argument)
1372 arg_index = -1;
1373 else
1374 arg_index = OptionParser::GetOptionIndex() - 1;
1375
1376 option_element_vector.push_back(OptionArgElement(
1377 opt_defs_index, OptionParser::GetOptionIndex() - 2, arg_index));
1378 } else {
1379 option_element_vector.push_back(OptionArgElement(
1380 opt_defs_index, OptionParser::GetOptionIndex() - 1, -1));
1381 }
1382 break;
1383 case OptionParser::eOptionalArgument:
1384 if (OptionParser::GetOptionArgument() != nullptr) {
1385 option_element_vector.push_back(OptionArgElement(
1386 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1387 OptionParser::GetOptionIndex() - 1));
1388 } else {
1389 option_element_vector.push_back(OptionArgElement(
1390 opt_defs_index, OptionParser::GetOptionIndex() - 2,
1391 OptionParser::GetOptionIndex() - 1));
1392 }
1393 break;
1394 default:
1395 // The options table is messed up. Here we'll just continue
1396 option_element_vector.push_back(
1397 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1398 OptionParser::GetOptionIndex() - 1,
1399 OptionArgElement::eUnrecognizedArg));
1400 break;
1401 }
1402 } else {
1403 option_element_vector.push_back(
1404 OptionArgElement(OptionArgElement::eUnrecognizedArg,
1405 OptionParser::GetOptionIndex() - 1,
1406 OptionArgElement::eUnrecognizedArg));
1407 }
1408 }
1409
1410 // Finally we have to handle the case where the cursor index points at a
1411 // single "-". We want to mark that in
1412 // the option_element_vector, but only if it is not after the "--". But it
1413 // turns out that OptionParser::Parse just ignores
1414 // an isolated "-". So we have to look it up by hand here. We only care if
1415 // it is AT the cursor position.
1416 // Note, a single quoted dash is not the same as a single dash...
1417
1418 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1419 cursor_index < dash_dash_pos) &&
1420 m_args_quote_char[cursor_index] == '\0' &&
1421 strcmp(GetArgumentAtIndex(cursor_index), "-") == 0) {
1422 option_element_vector.push_back(
1423 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1424 OptionArgElement::eBareDash));
1425 }
1426}
1427
1428void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
1429 dst.clear();
1430 if (src) {
1431 for (const char *p = src; *p != '\0'; ++p) {
1432 size_t non_special_chars = ::strcspn(p, "\\");
1433 if (non_special_chars > 0) {
1434 dst.append(p, non_special_chars);
1435 p += non_special_chars;
1436 if (*p == '\0')
1437 break;
1438 }
1439
1440 if (*p == '\\') {
1441 ++p; // skip the slash
1442 switch (*p) {
1443 case 'a':
1444 dst.append(1, '\a');
1445 break;
1446 case 'b':
1447 dst.append(1, '\b');
1448 break;
1449 case 'f':
1450 dst.append(1, '\f');
1451 break;
1452 case 'n':
1453 dst.append(1, '\n');
1454 break;
1455 case 'r':
1456 dst.append(1, '\r');
1457 break;
1458 case 't':
1459 dst.append(1, '\t');
1460 break;
1461 case 'v':
1462 dst.append(1, '\v');
1463 break;
1464 case '\\':
1465 dst.append(1, '\\');
1466 break;
1467 case '\'':
1468 dst.append(1, '\'');
1469 break;
1470 case '"':
1471 dst.append(1, '"');
1472 break;
1473 case '0':
1474 // 1 to 3 octal chars
1475 {
1476 // Make a string that can hold onto the initial zero char,
1477 // up to 3 octal digits, and a terminating NULL.
1478 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
1479
1480 int i;
1481 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
1482 oct_str[i] = p[i];
1483
1484 // We don't want to consume the last octal character since
1485 // the main for loop will do this for us, so we advance p by
1486 // one less than i (even if i is zero)
1487 p += i - 1;
1488 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
1489 if (octal_value <= UINT8_MAX) {
1490 dst.append(1, (char)octal_value);
1491 }
1492 }
1493 break;
1494
1495 case 'x':
1496 // hex number in the format
1497 if (isxdigit(p[1])) {
1498 ++p; // Skip the 'x'
1499
1500 // Make a string that can hold onto two hex chars plus a
1501 // NULL terminator
1502 char hex_str[3] = {*p, '\0', '\0'};
1503 if (isxdigit(p[1])) {
1504 ++p; // Skip the first of the two hex chars
1505 hex_str[1] = *p;
1506 }
1507
1508 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
1509 if (hex_value <= UINT8_MAX)
1510 dst.append(1, (char)hex_value);
1511 } else {
1512 dst.append(1, 'x');
1513 }
1514 break;
1515
1516 default:
1517 // Just desensitize any other character by just printing what
1518 // came after the '\'
1519 dst.append(1, *p);
1520 break;
1521 }
1522 }
1523 }
1524 }
1525}
1526
1527void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
1528 dst.clear();
1529 if (src) {
1530 for (const char *p = src; *p != '\0'; ++p) {
1531 if (isprint8(*p))
1532 dst.append(1, *p);
1533 else {
1534 switch (*p) {
1535 case '\a':
1536 dst.append("\\a");
1537 break;
1538 case '\b':
1539 dst.append("\\b");
1540 break;
1541 case '\f':
1542 dst.append("\\f");
1543 break;
1544 case '\n':
1545 dst.append("\\n");
1546 break;
1547 case '\r':
1548 dst.append("\\r");
1549 break;
1550 case '\t':
1551 dst.append("\\t");
1552 break;
1553 case '\v':
1554 dst.append("\\v");
1555 break;
1556 case '\'':
1557 dst.append("\\'");
1558 break;
1559 case '"':
1560 dst.append("\\\"");
1561 break;
1562 case '\\':
1563 dst.append("\\\\");
1564 break;
1565 default: {
1566 // Just encode as octal
1567 dst.append("\\0");
1568 char octal_str[32];
1569 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1570 dst.append(octal_str);
1571 } break;
1572 }
1573 }
1574 }
1575 }
1576}
1577
1578std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
1579 char quote_char) {
1580 const char *chars_to_escape = nullptr;
1581 switch (quote_char) {
1582 case '\0':
1583 chars_to_escape = " \t\\'\"`";
1584 break;
1585 case '\'':
1586 chars_to_escape = "";
1587 break;
1588 case '"':
1589 chars_to_escape = "$\"`\\";
1590 break;
1591 default:
1592 assert(false && "Unhandled quote character");
1593 }
1594
1595 std::string res;
1596 res.reserve(arg.size());
1597 for (char c : arg) {
1598 if (::strchr(chars_to_escape, c))
1599 res.push_back('\\');
1600 res.push_back(c);
1601 }
1602 return res;
1603}