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