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