1 //===-- Args.cpp ------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Utility/Args.h"
11 #include "lldb/Utility/ConstString.h"
12 #include "lldb/Utility/FileSpec.h"
13 #include "lldb/Utility/Stream.h"
14 #include "lldb/Utility/StringList.h"
15 #include "llvm/ADT/StringSwitch.h"
18 using namespace lldb_private;
20 // A helper function for argument parsing.
21 // Parses the initial part of the first argument using normal double quote
22 // rules: backslash escapes the double quote and itself. The parsed string is
23 // appended to the second argument. The function returns the unparsed portion
24 // of the string, starting at the closing quote.
25 static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
26 std::string &result) {
27 // Inside double quotes, '\' and '"' are special.
28 static const char *k_escapable_characters = "\"\\";
30 // Skip over over regular characters and append them.
31 size_t regular = quoted.find_first_of(k_escapable_characters);
32 result += quoted.substr(0, regular);
33 quoted = quoted.substr(regular);
35 // If we have reached the end of string or the closing quote, we're done.
36 if (quoted.empty() || quoted.front() == '"')
39 // We have found a backslash.
40 quoted = quoted.drop_front();
43 // A lone backslash at the end of string, let's just append it.
48 // If the character after the backslash is not a whitelisted escapable
49 // character, we leave the character sequence untouched.
50 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
53 result += quoted.front();
54 quoted = quoted.drop_front();
60 static size_t ArgvToArgc(const char **argv) {
69 // Trims all whitespace that can separate command line arguments from the left
70 // side of the string.
71 static llvm::StringRef ltrimForArgs(llvm::StringRef str) {
72 static const char *k_space_separators = " \t";
73 return str.ltrim(k_space_separators);
76 // A helper function for SetCommandString. Parses a single argument from the
77 // command string, processing quotes and backslashes in a shell-like manner.
78 // The function returns a tuple consisting of the parsed argument, the quote
79 // char used, and the unparsed portion of the string starting at the first
80 // unqouted, unescaped whitespace character.
81 static std::tuple<std::string, char, llvm::StringRef>
82 ParseSingleArgument(llvm::StringRef command) {
83 // Argument can be split into multiple discontiguous pieces, for example:
85 // this would result in a single argument "Hello World" (without the quotes)
86 // since the quotes would be removed and there is not space between the
90 // Since we can have multiple quotes that form a single command in a command
91 // like: "Hello "world'!' (which will make a single argument "Hello world!")
92 // we remember the first quote character we encounter and use that for the
94 char first_quote_char = '\0';
96 bool arg_complete = false;
98 // Skip over over regular characters and append them.
99 size_t regular = command.find_first_of(" \t\"'`\\");
100 arg += command.substr(0, regular);
101 command = command.substr(regular);
106 char special = command.front();
107 command = command.drop_front();
110 if (command.empty()) {
115 // If the character after the backslash is not a whitelisted escapable
116 // character, we leave the character sequence untouched.
117 if (strchr(" \t\\'\"`", command.front()) == nullptr)
120 arg += command.front();
121 command = command.drop_front();
127 // We are not inside any quotes, we just found a space after an argument.
135 // We found the start of a quote scope.
136 if (first_quote_char == '\0')
137 first_quote_char = special;
140 command = ParseDoubleQuotes(command, arg);
142 // For single quotes, we simply skip ahead to the matching quote
143 // character (or the end of the string).
144 size_t quoted = command.find(special);
145 arg += command.substr(0, quoted);
146 command = command.substr(quoted);
149 // If we found a closing quote, skip it.
150 if (!command.empty())
151 command = command.drop_front();
155 } while (!arg_complete);
157 return std::make_tuple(arg, first_quote_char, command);
160 Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
161 size_t size = str.size();
162 ptr.reset(new char[size + 1]);
164 ::memcpy(data(), str.data() ? str.data() : "", size);
166 ref = llvm::StringRef(c_str(), size);
169 //----------------------------------------------------------------------
171 //----------------------------------------------------------------------
172 Args::Args(llvm::StringRef command) { SetCommandString(command); }
174 Args::Args(const Args &rhs) { *this = rhs; }
176 Args::Args(const StringList &list) : Args() {
177 for (size_t i = 0; i < list.GetSize(); ++i)
178 AppendArgument(list[i]);
181 Args &Args::operator=(const Args &rhs) {
186 for (auto &entry : rhs.m_entries) {
187 m_entries.emplace_back(entry.ref, entry.quote);
188 m_argv.push_back(m_entries.back().data());
190 m_argv.push_back(nullptr);
194 //----------------------------------------------------------------------
196 //----------------------------------------------------------------------
199 void Args::Dump(Stream &s, const char *label_name) const {
204 for (auto &entry : m_entries) {
206 s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
208 s.Format("{0}[{1}]=NULL\n", label_name, i);
212 bool Args::GetCommandString(std::string &command) const {
215 for (size_t i = 0; i < m_entries.size(); ++i) {
218 command += m_entries[i].ref;
221 return !m_entries.empty();
224 bool Args::GetQuotedCommandString(std::string &command) const {
227 for (size_t i = 0; i < m_entries.size(); ++i) {
231 if (m_entries[i].quote) {
232 command += m_entries[i].quote;
233 command += m_entries[i].ref;
234 command += m_entries[i].quote;
236 command += m_entries[i].ref;
240 return !m_entries.empty();
243 void Args::SetCommandString(llvm::StringRef command) {
247 command = ltrimForArgs(command);
250 while (!command.empty()) {
251 std::tie(arg, quote, command) = ParseSingleArgument(command);
252 m_entries.emplace_back(arg, quote);
253 m_argv.push_back(m_entries.back().data());
254 command = ltrimForArgs(command);
256 m_argv.push_back(nullptr);
259 size_t Args::GetArgumentCount() const { return m_entries.size(); }
261 const char *Args::GetArgumentAtIndex(size_t idx) const {
262 if (idx < m_argv.size())
267 char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
268 if (idx < m_entries.size())
269 return m_entries[idx].quote;
273 char **Args::GetArgumentVector() {
274 assert(!m_argv.empty());
275 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
276 // when argv or envp is null. So the code below is actually wrong. However,
277 // other code in LLDB depends on it being null. The code has been acting
278 // this way for some time, so it makes sense to leave it this way until
279 // someone has the time to come along and fix it.
280 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
283 const char **Args::GetConstArgumentVector() const {
284 assert(!m_argv.empty());
285 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
290 // Don't pop the last NULL terminator from the argv array
291 if (m_entries.empty())
293 m_argv.erase(m_argv.begin());
294 m_entries.erase(m_entries.begin());
297 void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
298 InsertArgumentAtIndex(0, arg_str, quote_char);
301 void Args::AppendArguments(const Args &rhs) {
302 assert(m_argv.size() == m_entries.size() + 1);
303 assert(m_argv.back() == nullptr);
305 for (auto &entry : rhs.m_entries) {
306 m_entries.emplace_back(entry.ref, entry.quote);
307 m_argv.push_back(m_entries.back().data());
309 m_argv.push_back(nullptr);
312 void Args::AppendArguments(const char **argv) {
313 size_t argc = ArgvToArgc(argv);
315 assert(m_argv.size() == m_entries.size() + 1);
316 assert(m_argv.back() == nullptr);
318 for (auto arg : llvm::makeArrayRef(argv, argc)) {
319 m_entries.emplace_back(arg, '\0');
320 m_argv.push_back(m_entries.back().data());
323 m_argv.push_back(nullptr);
326 void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
327 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
330 void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
332 assert(m_argv.size() == m_entries.size() + 1);
333 assert(m_argv.back() == nullptr);
335 if (idx > m_entries.size())
337 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
338 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
341 void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
343 assert(m_argv.size() == m_entries.size() + 1);
344 assert(m_argv.back() == nullptr);
346 if (idx >= m_entries.size())
349 if (arg_str.size() > m_entries[idx].ref.size()) {
350 m_entries[idx] = ArgEntry(arg_str, quote_char);
351 m_argv[idx] = m_entries[idx].data();
353 const char *src_data = arg_str.data() ? arg_str.data() : "";
354 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
355 m_entries[idx].ptr[arg_str.size()] = 0;
356 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
360 void Args::DeleteArgumentAtIndex(size_t idx) {
361 if (idx >= m_entries.size())
364 m_argv.erase(m_argv.begin() + idx);
365 m_entries.erase(m_entries.begin() + idx);
368 void Args::SetArguments(size_t argc, const char **argv) {
371 auto args = llvm::makeArrayRef(argv, argc);
372 m_entries.resize(argc);
373 m_argv.resize(argc + 1);
374 for (size_t i = 0; i < args.size(); ++i) {
376 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
380 m_entries[i] = ArgEntry(args[i], quote);
381 m_argv[i] = m_entries[i].data();
385 void Args::SetArguments(const char **argv) {
386 SetArguments(ArgvToArgc(argv), argv);
392 m_argv.push_back(nullptr);
395 const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
396 bool return_null_if_empty) {
397 static const char *k_white_space = " \t\v";
400 size_t pos = s.find_first_not_of(k_white_space);
401 if (pos == std::string::npos)
408 size_t rpos = s.find_last_not_of(k_white_space);
409 if (rpos != std::string::npos && rpos + 1 < s.size())
413 if (return_null_if_empty && s.empty())
418 const char *Args::GetShellSafeArgument(const FileSpec &shell,
419 const char *unsafe_arg,
420 std::string &safe_arg) {
421 struct ShellDescriptor {
422 ConstString m_basename;
423 const char *m_escapables;
426 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
427 {ConstString("tcsh"), " '\"<>()&$"},
428 {ConstString("sh"), " '\"<>()&"}};
431 const char *escapables = " '\"";
433 if (auto basename = shell.GetFilename()) {
434 for (const auto &Shell : g_Shells) {
435 if (Shell.m_basename == basename) {
436 escapables = Shell.m_escapables;
442 safe_arg.assign(unsafe_arg);
444 while (prev_pos < safe_arg.size()) {
445 // Escape spaces and quotes
446 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
447 if (pos != std::string::npos) {
448 safe_arg.insert(pos, 1, '\\');
453 return safe_arg.c_str();
456 lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
457 lldb::Encoding fail_value) {
458 return llvm::StringSwitch<lldb::Encoding>(s)
459 .Case("uint", eEncodingUint)
460 .Case("sint", eEncodingSint)
461 .Case("ieee754", eEncodingIEEE754)
462 .Case("vector", eEncodingVector)
463 .Default(fail_value);
466 uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
468 return LLDB_INVALID_REGNUM;
469 uint32_t result = llvm::StringSwitch<uint32_t>(s)
470 .Case("pc", LLDB_REGNUM_GENERIC_PC)
471 .Case("sp", LLDB_REGNUM_GENERIC_SP)
472 .Case("fp", LLDB_REGNUM_GENERIC_FP)
473 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
474 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
475 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
476 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
477 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
478 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
479 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
480 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
481 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
482 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
483 .Default(LLDB_INVALID_REGNUM);
487 void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
490 for (const char *p = src; *p != '\0'; ++p) {
491 size_t non_special_chars = ::strcspn(p, "\\");
492 if (non_special_chars > 0) {
493 dst.append(p, non_special_chars);
494 p += non_special_chars;
500 ++p; // skip the slash
533 // 1 to 3 octal chars
535 // Make a string that can hold onto the initial zero char, up to 3
536 // octal digits, and a terminating NULL.
537 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
540 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
543 // We don't want to consume the last octal character since the main
544 // for loop will do this for us, so we advance p by one less than i
545 // (even if i is zero)
547 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
548 if (octal_value <= UINT8_MAX) {
549 dst.append(1, (char)octal_value);
555 // hex number in the format
556 if (isxdigit(p[1])) {
559 // Make a string that can hold onto two hex chars plus a
561 char hex_str[3] = {*p, '\0', '\0'};
562 if (isxdigit(p[1])) {
563 ++p; // Skip the first of the two hex chars
567 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
568 if (hex_value <= UINT8_MAX)
569 dst.append(1, (char)hex_value);
576 // Just desensitize any other character by just printing what came
586 void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
589 for (const char *p = src; *p != '\0'; ++p) {
625 // Just encode as octal
628 snprintf(octal_str, sizeof(octal_str), "%o", *p);
629 dst.append(octal_str);
637 std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
639 const char *chars_to_escape = nullptr;
640 switch (quote_char) {
642 chars_to_escape = " \t\\'\"`";
645 chars_to_escape = "";
648 chars_to_escape = "$\"`\\";
651 assert(false && "Unhandled quote character");
655 res.reserve(arg.size());
657 if (::strchr(chars_to_escape, c))
664 OptionsWithRaw::OptionsWithRaw(llvm::StringRef arg_string) {
665 SetFromString(arg_string);
668 void OptionsWithRaw::SetFromString(llvm::StringRef arg_string) {
669 const llvm::StringRef original_args = arg_string;
671 arg_string = ltrimForArgs(arg_string);
675 // If the string doesn't start with a dash, we just have no options and just
677 if (!arg_string.startswith("-")) {
678 m_suffix = original_args;
682 bool found_suffix = false;
684 while (!arg_string.empty()) {
685 // The length of the prefix before parsing.
686 std::size_t prev_prefix_length = original_args.size() - arg_string.size();
688 // Parse the next argument from the remaining string.
689 std::tie(arg, quote, arg_string) = ParseSingleArgument(arg_string);
691 // If we get an unquoted '--' argument, then we reached the suffix part
693 Args::ArgEntry entry(arg, quote);
694 if (!entry.IsQuoted() && arg == "--") {
695 // The remaining line is the raw suffix, and the line we parsed so far
696 // needs to be interpreted as arguments.
698 m_suffix = arg_string;
701 // The length of the prefix after parsing.
702 std::size_t prefix_length = original_args.size() - arg_string.size();
704 // Take the string we know contains all the arguments and actually parse
705 // it as proper arguments.
706 llvm::StringRef prefix = original_args.take_front(prev_prefix_length);
707 m_args = Args(prefix);
708 m_arg_string = prefix;
710 // We also record the part of the string that contains the arguments plus
712 m_arg_string_with_delimiter = original_args.take_front(prefix_length);
714 // As the rest of the string became the raw suffix, we are done here.
718 arg_string = ltrimForArgs(arg_string);
721 // If we didn't find a suffix delimiter, the whole string is the raw suffix.
724 m_suffix = original_args;