1 //===-- Args.cpp ------------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Utility/Args.h"
10 #include "lldb/Utility/ConstString.h"
11 #include "lldb/Utility/FileSpec.h"
12 #include "lldb/Utility/Stream.h"
13 #include "lldb/Utility/StringList.h"
14 #include "llvm/ADT/StringSwitch.h"
17 using namespace lldb_private;
19 // A helper function for argument parsing.
20 // Parses the initial part of the first argument using normal double quote
21 // rules: backslash escapes the double quote and itself. The parsed string is
22 // appended to the second argument. The function returns the unparsed portion
23 // of the string, starting at the closing quote.
24 static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
25 std::string &result) {
26 // Inside double quotes, '\' and '"' are special.
27 static const char *k_escapable_characters = "\"\\";
29 // Skip over over regular characters and append them.
30 size_t regular = quoted.find_first_of(k_escapable_characters);
31 result += quoted.substr(0, regular);
32 quoted = quoted.substr(regular);
34 // If we have reached the end of string or the closing quote, we're done.
35 if (quoted.empty() || quoted.front() == '"')
38 // We have found a backslash.
39 quoted = quoted.drop_front();
42 // A lone backslash at the end of string, let's just append it.
47 // If the character after the backslash is not a whitelisted escapable
48 // character, we leave the character sequence untouched.
49 if (strchr(k_escapable_characters, quoted.front()) == nullptr)
52 result += quoted.front();
53 quoted = quoted.drop_front();
59 static size_t ArgvToArgc(const char **argv) {
68 // Trims all whitespace that can separate command line arguments from the left
69 // side of the string.
70 static llvm::StringRef ltrimForArgs(llvm::StringRef str) {
71 static const char *k_space_separators = " \t";
72 return str.ltrim(k_space_separators);
75 // A helper function for SetCommandString. Parses a single argument from the
76 // command string, processing quotes and backslashes in a shell-like manner.
77 // The function returns a tuple consisting of the parsed argument, the quote
78 // char used, and the unparsed portion of the string starting at the first
79 // unqouted, unescaped whitespace character.
80 static std::tuple<std::string, char, llvm::StringRef>
81 ParseSingleArgument(llvm::StringRef command) {
82 // Argument can be split into multiple discontiguous pieces, for example:
84 // this would result in a single argument "Hello World" (without the quotes)
85 // since the quotes would be removed and there is not space between the
89 // Since we can have multiple quotes that form a single command in a command
90 // like: "Hello "world'!' (which will make a single argument "Hello world!")
91 // we remember the first quote character we encounter and use that for the
93 char first_quote_char = '\0';
95 bool arg_complete = false;
97 // Skip over over regular characters and append them.
98 size_t regular = command.find_first_of(" \t\r\"'`\\");
99 arg += command.substr(0, regular);
100 command = command.substr(regular);
105 char special = command.front();
106 command = command.drop_front();
109 if (command.empty()) {
114 // If the character after the backslash is not a whitelisted escapable
115 // character, we leave the character sequence untouched.
116 if (strchr(" \t\\'\"`", command.front()) == nullptr)
119 arg += command.front();
120 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);
170 Args::Args(llvm::StringRef command) { SetCommandString(command); }
172 Args::Args(const Args &rhs) { *this = rhs; }
174 Args::Args(const StringList &list) : Args() {
175 for (size_t i = 0; i < list.GetSize(); ++i)
176 AppendArgument(list[i]);
179 Args &Args::operator=(const Args &rhs) {
184 for (auto &entry : rhs.m_entries) {
185 m_entries.emplace_back(entry.ref, entry.quote);
186 m_argv.push_back(m_entries.back().data());
188 m_argv.push_back(nullptr);
195 void Args::Dump(Stream &s, const char *label_name) const {
200 for (auto &entry : m_entries) {
202 s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
204 s.Format("{0}[{1}]=NULL\n", label_name, i);
208 bool Args::GetCommandString(std::string &command) const {
211 for (size_t i = 0; i < m_entries.size(); ++i) {
214 command += m_entries[i].ref;
217 return !m_entries.empty();
220 bool Args::GetQuotedCommandString(std::string &command) const {
223 for (size_t i = 0; i < m_entries.size(); ++i) {
227 if (m_entries[i].quote) {
228 command += m_entries[i].quote;
229 command += m_entries[i].ref;
230 command += m_entries[i].quote;
232 command += m_entries[i].ref;
236 return !m_entries.empty();
239 void Args::SetCommandString(llvm::StringRef command) {
243 command = ltrimForArgs(command);
246 while (!command.empty()) {
247 std::tie(arg, quote, command) = ParseSingleArgument(command);
248 m_entries.emplace_back(arg, quote);
249 m_argv.push_back(m_entries.back().data());
250 command = ltrimForArgs(command);
252 m_argv.push_back(nullptr);
255 size_t Args::GetArgumentCount() const { return m_entries.size(); }
257 const char *Args::GetArgumentAtIndex(size_t idx) const {
258 if (idx < m_argv.size())
263 char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
264 if (idx < m_entries.size())
265 return m_entries[idx].quote;
269 char **Args::GetArgumentVector() {
270 assert(!m_argv.empty());
271 // TODO: functions like execve and posix_spawnp exhibit undefined behavior
272 // when argv or envp is null. So the code below is actually wrong. However,
273 // other code in LLDB depends on it being null. The code has been acting
274 // this way for some time, so it makes sense to leave it this way until
275 // someone has the time to come along and fix it.
276 return (m_argv.size() > 1) ? m_argv.data() : nullptr;
279 const char **Args::GetConstArgumentVector() const {
280 assert(!m_argv.empty());
281 return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
286 // Don't pop the last NULL terminator from the argv array
287 if (m_entries.empty())
289 m_argv.erase(m_argv.begin());
290 m_entries.erase(m_entries.begin());
293 void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
294 InsertArgumentAtIndex(0, arg_str, quote_char);
297 void Args::AppendArguments(const Args &rhs) {
298 assert(m_argv.size() == m_entries.size() + 1);
299 assert(m_argv.back() == nullptr);
301 for (auto &entry : rhs.m_entries) {
302 m_entries.emplace_back(entry.ref, entry.quote);
303 m_argv.push_back(m_entries.back().data());
305 m_argv.push_back(nullptr);
308 void Args::AppendArguments(const char **argv) {
309 size_t argc = ArgvToArgc(argv);
311 assert(m_argv.size() == m_entries.size() + 1);
312 assert(m_argv.back() == nullptr);
314 for (auto arg : llvm::makeArrayRef(argv, argc)) {
315 m_entries.emplace_back(arg, '\0');
316 m_argv.push_back(m_entries.back().data());
319 m_argv.push_back(nullptr);
322 void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
323 InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
326 void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
328 assert(m_argv.size() == m_entries.size() + 1);
329 assert(m_argv.back() == nullptr);
331 if (idx > m_entries.size())
333 m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
334 m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
337 void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
339 assert(m_argv.size() == m_entries.size() + 1);
340 assert(m_argv.back() == nullptr);
342 if (idx >= m_entries.size())
345 if (arg_str.size() > m_entries[idx].ref.size()) {
346 m_entries[idx] = ArgEntry(arg_str, quote_char);
347 m_argv[idx] = m_entries[idx].data();
349 const char *src_data = arg_str.data() ? arg_str.data() : "";
350 ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
351 m_entries[idx].ptr[arg_str.size()] = 0;
352 m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
356 void Args::DeleteArgumentAtIndex(size_t idx) {
357 if (idx >= m_entries.size())
360 m_argv.erase(m_argv.begin() + idx);
361 m_entries.erase(m_entries.begin() + idx);
364 void Args::SetArguments(size_t argc, const char **argv) {
367 auto args = llvm::makeArrayRef(argv, argc);
368 m_entries.resize(argc);
369 m_argv.resize(argc + 1);
370 for (size_t i = 0; i < args.size(); ++i) {
372 ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
376 m_entries[i] = ArgEntry(args[i], quote);
377 m_argv[i] = m_entries[i].data();
381 void Args::SetArguments(const char **argv) {
382 SetArguments(ArgvToArgc(argv), argv);
388 m_argv.push_back(nullptr);
391 const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
392 bool return_null_if_empty) {
393 static const char *k_white_space = " \t\v";
396 size_t pos = s.find_first_not_of(k_white_space);
397 if (pos == std::string::npos)
404 size_t rpos = s.find_last_not_of(k_white_space);
405 if (rpos != std::string::npos && rpos + 1 < s.size())
409 if (return_null_if_empty && s.empty())
414 const char *Args::GetShellSafeArgument(const FileSpec &shell,
415 const char *unsafe_arg,
416 std::string &safe_arg) {
417 struct ShellDescriptor {
418 ConstString m_basename;
419 const char *m_escapables;
422 static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
423 {ConstString("tcsh"), " '\"<>()&$"},
424 {ConstString("sh"), " '\"<>()&"}};
427 const char *escapables = " '\"";
429 if (auto basename = shell.GetFilename()) {
430 for (const auto &Shell : g_Shells) {
431 if (Shell.m_basename == basename) {
432 escapables = Shell.m_escapables;
438 safe_arg.assign(unsafe_arg);
440 while (prev_pos < safe_arg.size()) {
441 // Escape spaces and quotes
442 size_t pos = safe_arg.find_first_of(escapables, prev_pos);
443 if (pos != std::string::npos) {
444 safe_arg.insert(pos, 1, '\\');
449 return safe_arg.c_str();
452 lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
453 lldb::Encoding fail_value) {
454 return llvm::StringSwitch<lldb::Encoding>(s)
455 .Case("uint", eEncodingUint)
456 .Case("sint", eEncodingSint)
457 .Case("ieee754", eEncodingIEEE754)
458 .Case("vector", eEncodingVector)
459 .Default(fail_value);
462 uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
464 return LLDB_INVALID_REGNUM;
465 uint32_t result = llvm::StringSwitch<uint32_t>(s)
466 .Case("pc", LLDB_REGNUM_GENERIC_PC)
467 .Case("sp", LLDB_REGNUM_GENERIC_SP)
468 .Case("fp", LLDB_REGNUM_GENERIC_FP)
469 .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
470 .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
471 .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
472 .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
473 .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
474 .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
475 .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
476 .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
477 .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
478 .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
479 .Default(LLDB_INVALID_REGNUM);
483 void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
486 for (const char *p = src; *p != '\0'; ++p) {
487 size_t non_special_chars = ::strcspn(p, "\\");
488 if (non_special_chars > 0) {
489 dst.append(p, non_special_chars);
490 p += non_special_chars;
496 ++p; // skip the slash
529 // 1 to 3 octal chars
531 // Make a string that can hold onto the initial zero char, up to 3
532 // octal digits, and a terminating NULL.
533 char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
536 for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
539 // We don't want to consume the last octal character since the main
540 // for loop will do this for us, so we advance p by one less than i
541 // (even if i is zero)
543 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
544 if (octal_value <= UINT8_MAX) {
545 dst.append(1, static_cast<char>(octal_value));
551 // hex number in the format
552 if (isxdigit(p[1])) {
555 // Make a string that can hold onto two hex chars plus a
557 char hex_str[3] = {*p, '\0', '\0'};
558 if (isxdigit(p[1])) {
559 ++p; // Skip the first of the two hex chars
563 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
564 if (hex_value <= UINT8_MAX)
565 dst.append(1, static_cast<char>(hex_value));
572 // Just desensitize any other character by just printing what came
582 void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
585 for (const char *p = src; *p != '\0'; ++p) {
621 // Just encode as octal
624 snprintf(octal_str, sizeof(octal_str), "%o", *p);
625 dst.append(octal_str);
633 std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
635 const char *chars_to_escape = nullptr;
636 switch (quote_char) {
638 chars_to_escape = " \t\\'\"`";
641 chars_to_escape = "$\"`\\";
647 assert(false && "Unhandled quote character");
652 res.reserve(arg.size());
654 if (::strchr(chars_to_escape, c))
661 OptionsWithRaw::OptionsWithRaw(llvm::StringRef arg_string) {
662 SetFromString(arg_string);
665 void OptionsWithRaw::SetFromString(llvm::StringRef arg_string) {
666 const llvm::StringRef original_args = arg_string;
668 arg_string = ltrimForArgs(arg_string);
672 // If the string doesn't start with a dash, we just have no options and just
674 if (!arg_string.startswith("-")) {
675 m_suffix = original_args;
679 bool found_suffix = false;
681 while (!arg_string.empty()) {
682 // The length of the prefix before parsing.
683 std::size_t prev_prefix_length = original_args.size() - arg_string.size();
685 // Parse the next argument from the remaining string.
686 std::tie(arg, quote, arg_string) = ParseSingleArgument(arg_string);
688 // If we get an unquoted '--' argument, then we reached the suffix part
690 Args::ArgEntry entry(arg, quote);
691 if (!entry.IsQuoted() && arg == "--") {
692 // The remaining line is the raw suffix, and the line we parsed so far
693 // needs to be interpreted as arguments.
695 m_suffix = arg_string;
698 // The length of the prefix after parsing.
699 std::size_t prefix_length = original_args.size() - arg_string.size();
701 // Take the string we know contains all the arguments and actually parse
702 // it as proper arguments.
703 llvm::StringRef prefix = original_args.take_front(prev_prefix_length);
704 m_args = Args(prefix);
705 m_arg_string = prefix;
707 // We also record the part of the string that contains the arguments plus
709 m_arg_string_with_delimiter = original_args.take_front(prefix_length);
711 // As the rest of the string became the raw suffix, we are done here.
715 arg_string = ltrimForArgs(arg_string);
718 // If we didn't find a suffix delimiter, the whole string is the raw suffix.
721 m_suffix = original_args;