1 //===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
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"
15 
16 using namespace lldb;
17 using namespace lldb_private;
18 
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 = "\"\\";
28   while (true) {
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);
33 
34     // If we have reached the end of string or the closing quote, we're done.
35     if (quoted.empty() || quoted.front() == '"')
36       break;
37 
38     // We have found a backslash.
39     quoted = quoted.drop_front();
40 
41     if (quoted.empty()) {
42       // A lone backslash at the end of string, let's just append it.
43       result += '\\';
44       break;
45     }
46 
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)
50       result += '\\';
51 
52     result += quoted.front();
53     quoted = quoted.drop_front();
54   }
55 
56   return quoted;
57 }
58 
59 static size_t ArgvToArgc(const char **argv) {
60   if (!argv)
61     return 0;
62   size_t count = 0;
63   while (*argv++)
64     ++count;
65   return count;
66 }
67 
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);
73 }
74 
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:
83   //  "Hello ""World"
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
86   // strings.
87   std::string arg;
88 
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
92   // quote character.
93   char first_quote_char = '\0';
94 
95   bool arg_complete = false;
96   do {
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);
101 
102     if (command.empty())
103       break;
104 
105     char special = command.front();
106     command = command.drop_front();
107     switch (special) {
108     case '\\':
109       if (command.empty()) {
110         arg += '\\';
111         break;
112       }
113 
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)
117         arg += '\\';
118 
119       arg += command.front();
120       command = command.drop_front();
121 
122       break;
123 
124     case ' ':
125     case '\t':
126     case '\r':
127       // We are not inside any quotes, we just found a space after an argument.
128       // We are done.
129       arg_complete = true;
130       break;
131 
132     case '"':
133     case '\'':
134     case '`':
135       // We found the start of a quote scope.
136       if (first_quote_char == '\0')
137         first_quote_char = special;
138 
139       if (special == '"')
140         command = ParseDoubleQuotes(command, arg);
141       else {
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);
147       }
148 
149       // If we found a closing quote, skip it.
150       if (!command.empty())
151         command = command.drop_front();
152 
153       break;
154     }
155   } while (!arg_complete);
156 
157   return std::make_tuple(arg, first_quote_char, command);
158 }
159 
160 Args::ArgEntry::ArgEntry(llvm::StringRef str, char quote) : quote(quote) {
161   size_t size = str.size();
162   ptr.reset(new char[size + 1]);
163 
164   ::memcpy(data(), str.data() ? str.data() : "", size);
165   ptr[size] = 0;
166   ref = llvm::StringRef(c_str(), size);
167 }
168 
169 // Args constructor
170 Args::Args(llvm::StringRef command) { SetCommandString(command); }
171 
172 Args::Args(const Args &rhs) { *this = rhs; }
173 
174 Args::Args(const StringList &list) : Args() {
175   for (const std::string &arg : list)
176     AppendArgument(arg);
177 }
178 
179 Args &Args::operator=(const Args &rhs) {
180   Clear();
181 
182   m_argv.clear();
183   m_entries.clear();
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());
187   }
188   m_argv.push_back(nullptr);
189   return *this;
190 }
191 
192 // Destructor
193 Args::~Args() {}
194 
195 void Args::Dump(Stream &s, const char *label_name) const {
196   if (!label_name)
197     return;
198 
199   int i = 0;
200   for (auto &entry : m_entries) {
201     s.Indent();
202     s.Format("{0}[{1}]=\"{2}\"\n", label_name, i++, entry.ref);
203   }
204   s.Format("{0}[{1}]=NULL\n", label_name, i);
205   s.EOL();
206 }
207 
208 bool Args::GetCommandString(std::string &command) const {
209   command.clear();
210 
211   for (size_t i = 0; i < m_entries.size(); ++i) {
212     if (i > 0)
213       command += ' ';
214     command += m_entries[i].ref;
215   }
216 
217   return !m_entries.empty();
218 }
219 
220 bool Args::GetQuotedCommandString(std::string &command) const {
221   command.clear();
222 
223   for (size_t i = 0; i < m_entries.size(); ++i) {
224     if (i > 0)
225       command += ' ';
226 
227     if (m_entries[i].quote) {
228       command += m_entries[i].quote;
229       command += m_entries[i].ref;
230       command += m_entries[i].quote;
231     } else {
232       command += m_entries[i].ref;
233     }
234   }
235 
236   return !m_entries.empty();
237 }
238 
239 void Args::SetCommandString(llvm::StringRef command) {
240   Clear();
241   m_argv.clear();
242 
243   command = ltrimForArgs(command);
244   std::string arg;
245   char quote;
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);
251   }
252   m_argv.push_back(nullptr);
253 }
254 
255 size_t Args::GetArgumentCount() const { return m_entries.size(); }
256 
257 const char *Args::GetArgumentAtIndex(size_t idx) const {
258   if (idx < m_argv.size())
259     return m_argv[idx];
260   return nullptr;
261 }
262 
263 char **Args::GetArgumentVector() {
264   assert(!m_argv.empty());
265   // TODO: functions like execve and posix_spawnp exhibit undefined behavior
266   // when argv or envp is null.  So the code below is actually wrong.  However,
267   // other code in LLDB depends on it being null.  The code has been acting
268   // this way for some time, so it makes sense to leave it this way until
269   // someone has the time to come along and fix it.
270   return (m_argv.size() > 1) ? m_argv.data() : nullptr;
271 }
272 
273 const char **Args::GetConstArgumentVector() const {
274   assert(!m_argv.empty());
275   return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
276                              : nullptr;
277 }
278 
279 void Args::Shift() {
280   // Don't pop the last NULL terminator from the argv array
281   if (m_entries.empty())
282     return;
283   m_argv.erase(m_argv.begin());
284   m_entries.erase(m_entries.begin());
285 }
286 
287 void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
288   InsertArgumentAtIndex(0, arg_str, quote_char);
289 }
290 
291 void Args::AppendArguments(const Args &rhs) {
292   assert(m_argv.size() == m_entries.size() + 1);
293   assert(m_argv.back() == nullptr);
294   m_argv.pop_back();
295   for (auto &entry : rhs.m_entries) {
296     m_entries.emplace_back(entry.ref, entry.quote);
297     m_argv.push_back(m_entries.back().data());
298   }
299   m_argv.push_back(nullptr);
300 }
301 
302 void Args::AppendArguments(const char **argv) {
303   size_t argc = ArgvToArgc(argv);
304 
305   assert(m_argv.size() == m_entries.size() + 1);
306   assert(m_argv.back() == nullptr);
307   m_argv.pop_back();
308   for (auto arg : llvm::makeArrayRef(argv, argc)) {
309     m_entries.emplace_back(arg, '\0');
310     m_argv.push_back(m_entries.back().data());
311   }
312 
313   m_argv.push_back(nullptr);
314 }
315 
316 void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
317   InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
318 }
319 
320 void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
321                                  char quote_char) {
322   assert(m_argv.size() == m_entries.size() + 1);
323   assert(m_argv.back() == nullptr);
324 
325   if (idx > m_entries.size())
326     return;
327   m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
328   m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
329 }
330 
331 void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
332                                   char quote_char) {
333   assert(m_argv.size() == m_entries.size() + 1);
334   assert(m_argv.back() == nullptr);
335 
336   if (idx >= m_entries.size())
337     return;
338 
339   if (arg_str.size() > m_entries[idx].ref.size()) {
340     m_entries[idx] = ArgEntry(arg_str, quote_char);
341     m_argv[idx] = m_entries[idx].data();
342   } else {
343     const char *src_data = arg_str.data() ? arg_str.data() : "";
344     ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
345     m_entries[idx].ptr[arg_str.size()] = 0;
346     m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
347   }
348 }
349 
350 void Args::DeleteArgumentAtIndex(size_t idx) {
351   if (idx >= m_entries.size())
352     return;
353 
354   m_argv.erase(m_argv.begin() + idx);
355   m_entries.erase(m_entries.begin() + idx);
356 }
357 
358 void Args::SetArguments(size_t argc, const char **argv) {
359   Clear();
360 
361   auto args = llvm::makeArrayRef(argv, argc);
362   m_entries.resize(argc);
363   m_argv.resize(argc + 1);
364   for (size_t i = 0; i < args.size(); ++i) {
365     char quote =
366         ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
367             ? args[i][0]
368             : '\0';
369 
370     m_entries[i] = ArgEntry(args[i], quote);
371     m_argv[i] = m_entries[i].data();
372   }
373 }
374 
375 void Args::SetArguments(const char **argv) {
376   SetArguments(ArgvToArgc(argv), argv);
377 }
378 
379 void Args::Clear() {
380   m_entries.clear();
381   m_argv.clear();
382   m_argv.push_back(nullptr);
383 }
384 
385 const char *Args::GetShellSafeArgument(const FileSpec &shell,
386                                        const char *unsafe_arg,
387                                        std::string &safe_arg) {
388   struct ShellDescriptor {
389     ConstString m_basename;
390     const char *m_escapables;
391   };
392 
393   static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
394                                        {ConstString("tcsh"), " '\"<>()&$"},
395                                        {ConstString("sh"), " '\"<>()&"}};
396 
397   // safe minimal set
398   const char *escapables = " '\"";
399 
400   if (auto basename = shell.GetFilename()) {
401     for (const auto &Shell : g_Shells) {
402       if (Shell.m_basename == basename) {
403         escapables = Shell.m_escapables;
404         break;
405       }
406     }
407   }
408 
409   safe_arg.assign(unsafe_arg);
410   size_t prev_pos = 0;
411   while (prev_pos < safe_arg.size()) {
412     // Escape spaces and quotes
413     size_t pos = safe_arg.find_first_of(escapables, prev_pos);
414     if (pos != std::string::npos) {
415       safe_arg.insert(pos, 1, '\\');
416       prev_pos = pos + 2;
417     } else
418       break;
419   }
420   return safe_arg.c_str();
421 }
422 
423 lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
424                                       lldb::Encoding fail_value) {
425   return llvm::StringSwitch<lldb::Encoding>(s)
426       .Case("uint", eEncodingUint)
427       .Case("sint", eEncodingSint)
428       .Case("ieee754", eEncodingIEEE754)
429       .Case("vector", eEncodingVector)
430       .Default(fail_value);
431 }
432 
433 uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
434   if (s.empty())
435     return LLDB_INVALID_REGNUM;
436   uint32_t result = llvm::StringSwitch<uint32_t>(s)
437                         .Case("pc", LLDB_REGNUM_GENERIC_PC)
438                         .Case("sp", LLDB_REGNUM_GENERIC_SP)
439                         .Case("fp", LLDB_REGNUM_GENERIC_FP)
440                         .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
441                         .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
442                         .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
443                         .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
444                         .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
445                         .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
446                         .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
447                         .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
448                         .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
449                         .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
450                         .Default(LLDB_INVALID_REGNUM);
451   return result;
452 }
453 
454 void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
455   dst.clear();
456   if (src) {
457     for (const char *p = src; *p != '\0'; ++p) {
458       size_t non_special_chars = ::strcspn(p, "\\");
459       if (non_special_chars > 0) {
460         dst.append(p, non_special_chars);
461         p += non_special_chars;
462         if (*p == '\0')
463           break;
464       }
465 
466       if (*p == '\\') {
467         ++p; // skip the slash
468         switch (*p) {
469         case 'a':
470           dst.append(1, '\a');
471           break;
472         case 'b':
473           dst.append(1, '\b');
474           break;
475         case 'f':
476           dst.append(1, '\f');
477           break;
478         case 'n':
479           dst.append(1, '\n');
480           break;
481         case 'r':
482           dst.append(1, '\r');
483           break;
484         case 't':
485           dst.append(1, '\t');
486           break;
487         case 'v':
488           dst.append(1, '\v');
489           break;
490         case '\\':
491           dst.append(1, '\\');
492           break;
493         case '\'':
494           dst.append(1, '\'');
495           break;
496         case '"':
497           dst.append(1, '"');
498           break;
499         case '0':
500           // 1 to 3 octal chars
501           {
502             // Make a string that can hold onto the initial zero char, up to 3
503             // octal digits, and a terminating NULL.
504             char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
505 
506             int i;
507             for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
508               oct_str[i] = p[i];
509 
510             // We don't want to consume the last octal character since the main
511             // for loop will do this for us, so we advance p by one less than i
512             // (even if i is zero)
513             p += i - 1;
514             unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
515             if (octal_value <= UINT8_MAX) {
516               dst.append(1, static_cast<char>(octal_value));
517             }
518           }
519           break;
520 
521         case 'x':
522           // hex number in the format
523           if (isxdigit(p[1])) {
524             ++p; // Skip the 'x'
525 
526             // Make a string that can hold onto two hex chars plus a
527             // NULL terminator
528             char hex_str[3] = {*p, '\0', '\0'};
529             if (isxdigit(p[1])) {
530               ++p; // Skip the first of the two hex chars
531               hex_str[1] = *p;
532             }
533 
534             unsigned long hex_value = strtoul(hex_str, nullptr, 16);
535             if (hex_value <= UINT8_MAX)
536               dst.append(1, static_cast<char>(hex_value));
537           } else {
538             dst.append(1, 'x');
539           }
540           break;
541 
542         default:
543           // Just desensitize any other character by just printing what came
544           // after the '\'
545           dst.append(1, *p);
546           break;
547         }
548       }
549     }
550   }
551 }
552 
553 void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
554   dst.clear();
555   if (src) {
556     for (const char *p = src; *p != '\0'; ++p) {
557       if (isprint(*p))
558         dst.append(1, *p);
559       else {
560         switch (*p) {
561         case '\a':
562           dst.append("\\a");
563           break;
564         case '\b':
565           dst.append("\\b");
566           break;
567         case '\f':
568           dst.append("\\f");
569           break;
570         case '\n':
571           dst.append("\\n");
572           break;
573         case '\r':
574           dst.append("\\r");
575           break;
576         case '\t':
577           dst.append("\\t");
578           break;
579         case '\v':
580           dst.append("\\v");
581           break;
582         case '\'':
583           dst.append("\\'");
584           break;
585         case '"':
586           dst.append("\\\"");
587           break;
588         case '\\':
589           dst.append("\\\\");
590           break;
591         default: {
592           // Just encode as octal
593           dst.append("\\0");
594           char octal_str[32];
595           snprintf(octal_str, sizeof(octal_str), "%o", *p);
596           dst.append(octal_str);
597         } break;
598         }
599       }
600     }
601   }
602 }
603 
604 std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
605                                             char quote_char) {
606   const char *chars_to_escape = nullptr;
607   switch (quote_char) {
608   case '\0':
609     chars_to_escape = " \t\\'\"`";
610     break;
611   case '"':
612     chars_to_escape = "$\"`\\";
613     break;
614   case '`':
615   case '\'':
616     return arg;
617   default:
618     assert(false && "Unhandled quote character");
619     return arg;
620   }
621 
622   std::string res;
623   res.reserve(arg.size());
624   for (char c : arg) {
625     if (::strchr(chars_to_escape, c))
626       res.push_back('\\');
627     res.push_back(c);
628   }
629   return res;
630 }
631 
632 OptionsWithRaw::OptionsWithRaw(llvm::StringRef arg_string) {
633   SetFromString(arg_string);
634 }
635 
636 void OptionsWithRaw::SetFromString(llvm::StringRef arg_string) {
637   const llvm::StringRef original_args = arg_string;
638 
639   arg_string = ltrimForArgs(arg_string);
640   std::string arg;
641   char quote;
642 
643   // If the string doesn't start with a dash, we just have no options and just
644   // a raw part.
645   if (!arg_string.startswith("-")) {
646     m_suffix = original_args;
647     return;
648   }
649 
650   bool found_suffix = false;
651 
652   while (!arg_string.empty()) {
653     // The length of the prefix before parsing.
654     std::size_t prev_prefix_length = original_args.size() - arg_string.size();
655 
656     // Parse the next argument from the remaining string.
657     std::tie(arg, quote, arg_string) = ParseSingleArgument(arg_string);
658 
659     // If we get an unquoted '--' argument, then we reached the suffix part
660     // of the command.
661     Args::ArgEntry entry(arg, quote);
662     if (!entry.IsQuoted() && arg == "--") {
663       // The remaining line is the raw suffix, and the line we parsed so far
664       // needs to be interpreted as arguments.
665       m_has_args = true;
666       m_suffix = arg_string;
667       found_suffix = true;
668 
669       // The length of the prefix after parsing.
670       std::size_t prefix_length = original_args.size() - arg_string.size();
671 
672       // Take the string we know contains all the arguments and actually parse
673       // it as proper arguments.
674       llvm::StringRef prefix = original_args.take_front(prev_prefix_length);
675       m_args = Args(prefix);
676       m_arg_string = prefix;
677 
678       // We also record the part of the string that contains the arguments plus
679       // the delimiter.
680       m_arg_string_with_delimiter = original_args.take_front(prefix_length);
681 
682       // As the rest of the string became the raw suffix, we are done here.
683       break;
684     }
685 
686     arg_string = ltrimForArgs(arg_string);
687   }
688 
689   // If we didn't find a suffix delimiter, the whole string is the raw suffix.
690   if (!found_suffix) {
691     found_suffix = true;
692     m_suffix = original_args;
693   }
694 }
695