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