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