]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/include/lldb/Interpreter/Args.h
MFV r321673:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / include / lldb / Interpreter / Args.h
1 //===-- Args.h --------------------------------------------------*- 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 #ifndef liblldb_Command_h_
11 #define liblldb_Command_h_
12
13 // C Includes
14 // C++ Includes
15 #include <list>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 // Other libraries and framework includes
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/StringRef.h"
23 // Project includes
24 #include "lldb/Utility/Status.h"
25 #include "lldb/lldb-private-types.h"
26 #include "lldb/lldb-types.h"
27
28 namespace lldb_private {
29
30 struct Option;
31
32 typedef std::vector<std::tuple<std::string, int, std::string>> OptionArgVector;
33 typedef std::shared_ptr<OptionArgVector> OptionArgVectorSP;
34
35 struct OptionArgElement {
36   enum { eUnrecognizedArg = -1, eBareDash = -2, eBareDoubleDash = -3 };
37
38   OptionArgElement(int defs_index, int pos, int arg_pos)
39       : opt_defs_index(defs_index), opt_pos(pos), opt_arg_pos(arg_pos) {}
40
41   int opt_defs_index;
42   int opt_pos;
43   int opt_arg_pos;
44 };
45
46 typedef std::vector<OptionArgElement> OptionElementVector;
47
48 //----------------------------------------------------------------------
49 /// @class Args Args.h "lldb/Interpreter/Args.h"
50 /// @brief A command line argument class.
51 ///
52 /// The Args class is designed to be fed a command line. The
53 /// command line is copied into an internal buffer and then split up
54 /// into arguments. Arguments are space delimited if there are no quotes
55 /// (single, double, or backtick quotes) surrounding the argument. Spaces
56 /// can be escaped using a \ character to avoid having to surround an
57 /// argument that contains a space with quotes.
58 //----------------------------------------------------------------------
59 class Args {
60 public:
61   struct ArgEntry {
62   private:
63     friend class Args;
64     std::unique_ptr<char[]> ptr;
65
66     char *data() { return ptr.get(); }
67
68   public:
69     ArgEntry() = default;
70     ArgEntry(llvm::StringRef str, char quote);
71
72     llvm::StringRef ref;
73     char quote;
74     const char *c_str() const { return ptr.get(); }
75   };
76
77   //------------------------------------------------------------------
78   /// Construct with an option command string.
79   ///
80   /// @param[in] command
81   ///     A NULL terminated command that will be copied and split up
82   ///     into arguments.
83   ///
84   /// @see Args::SetCommandString(llvm::StringRef)
85   //------------------------------------------------------------------
86   Args(llvm::StringRef command = llvm::StringRef());
87
88   Args(const Args &rhs);
89
90   Args &operator=(const Args &rhs);
91
92   //------------------------------------------------------------------
93   /// Destructor.
94   //------------------------------------------------------------------
95   ~Args();
96
97   //------------------------------------------------------------------
98   /// Dump all entries to the stream \a s using label \a label_name.
99   ///
100   /// If label_name is nullptr, the dump operation is skipped.
101   ///
102   /// @param[in] s
103   ///     The stream to which to dump all arguments in the argument
104   ///     vector.
105   /// @param[in] label_name
106   ///     The label_name to use as the label printed for each
107   ///     entry of the args like so:
108   ///       {label_name}[{index}]={value}
109   //------------------------------------------------------------------
110   void Dump(Stream &s, const char *label_name = "argv") const;
111
112   //------------------------------------------------------------------
113   /// Sets the command string contained by this object.
114   ///
115   /// The command string will be copied and split up into arguments
116   /// that can be accessed via the accessor functions.
117   ///
118   /// @param[in] command
119   ///     A command StringRef that will be copied and split up
120   ///     into arguments.
121   ///
122   /// @see Args::GetArgumentCount() const
123   /// @see Args::GetArgumentAtIndex (size_t) const
124   /// @see Args::GetArgumentVector ()
125   /// @see Args::Shift ()
126   /// @see Args::Unshift (const char *)
127   //------------------------------------------------------------------
128   void SetCommandString(llvm::StringRef command);
129
130   bool GetCommandString(std::string &command) const;
131
132   bool GetQuotedCommandString(std::string &command) const;
133
134   //------------------------------------------------------------------
135   /// Gets the number of arguments left in this command object.
136   ///
137   /// @return
138   ///     The number or arguments in this object.
139   //------------------------------------------------------------------
140   size_t GetArgumentCount() const;
141   bool empty() const { return GetArgumentCount() == 0; }
142
143   //------------------------------------------------------------------
144   /// Gets the NULL terminated C string argument pointer for the
145   /// argument at index \a idx.
146   ///
147   /// @return
148   ///     The NULL terminated C string argument pointer if \a idx is a
149   ///     valid argument index, NULL otherwise.
150   //------------------------------------------------------------------
151   const char *GetArgumentAtIndex(size_t idx) const;
152
153   llvm::ArrayRef<ArgEntry> entries() const { return m_entries; }
154   char GetArgumentQuoteCharAtIndex(size_t idx) const;
155
156   std::vector<ArgEntry>::const_iterator begin() const {
157     return m_entries.begin();
158   }
159   std::vector<ArgEntry>::const_iterator end() const { return m_entries.end(); }
160
161   size_t size() const { return GetArgumentCount(); }
162   const ArgEntry &operator[](size_t n) const { return m_entries[n]; }
163
164   //------------------------------------------------------------------
165   /// Gets the argument vector.
166   ///
167   /// The value returned by this function can be used by any function
168   /// that takes and vector. The return value is just like \a argv
169   /// in the standard C entry point function:
170   ///     \code
171   ///         int main (int argc, const char **argv);
172   ///     \endcode
173   ///
174   /// @return
175   ///     An array of NULL terminated C string argument pointers that
176   ///     also has a terminating NULL C string pointer
177   //------------------------------------------------------------------
178   char **GetArgumentVector();
179
180   //------------------------------------------------------------------
181   /// Gets the argument vector.
182   ///
183   /// The value returned by this function can be used by any function
184   /// that takes and vector. The return value is just like \a argv
185   /// in the standard C entry point function:
186   ///     \code
187   ///         int main (int argc, const char **argv);
188   ///     \endcode
189   ///
190   /// @return
191   ///     An array of NULL terminate C string argument pointers that
192   ///     also has a terminating NULL C string pointer
193   //------------------------------------------------------------------
194   const char **GetConstArgumentVector() const;
195
196   //------------------------------------------------------------------
197   /// Gets the argument as an ArrayRef. Note that the return value does *not*
198   /// have a nullptr const char * at the end, as the size of the list is
199   /// embedded in the ArrayRef object.
200   //------------------------------------------------------------------
201   llvm::ArrayRef<const char *> GetArgumentArrayRef() const {
202     return llvm::makeArrayRef(m_argv).drop_back();
203   }
204
205   //------------------------------------------------------------------
206   /// Appends a new argument to the end of the list argument list.
207   ///
208   /// @param[in] arg_cstr
209   ///     The new argument as a NULL terminated C string.
210   ///
211   /// @param[in] quote_char
212   ///     If the argument was originally quoted, put in the quote char here.
213   //------------------------------------------------------------------
214   void AppendArgument(llvm::StringRef arg_str, char quote_char = '\0');
215
216   void AppendArguments(const Args &rhs);
217
218   void AppendArguments(const char **argv);
219
220   //------------------------------------------------------------------
221   /// Insert the argument value at index \a idx to \a arg_cstr.
222   ///
223   /// @param[in] idx
224   ///     The index of where to insert the argument.
225   ///
226   /// @param[in] arg_cstr
227   ///     The new argument as a NULL terminated C string.
228   ///
229   /// @param[in] quote_char
230   ///     If the argument was originally quoted, put in the quote char here.
231   ///
232   /// @return
233   ///     The NULL terminated C string of the copy of \a arg_cstr.
234   //------------------------------------------------------------------
235   void InsertArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
236                              char quote_char = '\0');
237
238   //------------------------------------------------------------------
239   /// Replaces the argument value at index \a idx to \a arg_cstr
240   /// if \a idx is a valid argument index.
241   ///
242   /// @param[in] idx
243   ///     The index of the argument that will have its value replaced.
244   ///
245   /// @param[in] arg_cstr
246   ///     The new argument as a NULL terminated C string.
247   ///
248   /// @param[in] quote_char
249   ///     If the argument was originally quoted, put in the quote char here.
250   //------------------------------------------------------------------
251   void ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str,
252                               char quote_char = '\0');
253
254   //------------------------------------------------------------------
255   /// Deletes the argument value at index
256   /// if \a idx is a valid argument index.
257   ///
258   /// @param[in] idx
259   ///     The index of the argument that will have its value replaced.
260   ///
261   //------------------------------------------------------------------
262   void DeleteArgumentAtIndex(size_t idx);
263
264   //------------------------------------------------------------------
265   /// Sets the argument vector value, optionally copying all
266   /// arguments into an internal buffer.
267   ///
268   /// Sets the arguments to match those found in \a argv. All argument
269   /// strings will be copied into an internal buffers.
270   //
271   //  FIXME: Handle the quote character somehow.
272   //------------------------------------------------------------------
273   void SetArguments(size_t argc, const char **argv);
274
275   void SetArguments(const char **argv);
276
277   //------------------------------------------------------------------
278   /// Shifts the first argument C string value of the array off the
279   /// argument array.
280   ///
281   /// The string value will be freed, so a copy of the string should
282   /// be made by calling Args::GetArgumentAtIndex (size_t) const
283   /// first and copying the returned value before calling
284   /// Args::Shift().
285   ///
286   /// @see Args::GetArgumentAtIndex (size_t) const
287   //------------------------------------------------------------------
288   void Shift();
289
290   //------------------------------------------------------------------
291   /// Inserts a class owned copy of \a arg_cstr at the beginning of
292   /// the argument vector.
293   ///
294   /// A copy \a arg_cstr will be made.
295   ///
296   /// @param[in] arg_cstr
297   ///     The argument to push on the front of the argument stack.
298   ///
299   /// @param[in] quote_char
300   ///     If the argument was originally quoted, put in the quote char here.
301   //------------------------------------------------------------------
302   void Unshift(llvm::StringRef arg_str, char quote_char = '\0');
303
304   //------------------------------------------------------------------
305   /// Parse the arguments in the contained arguments.
306   ///
307   /// The arguments that are consumed by the argument parsing process
308   /// will be removed from the argument vector. The arguments that
309   /// get processed start at the second argument. The first argument
310   /// is assumed to be the command and will not be touched.
311   ///
312   /// param[in] platform_sp
313   ///   The platform used for option validation.  This is necessary
314   ///   because an empty execution_context is not enough to get us
315   ///   to a reasonable platform.  If the platform isn't given,
316   ///   we'll try to get it from the execution context.  If we can't
317   ///   get it from the execution context, we'll skip validation.
318   ///
319   /// param[in] require_validation
320   ///   When true, it will fail option parsing if validation could
321   ///   not occur due to not having a platform.
322   ///
323   /// @see class Options
324   //------------------------------------------------------------------
325   Status ParseOptions(Options &options, ExecutionContext *execution_context,
326                       lldb::PlatformSP platform_sp, bool require_validation);
327
328   bool IsPositionalArgument(const char *arg);
329
330   // The following works almost identically to ParseOptions, except that no
331   // option is required to have arguments, and it builds up the
332   // option_arg_vector as it parses the options.
333
334   std::string ParseAliasOptions(Options &options, CommandReturnObject &result,
335                                 OptionArgVector *option_arg_vector,
336                                 llvm::StringRef raw_input_line);
337
338   void ParseArgsForCompletion(Options &options,
339                               OptionElementVector &option_element_vector,
340                               uint32_t cursor_index);
341
342   //------------------------------------------------------------------
343   // Clear the arguments.
344   //
345   // For re-setting or blanking out the list of arguments.
346   //------------------------------------------------------------------
347   void Clear();
348
349   static const char *StripSpaces(std::string &s, bool leading = true,
350                                  bool trailing = true,
351                                  bool return_null_if_empty = true);
352
353   static bool UInt64ValueIsValidForByteSize(uint64_t uval64,
354                                             size_t total_byte_size) {
355     if (total_byte_size > 8)
356       return false;
357
358     if (total_byte_size == 8)
359       return true;
360
361     const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1;
362     return uval64 <= max;
363   }
364
365   static bool SInt64ValueIsValidForByteSize(int64_t sval64,
366                                             size_t total_byte_size) {
367     if (total_byte_size > 8)
368       return false;
369
370     if (total_byte_size == 8)
371       return true;
372
373     const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1;
374     const int64_t min = ~(max);
375     return min <= sval64 && sval64 <= max;
376   }
377
378   static lldb::addr_t StringToAddress(const ExecutionContext *exe_ctx,
379                                       llvm::StringRef s,
380                                       lldb::addr_t fail_value, Status *error);
381
382   static bool StringToBoolean(llvm::StringRef s, bool fail_value,
383                               bool *success_ptr);
384
385   static char StringToChar(llvm::StringRef s, char fail_value,
386                            bool *success_ptr);
387
388   static int64_t StringToOptionEnum(llvm::StringRef s,
389                                     OptionEnumValueElement *enum_values,
390                                     int32_t fail_value, Status &error);
391
392   static lldb::ScriptLanguage
393   StringToScriptLanguage(llvm::StringRef s, lldb::ScriptLanguage fail_value,
394                          bool *success_ptr);
395
396   // TODO: Use StringRef
397   static Status StringToFormat(const char *s, lldb::Format &format,
398                                size_t *byte_size_ptr); // If non-NULL, then a
399                                                        // byte size can precede
400                                                        // the format character
401
402   static lldb::Encoding
403   StringToEncoding(llvm::StringRef s,
404                    lldb::Encoding fail_value = lldb::eEncodingInvalid);
405
406   static uint32_t StringToGenericRegister(llvm::StringRef s);
407
408   static bool StringToVersion(llvm::StringRef string, uint32_t &major,
409                               uint32_t &minor, uint32_t &update);
410
411   static const char *GetShellSafeArgument(const FileSpec &shell,
412                                           const char *unsafe_arg,
413                                           std::string &safe_arg);
414
415   // EncodeEscapeSequences will change the textual representation of common
416   // escape sequences like "\n" (two characters) into a single '\n'. It does
417   // this for all of the supported escaped sequences and for the \0ooo (octal)
418   // and \xXX (hex). The resulting "dst" string will contain the character
419   // versions of all supported escape sequences. The common supported escape
420   // sequences are: "\a", "\b", "\f", "\n", "\r", "\t", "\v", "\'", "\"", "\\".
421
422   static void EncodeEscapeSequences(const char *src, std::string &dst);
423
424   // ExpandEscapeSequences will change a string of possibly non-printable
425   // characters and expand them into text. So '\n' will turn into two characters
426   // like "\n" which is suitable for human reading. When a character is not
427   // printable and isn't one of the common in escape sequences listed in the
428   // help for EncodeEscapeSequences, then it will be encoded as octal. Printable
429   // characters are left alone.
430   static void ExpandEscapedCharacters(const char *src, std::string &dst);
431
432   static std::string EscapeLLDBCommandArgument(const std::string &arg,
433                                                char quote_char);
434
435   //------------------------------------------------------------------
436   /// Add or replace an environment variable with the given value.
437   ///
438   /// This command adds the environment variable if it is not already
439   /// present using the given value.  If the environment variable is
440   /// already in the list, it replaces the first such occurrence
441   /// with the new value.
442   //------------------------------------------------------------------
443   void AddOrReplaceEnvironmentVariable(llvm::StringRef env_var_name,
444                                        llvm::StringRef new_value);
445
446   /// Return whether a given environment variable exists.
447   ///
448   /// This command treats Args like a list of environment variables,
449   /// as used in ProcessLaunchInfo.  It treats each argument as
450   /// an {env_var_name}={value} or an {env_var_name} entry.
451   ///
452   /// @param[in] env_var_name
453   ///     Specifies the name of the environment variable to check.
454   ///
455   /// @param[out] argument_index
456   ///     If non-null, then when the environment variable is found,
457   ///     the index of the argument position will be returned in
458   ///     the size_t pointed to by this argument.
459   ///
460   /// @return
461   ///     true if the specified env var name exists in the list in
462   ///     either of the above-mentioned formats; otherwise, false.
463   //------------------------------------------------------------------
464   bool ContainsEnvironmentVariable(llvm::StringRef env_var_name,
465                                    size_t *argument_index = nullptr) const;
466
467 private:
468   size_t FindArgumentIndexForOption(Option *long_options,
469                                     int long_options_index) const;
470
471   std::vector<ArgEntry> m_entries;
472   std::vector<char *> m_argv;
473
474   void UpdateArgsAfterOptionParsing();
475 };
476
477 } // namespace lldb_private
478
479 #endif // liblldb_Command_h_