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