Path: blob/main/contrib/llvm-project/lldb/source/Utility/Args.cpp
39587 views
//===-- Args.cpp ----------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Utility/Args.h"9#include "lldb/Utility/FileSpec.h"10#include "lldb/Utility/Stream.h"11#include "lldb/Utility/StringList.h"12#include "llvm/ADT/StringSwitch.h"1314using namespace lldb;15using namespace lldb_private;1617// A helper function for argument parsing.18// Parses the initial part of the first argument using normal double quote19// rules: backslash escapes the double quote and itself. The parsed string is20// appended to the second argument. The function returns the unparsed portion21// of the string, starting at the closing quote.22static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,23std::string &result) {24// Inside double quotes, '\' and '"' are special.25static const char *k_escapable_characters = "\"\\";26while (true) {27// Skip over regular characters and append them.28size_t regular = quoted.find_first_of(k_escapable_characters);29result += quoted.substr(0, regular);30quoted = quoted.substr(regular);3132// If we have reached the end of string or the closing quote, we're done.33if (quoted.empty() || quoted.front() == '"')34break;3536// We have found a backslash.37quoted = quoted.drop_front();3839if (quoted.empty()) {40// A lone backslash at the end of string, let's just append it.41result += '\\';42break;43}4445// If the character after the backslash is not an allowed escapable46// character, we leave the character sequence untouched.47if (strchr(k_escapable_characters, quoted.front()) == nullptr)48result += '\\';4950result += quoted.front();51quoted = quoted.drop_front();52}5354return quoted;55}5657static size_t ArgvToArgc(const char **argv) {58if (!argv)59return 0;60size_t count = 0;61while (*argv++)62++count;63return count;64}6566// Trims all whitespace that can separate command line arguments from the left67// side of the string.68static llvm::StringRef ltrimForArgs(llvm::StringRef str) {69static const char *k_space_separators = " \t";70return str.ltrim(k_space_separators);71}7273// A helper function for SetCommandString. Parses a single argument from the74// command string, processing quotes and backslashes in a shell-like manner.75// The function returns a tuple consisting of the parsed argument, the quote76// char used, and the unparsed portion of the string starting at the first77// unqouted, unescaped whitespace character.78static std::tuple<std::string, char, llvm::StringRef>79ParseSingleArgument(llvm::StringRef command) {80// Argument can be split into multiple discontiguous pieces, for example:81// "Hello ""World"82// this would result in a single argument "Hello World" (without the quotes)83// since the quotes would be removed and there is not space between the84// strings.85std::string arg;8687// Since we can have multiple quotes that form a single command in a command88// like: "Hello "world'!' (which will make a single argument "Hello world!")89// we remember the first quote character we encounter and use that for the90// quote character.91char first_quote_char = '\0';9293bool arg_complete = false;94do {95// Skip over regular characters and append them.96size_t regular = command.find_first_of(" \t\r\"'`\\");97arg += command.substr(0, regular);98command = command.substr(regular);99100if (command.empty())101break;102103char special = command.front();104command = command.drop_front();105switch (special) {106case '\\':107if (command.empty()) {108arg += '\\';109break;110}111112// If the character after the backslash is not an allowed escapable113// character, we leave the character sequence untouched.114if (strchr(" \t\\'\"`", command.front()) == nullptr)115arg += '\\';116117arg += command.front();118command = command.drop_front();119120break;121122case ' ':123case '\t':124case '\r':125// We are not inside any quotes, we just found a space after an argument.126// We are done.127arg_complete = true;128break;129130case '"':131case '\'':132case '`':133// We found the start of a quote scope.134if (first_quote_char == '\0')135first_quote_char = special;136137if (special == '"')138command = ParseDoubleQuotes(command, arg);139else {140// For single quotes, we simply skip ahead to the matching quote141// character (or the end of the string).142size_t quoted = command.find(special);143arg += command.substr(0, quoted);144command = command.substr(quoted);145}146147// If we found a closing quote, skip it.148if (!command.empty())149command = command.drop_front();150151break;152}153} while (!arg_complete);154155return std::make_tuple(arg, first_quote_char, command);156}157158Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {159size_t size = str.size();160ptr.reset(new char[size + 1]);161162::memcpy(data(), str.data() ? str.data() : "", size);163ptr[size] = 0;164}165166// Args constructor167Args::Args(llvm::StringRef command) { SetCommandString(command); }168169Args::Args(const Args &rhs) { *this = rhs; }170171Args::Args(const StringList &list) : Args() {172for (const std::string &arg : list)173AppendArgument(arg);174}175176Args::Args(llvm::ArrayRef<llvm::StringRef> args) : Args() {177for (llvm::StringRef arg : args)178AppendArgument(arg);179}180181Args &Args::operator=(const Args &rhs) {182Clear();183184m_argv.clear();185m_entries.clear();186for (auto &entry : rhs.m_entries) {187m_entries.emplace_back(entry.ref(), entry.quote);188m_argv.push_back(m_entries.back().data());189}190m_argv.push_back(nullptr);191return *this;192}193194// Destructor195Args::~Args() = default;196197void Args::Dump(Stream &s, const char *label_name) const {198if (!label_name)199return;200201int i = 0;202for (auto &entry : m_entries) {203s.Indent();204s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref());205}206s.Format("{0}[{1}]=NULL\n", label_name, i);207s.EOL();208}209210bool Args::GetCommandString(std::string &command) const {211command.clear();212213for (size_t i = 0; i < m_entries.size(); ++i) {214if (i > 0)215command += ' ';216char quote = m_entries[i].quote;217if (quote != '\0')218command += quote;219command += m_entries[i].ref();220if (quote != '\0')221command += quote;222}223224return !m_entries.empty();225}226227bool Args::GetQuotedCommandString(std::string &command) const {228command.clear();229230for (size_t i = 0; i < m_entries.size(); ++i) {231if (i > 0)232command += ' ';233234if (m_entries[i].quote) {235command += m_entries[i].quote;236command += m_entries[i].ref();237command += m_entries[i].quote;238} else {239command += m_entries[i].ref();240}241}242243return !m_entries.empty();244}245246void Args::SetCommandString(llvm::StringRef command) {247Clear();248m_argv.clear();249250command = ltrimForArgs(command);251std::string arg;252char quote;253while (!command.empty()) {254std::tie(arg, quote, command) = ParseSingleArgument(command);255m_entries.emplace_back(arg, quote);256m_argv.push_back(m_entries.back().data());257command = ltrimForArgs(command);258}259m_argv.push_back(nullptr);260}261262const char *Args::GetArgumentAtIndex(size_t idx) const {263if (idx < m_argv.size())264return m_argv[idx];265return nullptr;266}267268char **Args::GetArgumentVector() {269assert(!m_argv.empty());270// TODO: functions like execve and posix_spawnp exhibit undefined behavior271// when argv or envp is null. So the code below is actually wrong. However,272// other code in LLDB depends on it being null. The code has been acting273// this way for some time, so it makes sense to leave it this way until274// someone has the time to come along and fix it.275return (m_argv.size() > 1) ? m_argv.data() : nullptr;276}277278const char **Args::GetConstArgumentVector() const {279assert(!m_argv.empty());280return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())281: nullptr;282}283284void Args::Shift() {285// Don't pop the last NULL terminator from the argv array286if (m_entries.empty())287return;288m_argv.erase(m_argv.begin());289m_entries.erase(m_entries.begin());290}291292void Args::Unshift(llvm::StringRef arg_str, char quote_char) {293InsertArgumentAtIndex(0, arg_str, quote_char);294}295296void Args::AppendArguments(const Args &rhs) {297assert(m_argv.size() == m_entries.size() + 1);298assert(m_argv.back() == nullptr);299m_argv.pop_back();300for (auto &entry : rhs.m_entries) {301m_entries.emplace_back(entry.ref(), entry.quote);302m_argv.push_back(m_entries.back().data());303}304m_argv.push_back(nullptr);305}306307void Args::AppendArguments(const char **argv) {308size_t argc = ArgvToArgc(argv);309310assert(m_argv.size() == m_entries.size() + 1);311assert(m_argv.back() == nullptr);312m_argv.pop_back();313for (auto arg : llvm::ArrayRef(argv, argc)) {314m_entries.emplace_back(arg, '\0');315m_argv.push_back(m_entries.back().data());316}317318m_argv.push_back(nullptr);319}320321void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {322InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);323}324325void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,326char quote_char) {327assert(m_argv.size() == m_entries.size() + 1);328assert(m_argv.back() == nullptr);329330if (idx > m_entries.size())331return;332m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);333m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());334}335336void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,337char quote_char) {338assert(m_argv.size() == m_entries.size() + 1);339assert(m_argv.back() == nullptr);340341if (idx >= m_entries.size())342return;343344m_entries[idx] = ArgEntry(arg_str, quote_char);345m_argv[idx] = m_entries[idx].data();346}347348void Args::DeleteArgumentAtIndex(size_t idx) {349if (idx >= m_entries.size())350return;351352m_argv.erase(m_argv.begin() + idx);353m_entries.erase(m_entries.begin() + idx);354}355356void Args::SetArguments(size_t argc, const char **argv) {357Clear();358359auto args = llvm::ArrayRef(argv, argc);360m_entries.resize(argc);361m_argv.resize(argc + 1);362for (size_t i = 0; i < args.size(); ++i) {363char quote =364((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))365? args[i][0]366: '\0';367368m_entries[i] = ArgEntry(args[i], quote);369m_argv[i] = m_entries[i].data();370}371}372373void Args::SetArguments(const char **argv) {374SetArguments(ArgvToArgc(argv), argv);375}376377void Args::Clear() {378m_entries.clear();379m_argv.clear();380m_argv.push_back(nullptr);381}382383std::string Args::GetShellSafeArgument(const FileSpec &shell,384llvm::StringRef unsafe_arg) {385struct ShellDescriptor {386llvm::StringRef m_basename;387llvm::StringRef m_escapables;388};389390static ShellDescriptor g_Shells[] = {{"bash", " '\"<>()&;"},391{"fish", " '\"<>()&\\|;"},392{"tcsh", " '\"<>()&;"},393{"zsh", " '\"<>()&;\\|"},394{"sh", " '\"<>()&;"}};395396// safe minimal set397llvm::StringRef escapables = " '\"";398399auto basename = shell.GetFilename().GetStringRef();400if (!basename.empty()) {401for (const auto &Shell : g_Shells) {402if (Shell.m_basename == basename) {403escapables = Shell.m_escapables;404break;405}406}407}408409std::string safe_arg;410safe_arg.reserve(unsafe_arg.size());411// Add a \ before every character that needs to be escaped.412for (char c : unsafe_arg) {413if (escapables.contains(c))414safe_arg.push_back('\\');415safe_arg.push_back(c);416}417return safe_arg;418}419420lldb::Encoding Args::StringToEncoding(llvm::StringRef s,421lldb::Encoding fail_value) {422return llvm::StringSwitch<lldb::Encoding>(s)423.Case("uint", eEncodingUint)424.Case("sint", eEncodingSint)425.Case("ieee754", eEncodingIEEE754)426.Case("vector", eEncodingVector)427.Default(fail_value);428}429430uint32_t Args::StringToGenericRegister(llvm::StringRef s) {431if (s.empty())432return LLDB_INVALID_REGNUM;433uint32_t result = llvm::StringSwitch<uint32_t>(s)434.Case("pc", LLDB_REGNUM_GENERIC_PC)435.Case("sp", LLDB_REGNUM_GENERIC_SP)436.Case("fp", LLDB_REGNUM_GENERIC_FP)437.Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)438.Case("flags", LLDB_REGNUM_GENERIC_FLAGS)439.Case("arg1", LLDB_REGNUM_GENERIC_ARG1)440.Case("arg2", LLDB_REGNUM_GENERIC_ARG2)441.Case("arg3", LLDB_REGNUM_GENERIC_ARG3)442.Case("arg4", LLDB_REGNUM_GENERIC_ARG4)443.Case("arg5", LLDB_REGNUM_GENERIC_ARG5)444.Case("arg6", LLDB_REGNUM_GENERIC_ARG6)445.Case("arg7", LLDB_REGNUM_GENERIC_ARG7)446.Case("arg8", LLDB_REGNUM_GENERIC_ARG8)447.Case("tp", LLDB_REGNUM_GENERIC_TP)448.Default(LLDB_INVALID_REGNUM);449return result;450}451452void Args::EncodeEscapeSequences(const char *src, std::string &dst) {453dst.clear();454if (src) {455for (const char *p = src; *p != '\0'; ++p) {456size_t non_special_chars = ::strcspn(p, "\\");457if (non_special_chars > 0) {458dst.append(p, non_special_chars);459p += non_special_chars;460if (*p == '\0')461break;462}463464if (*p == '\\') {465++p; // skip the slash466switch (*p) {467case 'a':468dst.append(1, '\a');469break;470case 'b':471dst.append(1, '\b');472break;473case 'f':474dst.append(1, '\f');475break;476case 'n':477dst.append(1, '\n');478break;479case 'r':480dst.append(1, '\r');481break;482case 't':483dst.append(1, '\t');484break;485case 'v':486dst.append(1, '\v');487break;488case '\\':489dst.append(1, '\\');490break;491case '\'':492dst.append(1, '\'');493break;494case '"':495dst.append(1, '"');496break;497case '0':498// 1 to 3 octal chars499{500// Make a string that can hold onto the initial zero char, up to 3501// octal digits, and a terminating NULL.502char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};503504int i;505for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)506oct_str[i] = p[i];507508// We don't want to consume the last octal character since the main509// for loop will do this for us, so we advance p by one less than i510// (even if i is zero)511p += i - 1;512unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);513if (octal_value <= UINT8_MAX) {514dst.append(1, static_cast<char>(octal_value));515}516}517break;518519case 'x':520// hex number in the format521if (isxdigit(p[1])) {522++p; // Skip the 'x'523524// Make a string that can hold onto two hex chars plus a525// NULL terminator526char hex_str[3] = {*p, '\0', '\0'};527if (isxdigit(p[1])) {528++p; // Skip the first of the two hex chars529hex_str[1] = *p;530}531532unsigned long hex_value = strtoul(hex_str, nullptr, 16);533if (hex_value <= UINT8_MAX)534dst.append(1, static_cast<char>(hex_value));535} else {536dst.append(1, 'x');537}538break;539540default:541// Just desensitize any other character by just printing what came542// after the '\'543dst.append(1, *p);544break;545}546}547}548}549}550551void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {552dst.clear();553if (src) {554for (const char *p = src; *p != '\0'; ++p) {555if (llvm::isPrint(*p))556dst.append(1, *p);557else {558switch (*p) {559case '\a':560dst.append("\\a");561break;562case '\b':563dst.append("\\b");564break;565case '\f':566dst.append("\\f");567break;568case '\n':569dst.append("\\n");570break;571case '\r':572dst.append("\\r");573break;574case '\t':575dst.append("\\t");576break;577case '\v':578dst.append("\\v");579break;580case '\'':581dst.append("\\'");582break;583case '"':584dst.append("\\\"");585break;586case '\\':587dst.append("\\\\");588break;589default: {590// Just encode as octal591dst.append("\\0");592char octal_str[32];593snprintf(octal_str, sizeof(octal_str), "%o", *p);594dst.append(octal_str);595} break;596}597}598}599}600}601602std::string Args::EscapeLLDBCommandArgument(const std::string &arg,603char quote_char) {604const char *chars_to_escape = nullptr;605switch (quote_char) {606case '\0':607chars_to_escape = " \t\\'\"`";608break;609case '"':610chars_to_escape = "$\"`\\";611break;612case '`':613case '\'':614return arg;615default:616assert(false && "Unhandled quote character");617return arg;618}619620std::string res;621res.reserve(arg.size());622for (char c : arg) {623if (::strchr(chars_to_escape, c))624res.push_back('\\');625res.push_back(c);626}627return res;628}629630OptionsWithRaw::OptionsWithRaw(llvm::StringRef arg_string) {631SetFromString(arg_string);632}633634void OptionsWithRaw::SetFromString(llvm::StringRef arg_string) {635const llvm::StringRef original_args = arg_string;636637arg_string = ltrimForArgs(arg_string);638std::string arg;639char quote;640641// If the string doesn't start with a dash, we just have no options and just642// a raw part.643if (!arg_string.starts_with("-")) {644m_suffix = std::string(original_args);645return;646}647648bool found_suffix = false;649while (!arg_string.empty()) {650// The length of the prefix before parsing.651std::size_t prev_prefix_length = original_args.size() - arg_string.size();652653// Parse the next argument from the remaining string.654std::tie(arg, quote, arg_string) = ParseSingleArgument(arg_string);655656// If we get an unquoted '--' argument, then we reached the suffix part657// of the command.658Args::ArgEntry entry(arg, quote);659if (!entry.IsQuoted() && arg == "--") {660// The remaining line is the raw suffix, and the line we parsed so far661// needs to be interpreted as arguments.662m_has_args = true;663m_suffix = std::string(arg_string);664found_suffix = true;665666// The length of the prefix after parsing.667std::size_t prefix_length = original_args.size() - arg_string.size();668669// Take the string we know contains all the arguments and actually parse670// it as proper arguments.671llvm::StringRef prefix = original_args.take_front(prev_prefix_length);672m_args = Args(prefix);673m_arg_string = prefix;674675// We also record the part of the string that contains the arguments plus676// the delimiter.677m_arg_string_with_delimiter = original_args.take_front(prefix_length);678679// As the rest of the string became the raw suffix, we are done here.680break;681}682683arg_string = ltrimForArgs(arg_string);684}685686// If we didn't find a suffix delimiter, the whole string is the raw suffix.687if (!found_suffix)688m_suffix = std::string(original_args);689}690691692