1 //===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Utility/Args.h"
11 #include "lldb/Utility/ConstString.h"
12 #include "lldb/Utility/FileSpec.h"
13 #include "lldb/Utility/Stream.h"
14 #include "lldb/Utility/StringList.h"
15 #include "llvm/ADT/StringSwitch.h"
16 
17 using namespace lldb;
18 using namespace lldb_private;
19 
20 // A helper function for argument parsing.
21 // Parses the initial part of the first argument using normal double quote
22 // rules:
23 // backslash escapes the double quote and itself. The parsed string is appended
24 // to the second
25 // argument. The function returns the unparsed portion of the string, starting
26 // at the closing
27 // quote.
28 static llvm::StringRef ParseDoubleQuotes(llvm::StringRef quoted,
29                                          std::string &result) {
30   // Inside double quotes, '\' and '"' are special.
31   static const char *k_escapable_characters = "\"\\";
32   while (true) {
33     // Skip over over regular characters and append them.
34     size_t regular = quoted.find_first_of(k_escapable_characters);
35     result += quoted.substr(0, regular);
36     quoted = quoted.substr(regular);
37 
38     // If we have reached the end of string or the closing quote, we're done.
39     if (quoted.empty() || quoted.front() == '"')
40       break;
41 
42     // We have found a backslash.
43     quoted = quoted.drop_front();
44 
45     if (quoted.empty()) {
46       // A lone backslash at the end of string, let's just append it.
47       result += '\\';
48       break;
49     }
50 
51     // If the character after the backslash is not a whitelisted escapable
52     // character, we
53     // leave the character sequence untouched.
54     if (strchr(k_escapable_characters, quoted.front()) == nullptr)
55       result += '\\';
56 
57     result += quoted.front();
58     quoted = quoted.drop_front();
59   }
60 
61   return quoted;
62 }
63 
64 static size_t ArgvToArgc(const char **argv) {
65   if (!argv)
66     return 0;
67   size_t count = 0;
68   while (*argv++)
69     ++count;
70   return count;
71 }
72 
73 // A helper function for SetCommandString. Parses a single argument from the
74 // command string, processing quotes and backslashes in a shell-like manner.
75 // The function returns a tuple consisting of the parsed argument, the quote
76 // char used, and the unparsed portion of the string starting at the first
77 // unqouted, unescaped whitespace character.
78 static std::tuple<std::string, char, llvm::StringRef>
79 ParseSingleArgument(llvm::StringRef command) {
80   // Argument can be split into multiple discontiguous pieces, for example:
81   //  "Hello ""World"
82   // this would result in a single argument "Hello World" (without the quotes)
83   // since the quotes would be removed and there is not space between the
84   // strings.
85   std::string arg;
86 
87   // Since we can have multiple quotes that form a single command
88   // in a command like: "Hello "world'!' (which will make a single
89   // argument "Hello world!") we remember the first quote character
90   // we encounter and use that for the quote character.
91   char first_quote_char = '\0';
92 
93   bool arg_complete = false;
94   do {
95     // Skip over over regular characters and append them.
96     size_t regular = command.find_first_of(" \t\"'`\\");
97     arg += command.substr(0, regular);
98     command = command.substr(regular);
99 
100     if (command.empty())
101       break;
102 
103     char special = command.front();
104     command = command.drop_front();
105     switch (special) {
106     case '\\':
107       if (command.empty()) {
108         arg += '\\';
109         break;
110       }
111 
112       // If the character after the backslash is not a whitelisted escapable
113       // character, we
114       // leave the character sequence untouched.
115       if (strchr(" \t\\'\"`", command.front()) == nullptr)
116         arg += '\\';
117 
118       arg += command.front();
119       command = command.drop_front();
120 
121       break;
122 
123     case ' ':
124     case '\t':
125       // We are not inside any quotes, we just found a space after an
126       // argument. We are done.
127       arg_complete = true;
128       break;
129 
130     case '"':
131     case '\'':
132     case '`':
133       // We found the start of a quote scope.
134       if (first_quote_char == '\0')
135         first_quote_char = special;
136 
137       if (special == '"')
138         command = ParseDoubleQuotes(command, arg);
139       else {
140         // For single quotes, we simply skip ahead to the matching quote
141         // character
142         // (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   static const char *k_space_separators = " \t";
247   command = command.ltrim(k_space_separators);
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 = command.ltrim(k_space_separators);
255   }
256   m_argv.push_back(nullptr);
257 }
258 
259 size_t Args::GetArgumentCount() const { return m_entries.size(); }
260 
261 const char *Args::GetArgumentAtIndex(size_t idx) const {
262   if (idx < m_argv.size())
263     return m_argv[idx];
264   return nullptr;
265 }
266 
267 char Args::GetArgumentQuoteCharAtIndex(size_t idx) const {
268   if (idx < m_entries.size())
269     return m_entries[idx].quote;
270   return '\0';
271 }
272 
273 char **Args::GetArgumentVector() {
274   assert(!m_argv.empty());
275   // TODO: functions like execve and posix_spawnp exhibit undefined behavior
276   // when argv or envp is null.  So the code below is actually wrong.  However,
277   // other code in LLDB depends on it being null.  The code has been acting this
278   // way for some time, so it makes sense to leave it this way until someone
279   // has the time to come along and fix it.
280   return (m_argv.size() > 1) ? m_argv.data() : nullptr;
281 }
282 
283 const char **Args::GetConstArgumentVector() const {
284   assert(!m_argv.empty());
285   return (m_argv.size() > 1) ? const_cast<const char **>(m_argv.data())
286                              : nullptr;
287 }
288 
289 void Args::Shift() {
290   // Don't pop the last NULL terminator from the argv array
291   if (m_entries.empty())
292     return;
293   m_argv.erase(m_argv.begin());
294   m_entries.erase(m_entries.begin());
295 }
296 
297 void Args::Unshift(llvm::StringRef arg_str, char quote_char) {
298   InsertArgumentAtIndex(0, arg_str, quote_char);
299 }
300 
301 void Args::AppendArguments(const Args &rhs) {
302   assert(m_argv.size() == m_entries.size() + 1);
303   assert(m_argv.back() == nullptr);
304   m_argv.pop_back();
305   for (auto &entry : rhs.m_entries) {
306     m_entries.emplace_back(entry.ref, entry.quote);
307     m_argv.push_back(m_entries.back().data());
308   }
309   m_argv.push_back(nullptr);
310 }
311 
312 void Args::AppendArguments(const char **argv) {
313   size_t argc = ArgvToArgc(argv);
314 
315   assert(m_argv.size() == m_entries.size() + 1);
316   assert(m_argv.back() == nullptr);
317   m_argv.pop_back();
318   for (auto arg : llvm::makeArrayRef(argv, argc)) {
319     m_entries.emplace_back(arg, '\0');
320     m_argv.push_back(m_entries.back().data());
321   }
322 
323   m_argv.push_back(nullptr);
324 }
325 
326 void Args::AppendArgument(llvm::StringRef arg_str, char quote_char) {
327   InsertArgumentAtIndex(GetArgumentCount(), arg_str, quote_char);
328 }
329 
330 void Args::InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
331                                  char quote_char) {
332   assert(m_argv.size() == m_entries.size() + 1);
333   assert(m_argv.back() == nullptr);
334 
335   if (idx > m_entries.size())
336     return;
337   m_entries.emplace(m_entries.begin() + idx, arg_str, quote_char);
338   m_argv.insert(m_argv.begin() + idx, m_entries[idx].data());
339 }
340 
341 void Args::ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
342                                   char quote_char) {
343   assert(m_argv.size() == m_entries.size() + 1);
344   assert(m_argv.back() == nullptr);
345 
346   if (idx >= m_entries.size())
347     return;
348 
349   if (arg_str.size() > m_entries[idx].ref.size()) {
350     m_entries[idx] = ArgEntry(arg_str, quote_char);
351     m_argv[idx] = m_entries[idx].data();
352   } else {
353     const char *src_data = arg_str.data() ? arg_str.data() : "";
354     ::memcpy(m_entries[idx].data(), src_data, arg_str.size());
355     m_entries[idx].ptr[arg_str.size()] = 0;
356     m_entries[idx].ref = m_entries[idx].ref.take_front(arg_str.size());
357   }
358 }
359 
360 void Args::DeleteArgumentAtIndex(size_t idx) {
361   if (idx >= m_entries.size())
362     return;
363 
364   m_argv.erase(m_argv.begin() + idx);
365   m_entries.erase(m_entries.begin() + idx);
366 }
367 
368 void Args::SetArguments(size_t argc, const char **argv) {
369   Clear();
370 
371   auto args = llvm::makeArrayRef(argv, argc);
372   m_entries.resize(argc);
373   m_argv.resize(argc + 1);
374   for (size_t i = 0; i < args.size(); ++i) {
375     char quote =
376         ((args[i][0] == '\'') || (args[i][0] == '"') || (args[i][0] == '`'))
377             ? args[i][0]
378             : '\0';
379 
380     m_entries[i] = ArgEntry(args[i], quote);
381     m_argv[i] = m_entries[i].data();
382   }
383 }
384 
385 void Args::SetArguments(const char **argv) {
386   SetArguments(ArgvToArgc(argv), argv);
387 }
388 
389 void Args::Clear() {
390   m_entries.clear();
391   m_argv.clear();
392   m_argv.push_back(nullptr);
393 }
394 
395 const char *Args::StripSpaces(std::string &s, bool leading, bool trailing,
396                               bool return_null_if_empty) {
397   static const char *k_white_space = " \t\v";
398   if (!s.empty()) {
399     if (leading) {
400       size_t pos = s.find_first_not_of(k_white_space);
401       if (pos == std::string::npos)
402         s.clear();
403       else if (pos > 0)
404         s.erase(0, pos);
405     }
406 
407     if (trailing) {
408       size_t rpos = s.find_last_not_of(k_white_space);
409       if (rpos != std::string::npos && rpos + 1 < s.size())
410         s.erase(rpos + 1);
411     }
412   }
413   if (return_null_if_empty && s.empty())
414     return nullptr;
415   return s.c_str();
416 }
417 
418 bool Args::StringToVersion(llvm::StringRef string, uint32_t &major,
419                            uint32_t &minor, uint32_t &update) {
420   major = UINT32_MAX;
421   minor = UINT32_MAX;
422   update = UINT32_MAX;
423 
424   if (string.empty())
425     return false;
426 
427   llvm::StringRef major_str, minor_str, update_str;
428 
429   std::tie(major_str, minor_str) = string.split('.');
430   std::tie(minor_str, update_str) = minor_str.split('.');
431   if (major_str.getAsInteger(10, major))
432     return false;
433   if (!minor_str.empty() && minor_str.getAsInteger(10, minor))
434     return false;
435   if (!update_str.empty() && update_str.getAsInteger(10, update))
436     return false;
437 
438   return true;
439 }
440 
441 const char *Args::GetShellSafeArgument(const FileSpec &shell,
442                                        const char *unsafe_arg,
443                                        std::string &safe_arg) {
444   struct ShellDescriptor {
445     ConstString m_basename;
446     const char *m_escapables;
447   };
448 
449   static ShellDescriptor g_Shells[] = {{ConstString("bash"), " '\"<>()&"},
450                                        {ConstString("tcsh"), " '\"<>()&$"},
451                                        {ConstString("sh"), " '\"<>()&"}};
452 
453   // safe minimal set
454   const char *escapables = " '\"";
455 
456   if (auto basename = shell.GetFilename()) {
457     for (const auto &Shell : g_Shells) {
458       if (Shell.m_basename == basename) {
459         escapables = Shell.m_escapables;
460         break;
461       }
462     }
463   }
464 
465   safe_arg.assign(unsafe_arg);
466   size_t prev_pos = 0;
467   while (prev_pos < safe_arg.size()) {
468     // Escape spaces and quotes
469     size_t pos = safe_arg.find_first_of(escapables, prev_pos);
470     if (pos != std::string::npos) {
471       safe_arg.insert(pos, 1, '\\');
472       prev_pos = pos + 2;
473     } else
474       break;
475   }
476   return safe_arg.c_str();
477 }
478 
479 lldb::Encoding Args::StringToEncoding(llvm::StringRef s,
480                                       lldb::Encoding fail_value) {
481   return llvm::StringSwitch<lldb::Encoding>(s)
482       .Case("uint", eEncodingUint)
483       .Case("sint", eEncodingSint)
484       .Case("ieee754", eEncodingIEEE754)
485       .Case("vector", eEncodingVector)
486       .Default(fail_value);
487 }
488 
489 uint32_t Args::StringToGenericRegister(llvm::StringRef s) {
490   if (s.empty())
491     return LLDB_INVALID_REGNUM;
492   uint32_t result = llvm::StringSwitch<uint32_t>(s)
493                         .Case("pc", LLDB_REGNUM_GENERIC_PC)
494                         .Case("sp", LLDB_REGNUM_GENERIC_SP)
495                         .Case("fp", LLDB_REGNUM_GENERIC_FP)
496                         .Cases("ra", "lr", LLDB_REGNUM_GENERIC_RA)
497                         .Case("flags", LLDB_REGNUM_GENERIC_FLAGS)
498                         .Case("arg1", LLDB_REGNUM_GENERIC_ARG1)
499                         .Case("arg2", LLDB_REGNUM_GENERIC_ARG2)
500                         .Case("arg3", LLDB_REGNUM_GENERIC_ARG3)
501                         .Case("arg4", LLDB_REGNUM_GENERIC_ARG4)
502                         .Case("arg5", LLDB_REGNUM_GENERIC_ARG5)
503                         .Case("arg6", LLDB_REGNUM_GENERIC_ARG6)
504                         .Case("arg7", LLDB_REGNUM_GENERIC_ARG7)
505                         .Case("arg8", LLDB_REGNUM_GENERIC_ARG8)
506                         .Default(LLDB_INVALID_REGNUM);
507   return result;
508 }
509 
510 void Args::EncodeEscapeSequences(const char *src, std::string &dst) {
511   dst.clear();
512   if (src) {
513     for (const char *p = src; *p != '\0'; ++p) {
514       size_t non_special_chars = ::strcspn(p, "\\");
515       if (non_special_chars > 0) {
516         dst.append(p, non_special_chars);
517         p += non_special_chars;
518         if (*p == '\0')
519           break;
520       }
521 
522       if (*p == '\\') {
523         ++p; // skip the slash
524         switch (*p) {
525         case 'a':
526           dst.append(1, '\a');
527           break;
528         case 'b':
529           dst.append(1, '\b');
530           break;
531         case 'f':
532           dst.append(1, '\f');
533           break;
534         case 'n':
535           dst.append(1, '\n');
536           break;
537         case 'r':
538           dst.append(1, '\r');
539           break;
540         case 't':
541           dst.append(1, '\t');
542           break;
543         case 'v':
544           dst.append(1, '\v');
545           break;
546         case '\\':
547           dst.append(1, '\\');
548           break;
549         case '\'':
550           dst.append(1, '\'');
551           break;
552         case '"':
553           dst.append(1, '"');
554           break;
555         case '0':
556           // 1 to 3 octal chars
557           {
558             // Make a string that can hold onto the initial zero char,
559             // up to 3 octal digits, and a terminating NULL.
560             char oct_str[5] = {'\0', '\0', '\0', '\0', '\0'};
561 
562             int i;
563             for (i = 0; (p[i] >= '0' && p[i] <= '7') && i < 4; ++i)
564               oct_str[i] = p[i];
565 
566             // We don't want to consume the last octal character since
567             // the main for loop will do this for us, so we advance p by
568             // one less than i (even if i is zero)
569             p += i - 1;
570             unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
571             if (octal_value <= UINT8_MAX) {
572               dst.append(1, (char)octal_value);
573             }
574           }
575           break;
576 
577         case 'x':
578           // hex number in the format
579           if (isxdigit(p[1])) {
580             ++p; // Skip the 'x'
581 
582             // Make a string that can hold onto two hex chars plus a
583             // NULL terminator
584             char hex_str[3] = {*p, '\0', '\0'};
585             if (isxdigit(p[1])) {
586               ++p; // Skip the first of the two hex chars
587               hex_str[1] = *p;
588             }
589 
590             unsigned long hex_value = strtoul(hex_str, nullptr, 16);
591             if (hex_value <= UINT8_MAX)
592               dst.append(1, (char)hex_value);
593           } else {
594             dst.append(1, 'x');
595           }
596           break;
597 
598         default:
599           // Just desensitize any other character by just printing what
600           // came after the '\'
601           dst.append(1, *p);
602           break;
603         }
604       }
605     }
606   }
607 }
608 
609 void Args::ExpandEscapedCharacters(const char *src, std::string &dst) {
610   dst.clear();
611   if (src) {
612     for (const char *p = src; *p != '\0'; ++p) {
613       if (isprint(*p))
614         dst.append(1, *p);
615       else {
616         switch (*p) {
617         case '\a':
618           dst.append("\\a");
619           break;
620         case '\b':
621           dst.append("\\b");
622           break;
623         case '\f':
624           dst.append("\\f");
625           break;
626         case '\n':
627           dst.append("\\n");
628           break;
629         case '\r':
630           dst.append("\\r");
631           break;
632         case '\t':
633           dst.append("\\t");
634           break;
635         case '\v':
636           dst.append("\\v");
637           break;
638         case '\'':
639           dst.append("\\'");
640           break;
641         case '"':
642           dst.append("\\\"");
643           break;
644         case '\\':
645           dst.append("\\\\");
646           break;
647         default: {
648           // Just encode as octal
649           dst.append("\\0");
650           char octal_str[32];
651           snprintf(octal_str, sizeof(octal_str), "%o", *p);
652           dst.append(octal_str);
653         } break;
654         }
655       }
656     }
657   }
658 }
659 
660 std::string Args::EscapeLLDBCommandArgument(const std::string &arg,
661                                             char quote_char) {
662   const char *chars_to_escape = nullptr;
663   switch (quote_char) {
664   case '\0':
665     chars_to_escape = " \t\\'\"`";
666     break;
667   case '\'':
668     chars_to_escape = "";
669     break;
670   case '"':
671     chars_to_escape = "$\"`\\";
672     break;
673   default:
674     assert(false && "Unhandled quote character");
675   }
676 
677   std::string res;
678   res.reserve(arg.size());
679   for (char c : arg) {
680     if (::strchr(chars_to_escape, c))
681       res.push_back('\\');
682     res.push_back(c);
683   }
684   return res;
685 }
686