180814287SRaphael Isemann //===-- Args.cpp ----------------------------------------------------------===//
2145d95c9SPavel Labath //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6145d95c9SPavel Labath //
7145d95c9SPavel Labath //===----------------------------------------------------------------------===//
8145d95c9SPavel Labath 
9145d95c9SPavel Labath #include "lldb/Utility/Args.h"
10145d95c9SPavel Labath #include "lldb/Utility/ConstString.h"
11145d95c9SPavel Labath #include "lldb/Utility/FileSpec.h"
12145d95c9SPavel Labath #include "lldb/Utility/Stream.h"
13145d95c9SPavel Labath #include "lldb/Utility/StringList.h"
14145d95c9SPavel Labath #include "llvm/ADT/StringSwitch.h"
15145d95c9SPavel Labath 
16145d95c9SPavel Labath using namespace lldb;
17145d95c9SPavel Labath using namespace lldb_private;
18145d95c9SPavel Labath 
19145d95c9SPavel Labath // A helper function for argument parsing.
20145d95c9SPavel Labath // Parses the initial part of the first argument using normal double quote
2105097246SAdrian Prantl // rules: backslash escapes the double quote and itself. The parsed string is
2205097246SAdrian Prantl // appended to the second argument. The function returns the unparsed portion
2305097246SAdrian Prantl // of the string, starting at the closing quote.
ParseDoubleQuotes(llvm::StringRef quoted,std::string & result)24145d95c9SPavel Labath static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
25145d95c9SPavel Labath                                          std::string &result) {
26145d95c9SPavel Labath   // Inside double quotes, '\' and '"' are special.
27145d95c9SPavel Labath   static const char *k_escapable_characters = "\"\\";
28145d95c9SPavel Labath   while (true) {
29145d95c9SPavel Labath     // Skip over over regular characters and append them.
30145d95c9SPavel Labath     size_t regular = quoted.find_first_of(k_escapable_characters);
31145d95c9SPavel Labath     result += quoted.substr(0, regular);
32145d95c9SPavel Labath     quoted = quoted.substr(regular);
33145d95c9SPavel Labath 
34145d95c9SPavel Labath     // If we have reached the end of string or the closing quote, we're done.
35145d95c9SPavel Labath     if (quoted.empty() || quoted.front() == '"')
36145d95c9SPavel Labath       break;
37145d95c9SPavel Labath 
38145d95c9SPavel Labath     // We have found a backslash.
39145d95c9SPavel Labath     quoted = quoted.drop_front();
40145d95c9SPavel Labath 
41145d95c9SPavel Labath     if (quoted.empty()) {
42145d95c9SPavel Labath       // A lone backslash at the end of string, let's just append it.
43145d95c9SPavel Labath       result += '\\';
44145d95c9SPavel Labath       break;
45145d95c9SPavel Labath     }
46145d95c9SPavel Labath 
47efb328f6SEric Christopher     // If the character after the backslash is not an allowed escapable
4805097246SAdrian Prantl     // character, we leave the character sequence untouched.
49145d95c9SPavel Labath     if (strchr(k_escapable_characters, quoted.front()) == nullptr)
50145d95c9SPavel Labath       result += '\\';
51145d95c9SPavel Labath 
52145d95c9SPavel Labath     result += quoted.front();
53145d95c9SPavel Labath     quoted = quoted.drop_front();
54145d95c9SPavel Labath   }
55145d95c9SPavel Labath 
56145d95c9SPavel Labath   return quoted;
57145d95c9SPavel Labath }
58145d95c9SPavel Labath 
ArgvToArgc(const char ** argv)59145d95c9SPavel Labath static size_t ArgvToArgc(const char **argv) {
60145d95c9SPavel Labath   if (!argv)
61145d95c9SPavel Labath     return 0;
62145d95c9SPavel Labath   size_t count = 0;
63145d95c9SPavel Labath   while (*argv++)
64145d95c9SPavel Labath     ++count;
65145d95c9SPavel Labath   return count;
66145d95c9SPavel Labath }
67145d95c9SPavel Labath 
683a0e1270SRaphael Isemann // Trims all whitespace that can separate command line arguments from the left
693a0e1270SRaphael Isemann // side of the string.
ltrimForArgs(llvm::StringRef str)703a0e1270SRaphael Isemann static llvm::StringRef ltrimForArgs(llvm::StringRef str) {
713a0e1270SRaphael Isemann   static const char *k_space_separators = " \t";
723a0e1270SRaphael Isemann   return str.ltrim(k_space_separators);
733a0e1270SRaphael Isemann }
743a0e1270SRaphael Isemann 
75145d95c9SPavel Labath // A helper function for SetCommandString. Parses a single argument from the
76145d95c9SPavel Labath // command string, processing quotes and backslashes in a shell-like manner.
77145d95c9SPavel Labath // The function returns a tuple consisting of the parsed argument, the quote
78145d95c9SPavel Labath // char used, and the unparsed portion of the string starting at the first
79145d95c9SPavel Labath // unqouted, unescaped whitespace character.
80145d95c9SPavel Labath static std::tuple<std::string, char, llvm::StringRef>
ParseSingleArgument(llvm::StringRef command)81145d95c9SPavel Labath ParseSingleArgument(llvm::StringRef command) {
82145d95c9SPavel Labath   // Argument can be split into multiple discontiguous pieces, for example:
83145d95c9SPavel Labath   //  "Hello ""World"
84145d95c9SPavel Labath   // this would result in a single argument "Hello World" (without the quotes)
85145d95c9SPavel Labath   // since the quotes would be removed and there is not space between the
86145d95c9SPavel Labath   // strings.
87145d95c9SPavel Labath   std::string arg;
88145d95c9SPavel Labath 
8905097246SAdrian Prantl   // Since we can have multiple quotes that form a single command in a command
9005097246SAdrian Prantl   // like: "Hello "world'!' (which will make a single argument "Hello world!")
9105097246SAdrian Prantl   // we remember the first quote character we encounter and use that for the
9205097246SAdrian Prantl   // quote character.
93145d95c9SPavel Labath   char first_quote_char = '\0';
94145d95c9SPavel Labath 
95145d95c9SPavel Labath   bool arg_complete = false;
96145d95c9SPavel Labath   do {
97145d95c9SPavel Labath     // Skip over over regular characters and append them.
984447d15aSAdrian McCarthy     size_t regular = command.find_first_of(" \t\r\"'`\\");
99145d95c9SPavel Labath     arg += command.substr(0, regular);
100145d95c9SPavel Labath     command = command.substr(regular);
101145d95c9SPavel Labath 
102145d95c9SPavel Labath     if (command.empty())
103145d95c9SPavel Labath       break;
104145d95c9SPavel Labath 
105145d95c9SPavel Labath     char special = command.front();
106145d95c9SPavel Labath     command = command.drop_front();
107145d95c9SPavel Labath     switch (special) {
108145d95c9SPavel Labath     case '\\':
109145d95c9SPavel Labath       if (command.empty()) {
110145d95c9SPavel Labath         arg += '\\';
111145d95c9SPavel Labath         break;
112145d95c9SPavel Labath       }
113145d95c9SPavel Labath 
114efb328f6SEric Christopher       // If the character after the backslash is not an allowed escapable
11505097246SAdrian Prantl       // character, we leave the character sequence untouched.
116145d95c9SPavel Labath       if (strchr(" \t\\'\"`", command.front()) == nullptr)
117145d95c9SPavel Labath         arg += '\\';
118145d95c9SPavel Labath 
119145d95c9SPavel Labath       arg += command.front();
120145d95c9SPavel Labath       command = command.drop_front();
121145d95c9SPavel Labath 
122145d95c9SPavel Labath       break;
123145d95c9SPavel Labath 
124145d95c9SPavel Labath     case ' ':
125145d95c9SPavel Labath     case '\t':
1264447d15aSAdrian McCarthy     case '\r':
12705097246SAdrian Prantl       // We are not inside any quotes, we just found a space after an argument.
12805097246SAdrian Prantl       // We are done.
129145d95c9SPavel Labath       arg_complete = true;
130145d95c9SPavel Labath       break;
131145d95c9SPavel Labath 
132145d95c9SPavel Labath     case '"':
133145d95c9SPavel Labath     case '\'':
134145d95c9SPavel Labath     case '`':
135145d95c9SPavel Labath       // We found the start of a quote scope.
136145d95c9SPavel Labath       if (first_quote_char == '\0')
137145d95c9SPavel Labath         first_quote_char = special;
138145d95c9SPavel Labath 
139145d95c9SPavel Labath       if (special == '"')
140145d95c9SPavel Labath         command = ParseDoubleQuotes(command, arg);
141145d95c9SPavel Labath       else {
142145d95c9SPavel Labath         // For single quotes, we simply skip ahead to the matching quote
14305097246SAdrian Prantl         // character (or the end of the string).
144145d95c9SPavel Labath         size_t quoted = command.find(special);
145145d95c9SPavel Labath         arg += command.substr(0, quoted);
146145d95c9SPavel Labath         command = command.substr(quoted);
147145d95c9SPavel Labath       }
148145d95c9SPavel Labath 
149145d95c9SPavel Labath       // If we found a closing quote, skip it.
150145d95c9SPavel Labath       if (!command.empty())
151145d95c9SPavel Labath         command = command.drop_front();
152145d95c9SPavel Labath 
153145d95c9SPavel Labath       break;
154145d95c9SPavel Labath     }
155145d95c9SPavel Labath   } while (!arg_complete);
156145d95c9SPavel Labath 
157145d95c9SPavel Labath   return std::make_tuple(arg, first_quote_char, command);
158145d95c9SPavel Labath }
159145d95c9SPavel Labath 
ArgEntry(llvm::StringRef str,char quote)160145d95c9SPavel Labath Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
161145d95c9SPavel Labath   size_t size = str.size();
162145d95c9SPavel Labath   ptr.reset(new char[size + 1]);
163145d95c9SPavel Labath 
164145d95c9SPavel Labath   ::memcpy(data(), str.data() ? str.data() : "", size);
165145d95c9SPavel Labath   ptr[size] = 0;
166145d95c9SPavel Labath }
167145d95c9SPavel Labath 
168145d95c9SPavel Labath // Args constructor
Args(llvm::StringRef command)169145d95c9SPavel Labath Args::Args(llvm::StringRef command) { SetCommandString(command); }
170145d95c9SPavel Labath 
Args(const Args & rhs)171145d95c9SPavel Labath Args::Args(const Args &rhs) { *this = rhs; }
172145d95c9SPavel Labath 
Args(const StringList & list)173145d95c9SPavel Labath Args::Args(const StringList &list) : Args() {
1744c78b788SRaphael Isemann   for (const std::string &arg : list)
1754c78b788SRaphael Isemann     AppendArgument(arg);
176145d95c9SPavel Labath }
177145d95c9SPavel Labath 
Args(llvm::ArrayRef<llvm::StringRef> args)178fa5fa63fSPavel Labath Args::Args(llvm::ArrayRef<llvm::StringRef> args) : Args() {
179fa5fa63fSPavel Labath   for (llvm::StringRef arg : args)
180fa5fa63fSPavel Labath     AppendArgument(arg);
181fa5fa63fSPavel Labath }
182fa5fa63fSPavel Labath 
operator =(const Args & rhs)183145d95c9SPavel Labath Args &Args::operator=(const Args &rhs) {
184145d95c9SPavel Labath   Clear();
185145d95c9SPavel Labath 
186145d95c9SPavel Labath   m_argv.clear();
187145d95c9SPavel Labath   m_entries.clear();
188145d95c9SPavel Labath   for (auto &entry : rhs.m_entries) {
1890d9a201eSRaphael Isemann     m_entries.emplace_back(entry.ref(), entry.quote);
190145d95c9SPavel Labath     m_argv.push_back(m_entries.back().data());
191145d95c9SPavel Labath   }
192145d95c9SPavel Labath   m_argv.push_back(nullptr);
193145d95c9SPavel Labath   return *this;
194145d95c9SPavel Labath }
195145d95c9SPavel Labath 
196145d95c9SPavel Labath // Destructor
197fd2433e1SJonas Devlieghere Args::~Args() = default;
198145d95c9SPavel Labath 
Dump(Stream & s,const char * label_name) const199145d95c9SPavel Labath void Args::Dump(Stream &s, const char *label_name) const {
200145d95c9SPavel Labath   if (!label_name)
201145d95c9SPavel Labath     return;
202145d95c9SPavel Labath 
203145d95c9SPavel Labath   int i = 0;
204145d95c9SPavel Labath   for (auto &entry : m_entries) {
205145d95c9SPavel Labath     s.Indent();
2060d9a201eSRaphael Isemann     s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref());
207145d95c9SPavel Labath   }
208145d95c9SPavel Labath   s.Format("{0}[{1}]=NULL\n", label_name, i);
209145d95c9SPavel Labath   s.EOL();
210145d95c9SPavel Labath }
211145d95c9SPavel Labath 
GetCommandString(std::string & command) const212145d95c9SPavel Labath bool Args::GetCommandString(std::string &command) const {
213145d95c9SPavel Labath   command.clear();
214145d95c9SPavel Labath 
215145d95c9SPavel Labath   for (size_t i = 0; i < m_entries.size(); ++i) {
216145d95c9SPavel Labath     if (i > 0)
217145d95c9SPavel Labath       command += ' ';
2180d9a201eSRaphael Isemann     command += m_entries[i].ref();
219145d95c9SPavel Labath   }
220145d95c9SPavel Labath 
221145d95c9SPavel Labath   return !m_entries.empty();
222145d95c9SPavel Labath }
223145d95c9SPavel Labath 
GetQuotedCommandString(std::string & command) const224145d95c9SPavel Labath bool Args::GetQuotedCommandString(std::string &command) const {
225145d95c9SPavel Labath   command.clear();
226145d95c9SPavel Labath 
227145d95c9SPavel Labath   for (size_t i = 0; i < m_entries.size(); ++i) {
228145d95c9SPavel Labath     if (i > 0)
229145d95c9SPavel Labath       command += ' ';
230145d95c9SPavel Labath 
231145d95c9SPavel Labath     if (m_entries[i].quote) {
232145d95c9SPavel Labath       command += m_entries[i].quote;
2330d9a201eSRaphael Isemann       command += m_entries[i].ref();
234145d95c9SPavel Labath       command += m_entries[i].quote;
235145d95c9SPavel Labath     } else {
2360d9a201eSRaphael Isemann       command += m_entries[i].ref();
237145d95c9SPavel Labath     }
238145d95c9SPavel Labath   }
239145d95c9SPavel Labath 
240145d95c9SPavel Labath   return !m_entries.empty();
241145d95c9SPavel Labath }
242145d95c9SPavel Labath 
SetCommandString(llvm::StringRef command)243145d95c9SPavel Labath void Args::SetCommandString(llvm::StringRef command) {
244145d95c9SPavel Labath   Clear();
245145d95c9SPavel Labath   m_argv.clear();
246145d95c9SPavel Labath 
2473a0e1270SRaphael Isemann   command = ltrimForArgs(command);
248145d95c9SPavel Labath   std::string arg;
249145d95c9SPavel Labath   char quote;
250145d95c9SPavel Labath   while (!command.empty()) {
251145d95c9SPavel Labath     std::tie(arg, quote, command) = ParseSingleArgument(command);
252145d95c9SPavel Labath     m_entries.emplace_back(arg, quote);
253145d95c9SPavel Labath     m_argv.push_back(m_entries.back().data());
2543a0e1270SRaphael Isemann     command = ltrimForArgs(command);
255145d95c9SPavel Labath   }
256145d95c9SPavel Labath   m_argv.push_back(nullptr);
257145d95c9SPavel Labath }
258145d95c9SPavel Labath 
GetArgumentAtIndex(size_t idx) const259145d95c9SPavel Labath const char *Args::GetArgumentAtIndex(size_t idx) const {
260145d95c9SPavel Labath   if (idx < m_argv.size())
261145d95c9SPavel Labath     return m_argv[idx];
262145d95c9SPavel Labath   return nullptr;
263145d95c9SPavel Labath }
264145d95c9SPavel Labath 
GetArgumentVector()265145d95c9SPavel Labath char **Args::GetArgumentVector() {
266145d95c9SPavel Labath   assert(!m_argv.empty());
267145d95c9SPavel Labath   // TODO: functions like execve and posix_spawnp exhibit undefined behavior
268145d95c9SPavel Labath   // when argv or envp is null.  So the code below is actually wrong.  However,
26905097246SAdrian Prantl   // other code in LLDB depends on it being null.  The code has been acting
27005097246SAdrian Prantl   // this way for some time, so it makes sense to leave it this way until
27105097246SAdrian Prantl   // someone has the time to come along and fix it.
272145d95c9SPavel Labath   return (m_argv.size() > 1) ? m_argv.data() : nullptr;
273145d95c9SPavel Labath }
274145d95c9SPavel Labath 
GetConstArgumentVector() const275145d95c9SPavel Labath const char **Args::GetConstArgumentVector() const {
276145d95c9SPavel Labath   assert(!m_argv.empty());
277145d95c9SPavel Labath   return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
278145d95c9SPavel Labath                              : nullptr;
279145d95c9SPavel Labath }
280145d95c9SPavel Labath 
Shift()281145d95c9SPavel Labath void Args::Shift() {
282145d95c9SPavel Labath   // Don't pop the last NULL terminator from the argv array
283145d95c9SPavel Labath   if (m_entries.empty())
284145d95c9SPavel Labath     return;
285145d95c9SPavel Labath   m_argv.erase(m_argv.begin());
286145d95c9SPavel Labath   m_entries.erase(m_entries.begin());
287145d95c9SPavel Labath }
288145d95c9SPavel Labath 
Unshift(llvm::StringRef arg_str,char quote_char)289145d95c9SPavel Labath void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
290145d95c9SPavel Labath   InsertArgumentAtIndex(0, arg_str, quote_char);
291145d95c9SPavel Labath }
292145d95c9SPavel Labath 
AppendArguments(const Args & rhs)293145d95c9SPavel Labath void Args::AppendArguments(const Args &rhs) {
294145d95c9SPavel Labath   assert(m_argv.size() == m_entries.size() + 1);
295145d95c9SPavel Labath   assert(m_argv.back() == nullptr);
296145d95c9SPavel Labath   m_argv.pop_back();
297145d95c9SPavel Labath   for (auto &entry : rhs.m_entries) {
2980d9a201eSRaphael Isemann     m_entries.emplace_back(entry.ref(), entry.quote);
299145d95c9SPavel Labath     m_argv.push_back(m_entries.back().data());
300145d95c9SPavel Labath   }
301145d95c9SPavel Labath   m_argv.push_back(nullptr);
302145d95c9SPavel Labath }
303145d95c9SPavel Labath 
AppendArguments(const char ** argv)304145d95c9SPavel Labath void Args::AppendArguments(const char **argv) {
305145d95c9SPavel Labath   size_t argc = ArgvToArgc(argv);
306145d95c9SPavel Labath 
307145d95c9SPavel Labath   assert(m_argv.size() == m_entries.size() + 1);
308145d95c9SPavel Labath   assert(m_argv.back() == nullptr);
309145d95c9SPavel Labath   m_argv.pop_back();
310145d95c9SPavel Labath   for (auto arg : llvm::makeArrayRef(argv, argc)) {
311145d95c9SPavel Labath     m_entries.emplace_back(arg, '\0');
312145d95c9SPavel Labath     m_argv.push_back(m_entries.back().data());
313145d95c9SPavel Labath   }
314145d95c9SPavel Labath 
315145d95c9SPavel Labath   m_argv.push_back(nullptr);
316145d95c9SPavel Labath }
317145d95c9SPavel Labath 
AppendArgument(llvm::StringRef arg_str,char quote_char)318145d95c9SPavel Labath void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
319145d95c9SPavel Labath   InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
320145d95c9SPavel Labath }
321145d95c9SPavel Labath 
InsertArgumentAtIndex(size_t idx,llvm::StringRef arg_str,char quote_char)322145d95c9SPavel Labath void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
323145d95c9SPavel Labath                                  char quote_char) {
324145d95c9SPavel Labath   assert(m_argv.size() == m_entries.size() + 1);
325145d95c9SPavel Labath   assert(m_argv.back() == nullptr);
326145d95c9SPavel Labath 
327145d95c9SPavel Labath   if (idx > m_entries.size())
328145d95c9SPavel Labath     return;
329145d95c9SPavel Labath   m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
330145d95c9SPavel Labath   m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
331145d95c9SPavel Labath }
332145d95c9SPavel Labath 
ReplaceArgumentAtIndex(size_t idx,llvm::StringRef arg_str,char quote_char)333145d95c9SPavel Labath void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
334145d95c9SPavel Labath                                   char quote_char) {
335145d95c9SPavel Labath   assert(m_argv.size() == m_entries.size() + 1);
336145d95c9SPavel Labath   assert(m_argv.back() == nullptr);
337145d95c9SPavel Labath 
338145d95c9SPavel Labath   if (idx >= m_entries.size())
339145d95c9SPavel Labath     return;
340145d95c9SPavel Labath 
341145d95c9SPavel Labath   m_entries[idx] = ArgEntry(arg_str, quote_char);
342145d95c9SPavel Labath   m_argv[idx] = m_entries[idx].data();
343145d95c9SPavel Labath }
344145d95c9SPavel Labath 
DeleteArgumentAtIndex(size_t idx)345145d95c9SPavel Labath void Args::DeleteArgumentAtIndex(size_t idx) {
346145d95c9SPavel Labath   if (idx >= m_entries.size())
347145d95c9SPavel Labath     return;
348145d95c9SPavel Labath 
349145d95c9SPavel Labath   m_argv.erase(m_argv.begin() + idx);
350145d95c9SPavel Labath   m_entries.erase(m_entries.begin() + idx);
351145d95c9SPavel Labath }
352145d95c9SPavel Labath 
SetArguments(size_t argc,const char ** argv)353145d95c9SPavel Labath void Args::SetArguments(size_t argc, const char **argv) {
354145d95c9SPavel Labath   Clear();
355145d95c9SPavel Labath 
356145d95c9SPavel Labath   auto args = llvm::makeArrayRef(argv, argc);
357145d95c9SPavel Labath   m_entries.resize(argc);
358145d95c9SPavel Labath   m_argv.resize(argc + 1);
359145d95c9SPavel Labath   for (size_t i = 0; i < args.size(); ++i) {
360145d95c9SPavel Labath     char quote =
361145d95c9SPavel Labath         ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
362145d95c9SPavel Labath             ? args[i][0]
363145d95c9SPavel Labath             : '\0';
364145d95c9SPavel Labath 
365145d95c9SPavel Labath     m_entries[i] = ArgEntry(args[i], quote);
366145d95c9SPavel Labath     m_argv[i] = m_entries[i].data();
367145d95c9SPavel Labath   }
368145d95c9SPavel Labath }
369145d95c9SPavel Labath 
SetArguments(const char ** argv)370145d95c9SPavel Labath void Args::SetArguments(const char **argv) {
371145d95c9SPavel Labath   SetArguments(ArgvToArgc(argv), argv);
372145d95c9SPavel Labath }
373145d95c9SPavel Labath 
Clear()374145d95c9SPavel Labath void Args::Clear() {
375145d95c9SPavel Labath   m_entries.clear();
376145d95c9SPavel Labath   m_argv.clear();
377145d95c9SPavel Labath   m_argv.push_back(nullptr);
378145d95c9SPavel Labath }
379145d95c9SPavel Labath 
GetShellSafeArgument(const FileSpec & shell,llvm::StringRef unsafe_arg)380bb1d702eSRaphael Isemann std::string Args::GetShellSafeArgument(const FileSpec &shell,
381bb1d702eSRaphael Isemann                                        llvm::StringRef unsafe_arg) {
382145d95c9SPavel Labath   struct ShellDescriptor {
383145d95c9SPavel Labath     ConstString m_basename;
384d0ee1d8eSRaphael Isemann     llvm::StringRef m_escapables;
385145d95c9SPavel Labath   };
386145d95c9SPavel Labath 
38707a722c5SRaphael Isemann   static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&;"},
388*9bc34636SRaphael Isemann                                        {ConstString("fish"), " '\"<>()&\\|;"},
389acc56e55SJonas Devlieghere                                        {ConstString("tcsh"), " '\"<>()&;"},
390c197cddbSRaphael Isemann                                        {ConstString("zsh"), " '\"<>()&;\\|"},
39107a722c5SRaphael Isemann                                        {ConstString("sh"), " '\"<>()&;"}};
392145d95c9SPavel Labath 
393145d95c9SPavel Labath   // safe minimal set
394d0ee1d8eSRaphael Isemann   llvm::StringRef escapables = " '\"";
395145d95c9SPavel Labath 
396145d95c9SPavel Labath   if (auto basename = shell.GetFilename()) {
397145d95c9SPavel Labath     for (const auto &Shell : g_Shells) {
398145d95c9SPavel Labath       if (Shell.m_basename == basename) {
399145d95c9SPavel Labath         escapables = Shell.m_escapables;
400145d95c9SPavel Labath         break;
401145d95c9SPavel Labath       }
402145d95c9SPavel Labath     }
403145d95c9SPavel Labath   }
404145d95c9SPavel Labath 
405d0ee1d8eSRaphael Isemann   std::string safe_arg;
406d0ee1d8eSRaphael Isemann   safe_arg.reserve(unsafe_arg.size());
407d0ee1d8eSRaphael Isemann   // Add a \ before every character that needs to be escaped.
408d0ee1d8eSRaphael Isemann   for (char c : unsafe_arg) {
409d0ee1d8eSRaphael Isemann     if (escapables.contains(c))
410d0ee1d8eSRaphael Isemann       safe_arg.push_back('\\');
411d0ee1d8eSRaphael Isemann     safe_arg.push_back(c);
412145d95c9SPavel Labath   }
413bb1d702eSRaphael Isemann   return safe_arg;
414145d95c9SPavel Labath }
415145d95c9SPavel Labath 
StringToEncoding(llvm::StringRef s,lldb::Encoding fail_value)416145d95c9SPavel Labath lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
417145d95c9SPavel Labath                                       lldb::Encoding fail_value) {
418145d95c9SPavel Labath   return llvm::StringSwitch<lldb::Encoding>(s)
419145d95c9SPavel Labath       .Case("uint", eEncodingUint)
420145d95c9SPavel Labath       .Case("sint", eEncodingSint)
421145d95c9SPavel Labath       .Case("ieee754", eEncodingIEEE754)
422145d95c9SPavel Labath       .Case("vector", eEncodingVector)
423145d95c9SPavel Labath       .Default(fail_value);
424145d95c9SPavel Labath }
425145d95c9SPavel Labath 
StringToGenericRegister(llvm::StringRef s)426145d95c9SPavel Labath uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
427145d95c9SPavel Labath   if (s.empty())
428145d95c9SPavel Labath     return LLDB_INVALID_REGNUM;
429145d95c9SPavel Labath   uint32_t result = llvm::StringSwitch<uint32_t>(s)
430145d95c9SPavel Labath                         .Case("pc", LLDB_REGNUM_GENERIC_PC)
431145d95c9SPavel Labath                         .Case("sp", LLDB_REGNUM_GENERIC_SP)
432145d95c9SPavel Labath                         .Case("fp", LLDB_REGNUM_GENERIC_FP)
433145d95c9SPavel Labath                         .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
434145d95c9SPavel Labath                         .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
435145d95c9SPavel Labath                         .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
436145d95c9SPavel Labath                         .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
437145d95c9SPavel Labath                         .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
438145d95c9SPavel Labath                         .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
439145d95c9SPavel Labath                         .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
440145d95c9SPavel Labath                         .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
441145d95c9SPavel Labath                         .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
442145d95c9SPavel Labath                         .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
443145d95c9SPavel Labath                         .Default(LLDB_INVALID_REGNUM);
444145d95c9SPavel Labath   return result;
445145d95c9SPavel Labath }
446145d95c9SPavel Labath 
EncodeEscapeSequences(const char * src,std::string & dst)447145d95c9SPavel Labath void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
448145d95c9SPavel Labath   dst.clear();
449145d95c9SPavel Labath   if (src) {
450145d95c9SPavel Labath     for (const char *p = src; *p != '\0'; ++p) {
451145d95c9SPavel Labath       size_t non_special_chars = ::strcspn(p, "\\");
452145d95c9SPavel Labath       if (non_special_chars > 0) {
453145d95c9SPavel Labath         dst.append(p, non_special_chars);
454145d95c9SPavel Labath         p += non_special_chars;
455145d95c9SPavel Labath         if (*p == '\0')
456145d95c9SPavel Labath           break;
457145d95c9SPavel Labath       }
458145d95c9SPavel Labath 
459145d95c9SPavel Labath       if (*p == '\\') {
460145d95c9SPavel Labath         ++p; // skip the slash
461145d95c9SPavel Labath         switch (*p) {
462145d95c9SPavel Labath         case 'a':
463145d95c9SPavel Labath           dst.append(1, '\a');
464145d95c9SPavel Labath           break;
465145d95c9SPavel Labath         case 'b':
466145d95c9SPavel Labath           dst.append(1, '\b');
467145d95c9SPavel Labath           break;
468145d95c9SPavel Labath         case 'f':
469145d95c9SPavel Labath           dst.append(1, '\f');
470145d95c9SPavel Labath           break;
471145d95c9SPavel Labath         case 'n':
472145d95c9SPavel Labath           dst.append(1, '\n');
473145d95c9SPavel Labath           break;
474145d95c9SPavel Labath         case 'r':
475145d95c9SPavel Labath           dst.append(1, '\r');
476145d95c9SPavel Labath           break;
477145d95c9SPavel Labath         case 't':
478145d95c9SPavel Labath           dst.append(1, '\t');
479145d95c9SPavel Labath           break;
480145d95c9SPavel Labath         case 'v':
481145d95c9SPavel Labath           dst.append(1, '\v');
482145d95c9SPavel Labath           break;
483145d95c9SPavel Labath         case '\\':
484145d95c9SPavel Labath           dst.append(1, '\\');
485145d95c9SPavel Labath           break;
486145d95c9SPavel Labath         case '\'':
487145d95c9SPavel Labath           dst.append(1, '\'');
488145d95c9SPavel Labath           break;
489145d95c9SPavel Labath         case '"':
490145d95c9SPavel Labath           dst.append(1, '"');
491145d95c9SPavel Labath           break;
492145d95c9SPavel Labath         case '0':
493145d95c9SPavel Labath           // 1 to 3 octal chars
494145d95c9SPavel Labath           {
49505097246SAdrian Prantl             // Make a string that can hold onto the initial zero char, up to 3
49605097246SAdrian Prantl             // octal digits, and a terminating NULL.
497145d95c9SPavel Labath             char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
498145d95c9SPavel Labath 
499145d95c9SPavel Labath             int i;
500145d95c9SPavel Labath             for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
501145d95c9SPavel Labath               oct_str[i] = p[i];
502145d95c9SPavel Labath 
50305097246SAdrian Prantl             // We don't want to consume the last octal character since the main
50405097246SAdrian Prantl             // for loop will do this for us, so we advance p by one less than i
50505097246SAdrian Prantl             // (even if i is zero)
506145d95c9SPavel Labath             p += i - 1;
507145d95c9SPavel Labath             unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
508145d95c9SPavel Labath             if (octal_value <= UINT8_MAX) {
50924374aefSJonas Devlieghere               dst.append(1, static_cast<char>(octal_value));
510145d95c9SPavel Labath             }
511145d95c9SPavel Labath           }
512145d95c9SPavel Labath           break;
513145d95c9SPavel Labath 
514145d95c9SPavel Labath         case 'x':
515145d95c9SPavel Labath           // hex number in the format
516145d95c9SPavel Labath           if (isxdigit(p[1])) {
517145d95c9SPavel Labath             ++p; // Skip the 'x'
518145d95c9SPavel Labath 
519145d95c9SPavel Labath             // Make a string that can hold onto two hex chars plus a
520145d95c9SPavel Labath             // NULL terminator
521145d95c9SPavel Labath             char hex_str[3] = {*p, '\0', '\0'};
522145d95c9SPavel Labath             if (isxdigit(p[1])) {
523145d95c9SPavel Labath               ++p; // Skip the first of the two hex chars
524145d95c9SPavel Labath               hex_str[1] = *p;
525145d95c9SPavel Labath             }
526145d95c9SPavel Labath 
527145d95c9SPavel Labath             unsigned long hex_value = strtoul(hex_str, nullptr, 16);
528145d95c9SPavel Labath             if (hex_value <= UINT8_MAX)
52924374aefSJonas Devlieghere               dst.append(1, static_cast<char>(hex_value));
530145d95c9SPavel Labath           } else {
531145d95c9SPavel Labath             dst.append(1, 'x');
532145d95c9SPavel Labath           }
533145d95c9SPavel Labath           break;
534145d95c9SPavel Labath 
535145d95c9SPavel Labath         default:
53605097246SAdrian Prantl           // Just desensitize any other character by just printing what came
53705097246SAdrian Prantl           // after the '\'
538145d95c9SPavel Labath           dst.append(1, *p);
539145d95c9SPavel Labath           break;
540145d95c9SPavel Labath         }
541145d95c9SPavel Labath       }
542145d95c9SPavel Labath     }
543145d95c9SPavel Labath   }
544145d95c9SPavel Labath }
545145d95c9SPavel Labath 
ExpandEscapedCharacters(const char * src,std::string & dst)546145d95c9SPavel Labath void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
547145d95c9SPavel Labath   dst.clear();
548145d95c9SPavel Labath   if (src) {
549145d95c9SPavel Labath     for (const char *p = src; *p != '\0'; ++p) {
550f5eaa2afSRaphael Isemann       if (llvm::isPrint(*p))
551145d95c9SPavel Labath         dst.append(1, *p);
552145d95c9SPavel Labath       else {
553145d95c9SPavel Labath         switch (*p) {
554145d95c9SPavel Labath         case '\a':
555145d95c9SPavel Labath           dst.append("\\a");
556145d95c9SPavel Labath           break;
557145d95c9SPavel Labath         case '\b':
558145d95c9SPavel Labath           dst.append("\\b");
559145d95c9SPavel Labath           break;
560145d95c9SPavel Labath         case '\f':
561145d95c9SPavel Labath           dst.append("\\f");
562145d95c9SPavel Labath           break;
563145d95c9SPavel Labath         case '\n':
564145d95c9SPavel Labath           dst.append("\\n");
565145d95c9SPavel Labath           break;
566145d95c9SPavel Labath         case '\r':
567145d95c9SPavel Labath           dst.append("\\r");
568145d95c9SPavel Labath           break;
569145d95c9SPavel Labath         case '\t':
570145d95c9SPavel Labath           dst.append("\\t");
571145d95c9SPavel Labath           break;
572145d95c9SPavel Labath         case '\v':
573145d95c9SPavel Labath           dst.append("\\v");
574145d95c9SPavel Labath           break;
575145d95c9SPavel Labath         case '\'':
576145d95c9SPavel Labath           dst.append("\\'");
577145d95c9SPavel Labath           break;
578145d95c9SPavel Labath         case '"':
579145d95c9SPavel Labath           dst.append("\\\"");
580145d95c9SPavel Labath           break;
581145d95c9SPavel Labath         case '\\':
582145d95c9SPavel Labath           dst.append("\\\\");
583145d95c9SPavel Labath           break;
584145d95c9SPavel Labath         default: {
585145d95c9SPavel Labath           // Just encode as octal
586145d95c9SPavel Labath           dst.append("\\0");
587145d95c9SPavel Labath           char octal_str[32];
588145d95c9SPavel Labath           snprintf(octal_str, sizeof(octal_str), "%o", *p);
589145d95c9SPavel Labath           dst.append(octal_str);
590145d95c9SPavel Labath         } break;
591145d95c9SPavel Labath         }
592145d95c9SPavel Labath       }
593145d95c9SPavel Labath     }
594145d95c9SPavel Labath   }
595145d95c9SPavel Labath }
596145d95c9SPavel Labath 
EscapeLLDBCommandArgument(const std::string & arg,char quote_char)597145d95c9SPavel Labath std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
598145d95c9SPavel Labath                                             char quote_char) {
599145d95c9SPavel Labath   const char *chars_to_escape = nullptr;
600145d95c9SPavel Labath   switch (quote_char) {
601145d95c9SPavel Labath   case '\0':
602145d95c9SPavel Labath     chars_to_escape = " \t\\'\"`";
603145d95c9SPavel Labath     break;
604145d95c9SPavel Labath   case '"':
605145d95c9SPavel Labath     chars_to_escape = "$\"`\\";
606145d95c9SPavel Labath     break;
6077d3225c4SJonas Devlieghere   case '`':
6087d3225c4SJonas Devlieghere   case '\'':
6097d3225c4SJonas Devlieghere     return arg;
610145d95c9SPavel Labath   default:
611145d95c9SPavel Labath     assert(false && "Unhandled quote character");
6127d3225c4SJonas Devlieghere     return arg;
613145d95c9SPavel Labath   }
614145d95c9SPavel Labath 
615145d95c9SPavel Labath   std::string res;
616145d95c9SPavel Labath   res.reserve(arg.size());
617145d95c9SPavel Labath   for (char c : arg) {
618145d95c9SPavel Labath     if (::strchr(chars_to_escape, c))
619145d95c9SPavel Labath       res.push_back('\\');
620145d95c9SPavel Labath     res.push_back(c);
621145d95c9SPavel Labath   }
622145d95c9SPavel Labath   return res;
623145d95c9SPavel Labath }
6243a0e1270SRaphael Isemann 
OptionsWithRaw(llvm::StringRef arg_string)6253a0e1270SRaphael Isemann OptionsWithRaw::OptionsWithRaw(llvm::StringRef arg_string) {
6263a0e1270SRaphael Isemann   SetFromString(arg_string);
6273a0e1270SRaphael Isemann }
6283a0e1270SRaphael Isemann 
SetFromString(llvm::StringRef arg_string)6293a0e1270SRaphael Isemann void OptionsWithRaw::SetFromString(llvm::StringRef arg_string) {
6303a0e1270SRaphael Isemann   const llvm::StringRef original_args = arg_string;
6313a0e1270SRaphael Isemann 
6323a0e1270SRaphael Isemann   arg_string = ltrimForArgs(arg_string);
6333a0e1270SRaphael Isemann   std::string arg;
6343a0e1270SRaphael Isemann   char quote;
6353a0e1270SRaphael Isemann 
6363a0e1270SRaphael Isemann   // If the string doesn't start with a dash, we just have no options and just
6373a0e1270SRaphael Isemann   // a raw part.
6383a0e1270SRaphael Isemann   if (!arg_string.startswith("-")) {
639adcd0268SBenjamin Kramer     m_suffix = std::string(original_args);
6403a0e1270SRaphael Isemann     return;
6413a0e1270SRaphael Isemann   }
6423a0e1270SRaphael Isemann 
6433a0e1270SRaphael Isemann   bool found_suffix = false;
6443a0e1270SRaphael Isemann   while (!arg_string.empty()) {
6453a0e1270SRaphael Isemann     // The length of the prefix before parsing.
6463a0e1270SRaphael Isemann     std::size_t prev_prefix_length = original_args.size() - arg_string.size();
6473a0e1270SRaphael Isemann 
6483a0e1270SRaphael Isemann     // Parse the next argument from the remaining string.
6493a0e1270SRaphael Isemann     std::tie(arg, quote, arg_string) = ParseSingleArgument(arg_string);
6503a0e1270SRaphael Isemann 
6513a0e1270SRaphael Isemann     // If we get an unquoted '--' argument, then we reached the suffix part
6523a0e1270SRaphael Isemann     // of the command.
6533a0e1270SRaphael Isemann     Args::ArgEntry entry(arg, quote);
6543a0e1270SRaphael Isemann     if (!entry.IsQuoted() && arg == "--") {
6553a0e1270SRaphael Isemann       // The remaining line is the raw suffix, and the line we parsed so far
6563a0e1270SRaphael Isemann       // needs to be interpreted as arguments.
6573a0e1270SRaphael Isemann       m_has_args = true;
658adcd0268SBenjamin Kramer       m_suffix = std::string(arg_string);
6593a0e1270SRaphael Isemann       found_suffix = true;
6603a0e1270SRaphael Isemann 
6613a0e1270SRaphael Isemann       // The length of the prefix after parsing.
6623a0e1270SRaphael Isemann       std::size_t prefix_length = original_args.size() - arg_string.size();
6633a0e1270SRaphael Isemann 
6643a0e1270SRaphael Isemann       // Take the string we know contains all the arguments and actually parse
6653a0e1270SRaphael Isemann       // it as proper arguments.
6663a0e1270SRaphael Isemann       llvm::StringRef prefix = original_args.take_front(prev_prefix_length);
6673a0e1270SRaphael Isemann       m_args = Args(prefix);
6683a0e1270SRaphael Isemann       m_arg_string = prefix;
6693a0e1270SRaphael Isemann 
6703a0e1270SRaphael Isemann       // We also record the part of the string that contains the arguments plus
6713a0e1270SRaphael Isemann       // the delimiter.
6723a0e1270SRaphael Isemann       m_arg_string_with_delimiter = original_args.take_front(prefix_length);
6733a0e1270SRaphael Isemann 
6743a0e1270SRaphael Isemann       // As the rest of the string became the raw suffix, we are done here.
6753a0e1270SRaphael Isemann       break;
6763a0e1270SRaphael Isemann     }
6773a0e1270SRaphael Isemann 
6783a0e1270SRaphael Isemann     arg_string = ltrimForArgs(arg_string);
6793a0e1270SRaphael Isemann   }
6803a0e1270SRaphael Isemann 
6813a0e1270SRaphael Isemann   // If we didn't find a suffix delimiter, the whole string is the raw suffix.
6829097ef84SJonas Devlieghere   if (!found_suffix)
683adcd0268SBenjamin Kramer     m_suffix = std::string(original_args);
6843a0e1270SRaphael Isemann }
685bad61548SJonas Devlieghere 
mapping(IO & io,Args::ArgEntry & v)686bad61548SJonas Devlieghere void llvm::yaml::MappingTraits<Args::ArgEntry>::mapping(IO &io,
687bad61548SJonas Devlieghere                                                         Args::ArgEntry &v) {
688bad61548SJonas Devlieghere   MappingNormalization<NormalizedArgEntry, Args::ArgEntry> keys(io, v);
689bad61548SJonas Devlieghere   io.mapRequired("value", keys->value);
690bad61548SJonas Devlieghere   io.mapRequired("quote", keys->quote);
691bad61548SJonas Devlieghere }
692bad61548SJonas Devlieghere 
mapping(IO & io,Args & v)693bad61548SJonas Devlieghere void llvm::yaml::MappingTraits<Args>::mapping(IO &io, Args &v) {
694bad61548SJonas Devlieghere   io.mapRequired("entries", v.m_entries);
695bad61548SJonas Devlieghere 
696bad61548SJonas Devlieghere   // Recompute m_argv vector.
697bad61548SJonas Devlieghere   v.m_argv.clear();
698bad61548SJonas Devlieghere   for (auto &entry : v.m_entries)
699bad61548SJonas Devlieghere     v.m_argv.push_back(entry.data());
700bad61548SJonas Devlieghere   v.m_argv.push_back(nullptr);
701bad61548SJonas Devlieghere }
702