• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // This class works with command lines: building and parsing.
6 // Arguments with prefixes ('--', '-', and on Windows, '/') are switches.
7 // Switches will precede all other arguments without switch prefixes.
8 // Switches can optionally have values, delimited by '=', e.g., "-switch=value".
9 // An argument of "--" will terminate switch parsing during initialization,
10 // interpreting subsequent tokens as non-switch arguments, regardless of prefix.
11 
12 // There is a singleton read-only CommandLine that represents the command line
13 // that the current process was started with.  It must be initialized in main().
14 
15 #ifndef BASE_COMMAND_LINE_H_
16 #define BASE_COMMAND_LINE_H_
17 
18 #include <stddef.h>
19 #include <map>
20 #include <string>
21 #include <vector>
22 
23 #include "base/base_export.h"
24 #include "base/strings/string16.h"
25 #include "base/strings/string_piece.h"
26 #include "build/build_config.h"
27 
28 namespace base {
29 
30 class FilePath;
31 
32 class BASE_EXPORT CommandLine {
33  public:
34 #if defined(OS_WIN)
35   // The native command line string type.
36   using StringType = string16;
37 #elif defined(OS_POSIX)
38   using StringType = std::string;
39 #endif
40 
41   using CharType = StringType::value_type;
42   using StringVector = std::vector<StringType>;
43   using SwitchMap = std::map<std::string, StringType>;
44   using StringPieceSwitchMap = std::map<StringPiece, const StringType*>;
45 
46   // A constructor for CommandLines that only carry switches and arguments.
47   enum NoProgram { NO_PROGRAM };
48   explicit CommandLine(NoProgram no_program);
49 
50   // Construct a new command line with |program| as argv[0].
51   explicit CommandLine(const FilePath& program);
52 
53   // Construct a new command line from an argument list.
54   CommandLine(int argc, const CharType* const* argv);
55   explicit CommandLine(const StringVector& argv);
56 
57   // Override copy and assign to ensure |switches_by_stringpiece_| is valid.
58   CommandLine(const CommandLine& other);
59   CommandLine& operator=(const CommandLine& other);
60 
61   ~CommandLine();
62 
63 #if defined(OS_WIN)
64   // By default this class will treat command-line arguments beginning with
65   // slashes as switches on Windows, but not other platforms.
66   //
67   // If this behavior is inappropriate for your application, you can call this
68   // function BEFORE initializing the current process' global command line
69   // object and the behavior will be the same as Posix systems (only hyphens
70   // begin switches, everything else will be an arg).
71   static void set_slash_is_not_a_switch();
72 
73   // Normally when the CommandLine singleton is initialized it gets the command
74   // line via the GetCommandLineW API and then uses the shell32 API
75   // CommandLineToArgvW to parse the command line and convert it back to
76   // argc and argv. Tests who don't want this dependency on shell32 and need
77   // to honor the arguments passed in should use this function.
78   static void InitUsingArgvForTesting(int argc, const char* const* argv);
79 #endif
80 
81   // Initialize the current process CommandLine singleton. On Windows, ignores
82   // its arguments (we instead parse GetCommandLineW() directly) because we
83   // don't trust the CRT's parsing of the command line, but it still must be
84   // called to set up the command line. Returns false if initialization has
85   // already occurred, and true otherwise. Only the caller receiving a 'true'
86   // return value should take responsibility for calling Reset.
87   static bool Init(int argc, const char* const* argv);
88 
89   // Destroys the current process CommandLine singleton. This is necessary if
90   // you want to reset the base library to its initial state (for example, in an
91   // outer library that needs to be able to terminate, and be re-initialized).
92   // If Init is called only once, as in main(), Reset() is not necessary.
93   // Do not call this in tests. Use base::test::ScopedCommandLine instead.
94   static void Reset();
95 
96   // Get the singleton CommandLine representing the current process's
97   // command line. Note: returned value is mutable, but not thread safe;
98   // only mutate if you know what you're doing!
99   static CommandLine* ForCurrentProcess();
100 
101   // Returns true if the CommandLine has been initialized for the given process.
102   static bool InitializedForCurrentProcess();
103 
104 #if defined(OS_WIN)
105   static CommandLine FromString(const string16& command_line);
106 #endif
107 
108   // Initialize from an argv vector.
109   void InitFromArgv(int argc, const CharType* const* argv);
110   void InitFromArgv(const StringVector& argv);
111 
112   // Constructs and returns the represented command line string.
113   // CAUTION! This should be avoided on POSIX because quoting behavior is
114   // unclear.
GetCommandLineString()115   StringType GetCommandLineString() const {
116     return GetCommandLineStringInternal(false);
117   }
118 
119 #if defined(OS_WIN)
120   // Constructs and returns the represented command line string. Assumes the
121   // command line contains placeholders (eg, %1) and quotes any program or
122   // argument with a '%' in it. This should be avoided unless the placeholder is
123   // required by an external interface (eg, the Windows registry), because it is
124   // not generally safe to replace it with an arbitrary string. If possible,
125   // placeholders should be replaced *before* converting the command line to a
126   // string.
GetCommandLineStringWithPlaceholders()127   StringType GetCommandLineStringWithPlaceholders() const {
128     return GetCommandLineStringInternal(true);
129   }
130 #endif
131 
132   // Constructs and returns the represented arguments string.
133   // CAUTION! This should be avoided on POSIX because quoting behavior is
134   // unclear.
GetArgumentsString()135   StringType GetArgumentsString() const {
136     return GetArgumentsStringInternal(false);
137   }
138 
139 #if defined(OS_WIN)
140   // Constructs and returns the represented arguments string. Assumes the
141   // command line contains placeholders (eg, %1) and quotes any argument with a
142   // '%' in it. This should be avoided unless the placeholder is required by an
143   // external interface (eg, the Windows registry), because it is not generally
144   // safe to replace it with an arbitrary string. If possible, placeholders
145   // should be replaced *before* converting the arguments to a string.
GetArgumentsStringWithPlaceholders()146   StringType GetArgumentsStringWithPlaceholders() const {
147     return GetArgumentsStringInternal(true);
148   }
149 #endif
150 
151   // Returns the original command line string as a vector of strings.
argv()152   const StringVector& argv() const { return argv_; }
153 
154   // Get and Set the program part of the command line string (the first item).
155   FilePath GetProgram() const;
156   void SetProgram(const FilePath& program);
157 
158   // Returns true if this command line contains the given switch.
159   // Switch names must be lowercase.
160   // The second override provides an optimized version to avoid inlining codegen
161   // at every callsite to find the length of the constant and construct a
162   // StringPiece.
163   bool HasSwitch(const StringPiece& switch_string) const;
164   bool HasSwitch(const char switch_constant[]) const;
165 
166   // Returns the value associated with the given switch. If the switch has no
167   // value or isn't present, this method returns the empty string.
168   // Switch names must be lowercase.
169   std::string GetSwitchValueASCII(const StringPiece& switch_string) const;
170   FilePath GetSwitchValuePath(const StringPiece& switch_string) const;
171   StringType GetSwitchValueNative(const StringPiece& switch_string) const;
172 
173   // Get a copy of all switches, along with their values.
GetSwitches()174   const SwitchMap& GetSwitches() const { return switches_; }
175 
176   // Append a switch [with optional value] to the command line.
177   // Note: Switches will precede arguments regardless of appending order.
178   void AppendSwitch(const std::string& switch_string);
179   void AppendSwitchPath(const std::string& switch_string,
180                         const FilePath& path);
181   void AppendSwitchNative(const std::string& switch_string,
182                           const StringType& value);
183   void AppendSwitchASCII(const std::string& switch_string,
184                          const std::string& value);
185 
186   // Copy a set of switches (and any values) from another command line.
187   // Commonly used when launching a subprocess.
188   void CopySwitchesFrom(const CommandLine& source,
189                         const char* const switches[],
190                         size_t count);
191 
192   // Get the remaining arguments to the command.
193   StringVector GetArgs() const;
194 
195   // Append an argument to the command line. Note that the argument is quoted
196   // properly such that it is interpreted as one argument to the target command.
197   // AppendArg is primarily for ASCII; non-ASCII input is interpreted as UTF-8.
198   // Note: Switches will precede arguments regardless of appending order.
199   void AppendArg(const std::string& value);
200   void AppendArgPath(const FilePath& value);
201   void AppendArgNative(const StringType& value);
202 
203   // Append the switches and arguments from another command line to this one.
204   // If |include_program| is true, include |other|'s program as well.
205   void AppendArguments(const CommandLine& other, bool include_program);
206 
207   // Insert a command before the current command.
208   // Common for debuggers, like "valgrind" or "gdb --args".
209   void PrependWrapper(const StringType& wrapper);
210 
211 #if defined(OS_WIN)
212   // Initialize by parsing the given command line string.
213   // The program name is assumed to be the first item in the string.
214   void ParseFromString(const string16& command_line);
215 #endif
216 
217  private:
218   // Disallow default constructor; a program name must be explicitly specified.
219   CommandLine();
220   // Allow the copy constructor. A common pattern is to copy of the current
221   // process's command line and then add some flags to it. For example:
222   //   CommandLine cl(*CommandLine::ForCurrentProcess());
223   //   cl.AppendSwitch(...);
224 
225   // Internal version of GetCommandLineString. If |quote_placeholders| is true,
226   // also quotes parts with '%' in them.
227   StringType GetCommandLineStringInternal(bool quote_placeholders) const;
228 
229   // Internal version of GetArgumentsString. If |quote_placeholders| is true,
230   // also quotes parts with '%' in them.
231   StringType GetArgumentsStringInternal(bool quote_placeholders) const;
232 
233   // Reconstruct |switches_by_stringpiece| to be a mirror of |switches|.
234   // |switches_by_stringpiece| only contains pointers to objects owned by
235   // |switches|.
236   void ResetStringPieces();
237 
238   // The singleton CommandLine representing the current process's command line.
239   static CommandLine* current_process_commandline_;
240 
241   // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
242   StringVector argv_;
243 
244   // Parsed-out switch keys and values.
245   SwitchMap switches_;
246 
247   // A mirror of |switches_| with only references to the actual strings.
248   // The StringPiece internally holds a pointer to a key in |switches_| while
249   // the mapped_type points to a value in |switches_|.
250   // Used for allocation-free lookups.
251   StringPieceSwitchMap switches_by_stringpiece_;
252 
253   // The index after the program and switches, any arguments start here.
254   size_t begin_args_;
255 };
256 
257 }  // namespace base
258 
259 #endif  // BASE_COMMAND_LINE_H_
260