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