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