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