1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
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 // If a switch is specified multiple times, only the last value is used.
10 // An argument of "--" will terminate switch parsing during initialization,
11 // interpreting subsequent tokens as non-switch arguments, regardless of prefix.
13 // There is a singleton read-only CommandLine that represents the command line
14 // that the current process was started with. It must be initialized in main().
16 #ifndef BASE_COMMAND_LINE_H_
17 #define BASE_COMMAND_LINE_H_
26 #include "base/base_export.h"
27 #include "base/strings/string_piece.h"
28 #include "build/build_config.h"
32 class DuplicateSwitchHandler;
35 class BASE_EXPORT CommandLine {
38 // The native command line string type.
39 using StringType = std::wstring;
40 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
41 using StringType = std::string;
44 using CharType = StringType::value_type;
45 using StringPieceType = base::BasicStringPiece<CharType>;
46 using StringVector = std::vector<StringType>;
47 using SwitchMap = std::map<std::string, StringType, std::less<>>;
49 // A constructor for CommandLines that only carry switches and arguments.
50 enum NoProgram { NO_PROGRAM };
51 explicit CommandLine(NoProgram no_program);
53 // Construct a new command line with |program| as argv[0].
54 explicit CommandLine(const FilePath& program);
56 // Construct a new command line from an argument list.
57 CommandLine(int argc, const CharType* const* argv);
58 explicit CommandLine(const StringVector& argv);
60 CommandLine(const CommandLine& other);
61 CommandLine& operator=(const CommandLine& other);
66 // By default this class will treat command-line arguments beginning with
67 // slashes as switches on Windows, but not other platforms.
69 // If this behavior is inappropriate for your application, you can call this
70 // function BEFORE initializing the current process' global command line
71 // object and the behavior will be the same as Posix systems (only hyphens
72 // begin switches, everything else will be an arg).
73 static void set_slash_is_not_a_switch();
75 // Normally when the CommandLine singleton is initialized it gets the command
76 // line via the GetCommandLineW API and then uses the shell32 API
77 // CommandLineToArgvW to parse the command line and convert it back to
78 // argc and argv. Tests who don't want this dependency on shell32 and need
79 // to honor the arguments passed in should use this function.
80 static void InitUsingArgvForTesting(int argc, const char* const* argv);
83 // Initialize the current process CommandLine singleton. On Windows, ignores
84 // its arguments (we instead parse GetCommandLineW() directly) because we
85 // don't trust the CRT's parsing of the command line, but it still must be
86 // called to set up the command line. Returns false if initialization has
87 // already occurred, and true otherwise. Only the caller receiving a 'true'
88 // return value should take responsibility for calling Reset.
89 static bool Init(int argc, const char* const* argv);
91 // Destroys the current process CommandLine singleton. This is necessary if
92 // you want to reset the base library to its initial state (for example, in an
93 // outer library that needs to be able to terminate, and be re-initialized).
94 // If Init is called only once, as in main(), Reset() is not necessary.
95 // Do not call this in tests. Use base::test::ScopedCommandLine instead.
98 // Get the singleton CommandLine representing the current process's
99 // command line. Note: returned value is mutable, but not thread safe;
100 // only mutate if you know what you're doing!
101 static CommandLine* ForCurrentProcess();
103 // Returns true if the CommandLine has been initialized for the given process.
104 static bool InitializedForCurrentProcess();
106 #if BUILDFLAG(IS_WIN)
107 static CommandLine FromString(StringPieceType command_line);
110 // Initialize from an argv vector.
111 void InitFromArgv(int argc, const CharType* const* argv);
112 void InitFromArgv(const StringVector& argv);
114 // Constructs and returns the represented command line string.
115 // CAUTION! This should be avoided on POSIX because quoting behavior is
117 // CAUTION! If writing a command line to the Windows registry, use
118 // GetCommandLineStringForShell() instead.
119 StringType GetCommandLineString() const;
121 #if BUILDFLAG(IS_WIN)
122 // Returns the command-line string in the proper format for the Windows shell,
123 // ending with the argument placeholder "--single-argument %1". The single-
124 // argument switch prevents unexpected parsing of arguments from other
125 // software that cannot be trusted to escape double quotes when substituting
126 // into a placeholder (e.g., "%1" insert sequences populated by the Windows
128 // NOTE: this must be used to generate the command-line string for the shell
129 // even if this command line was parsed from a string with the proper syntax,
130 // because the --single-argument switch is not preserved during parsing.
131 StringType GetCommandLineStringForShell() const;
133 // Returns the represented command-line string. Allows the use of unsafe
134 // Windows insert sequences like "%1". Only use this method if
135 // GetCommandLineStringForShell() is not adequate AND the processor inserting
136 // the arguments is known to do so securely (i.e., is not the Windows shell).
137 // If in doubt, do not use.
138 StringType GetCommandLineStringWithUnsafeInsertSequences() const;
141 // Constructs and returns the represented arguments string.
142 // CAUTION! This should be avoided on POSIX because quoting behavior is
144 StringType GetArgumentsString() const;
146 // Returns the original command line string as a vector of strings.
147 const StringVector& argv() const { return argv_; }
149 // Get and Set the program part of the command line string (the first item).
150 FilePath GetProgram() const;
151 void SetProgram(const FilePath& program);
153 // Returns true if this command line contains the given switch.
154 // Switch names must be lowercase.
155 // The second override provides an optimized version to avoid inlining codegen
156 // at every callsite to find the length of the constant and construct a
158 bool HasSwitch(StringPiece switch_string) const;
159 bool HasSwitch(const char switch_constant[]) const;
161 // Returns the value associated with the given switch. If the switch has no
162 // value or isn't present, this method returns the empty string.
163 // Switch names must be lowercase.
164 std::string GetSwitchValueASCII(StringPiece switch_string) const;
165 FilePath GetSwitchValuePath(StringPiece switch_string) const;
166 StringType GetSwitchValueNative(StringPiece switch_string) const;
168 // Get a copy of all switches, along with their values.
169 const SwitchMap& GetSwitches() const { return switches_; }
171 // Append a switch [with optional value] to the command line.
172 // Note: Switches will precede arguments regardless of appending order.
173 void AppendSwitch(StringPiece switch_string);
174 void AppendSwitchPath(StringPiece switch_string, const FilePath& path);
175 void AppendSwitchNative(StringPiece switch_string, StringPieceType value);
176 void AppendSwitchASCII(StringPiece switch_string, StringPiece value);
178 // Removes the switch that matches |switch_key_without_prefix|, regardless of
179 // prefix and value. If no such switch is present, this has no effect.
180 void RemoveSwitch(const base::StringPiece switch_key_without_prefix);
182 // Copy a set of switches (and any values) from another command line.
183 // Commonly used when launching a subprocess.
184 void CopySwitchesFrom(const CommandLine& source,
185 const char* const switches[],
188 // Get the remaining arguments to the command.
189 StringVector GetArgs() const;
191 // Append an argument to the command line. Note that the argument is quoted
192 // properly such that it is interpreted as one argument to the target command.
193 // AppendArg is primarily for ASCII; non-ASCII input is interpreted as UTF-8.
194 // Note: Switches will precede arguments regardless of appending order.
195 void AppendArg(StringPiece value);
196 void AppendArgPath(const FilePath& value);
197 void AppendArgNative(StringPieceType value);
199 // Append the switches and arguments from another command line to this one.
200 // If |include_program| is true, include |other|'s program as well.
201 void AppendArguments(const CommandLine& other, bool include_program);
203 // Insert a command before the current command.
204 // Common for debuggers, like "gdb --args".
205 void PrependWrapper(StringPieceType wrapper);
207 #if BUILDFLAG(IS_WIN)
208 // Initialize by parsing the given command line string.
209 // The program name is assumed to be the first item in the string.
210 void ParseFromString(StringPieceType command_line);
212 // Returns true if the command line had the --single-argument switch, and
213 // thus likely came from a Windows shell registration. This is only set if the
214 // command line is parsed, and is not changed after it is parsed.
215 bool HasSingleArgumentSwitch() const { return has_single_argument_switch_; }
218 // Sets a delegate that's called when we encounter a duplicate switch
219 static void SetDuplicateSwitchHandler(
220 std::unique_ptr<DuplicateSwitchHandler>);
223 // Disallow default constructor; a program name must be explicitly specified.
224 CommandLine() = delete;
225 // Allow the copy constructor. A common pattern is to copy of the current
226 // process's command line and then add some flags to it. For example:
227 // CommandLine cl(*CommandLine::ForCurrentProcess());
228 // cl.AppendSwitch(...);
230 // Append switches and arguments, keeping switches before arguments.
231 void AppendSwitchesAndArguments(const StringVector& argv);
233 // Internal version of GetArgumentsString to support allowing unsafe insert
234 // sequences in rare cases (see
235 // GetCommandLineStringWithUnsafeInsertSequences).
236 StringType GetArgumentsStringInternal(
237 bool allow_unsafe_insert_sequences) const;
239 #if BUILDFLAG(IS_WIN)
240 // Initializes by parsing |raw_command_line_string_|, treating everything
241 // after |single_arg_switch_string| + <a single character> as the command
242 // line's single argument, and dropping any arguments previously parsed. The
243 // command line must contain |single_arg_switch_string|, and the argument, if
244 // present, must be separated from |single_arg_switch_string| by one
246 // NOTE: the single-argument switch is not preserved after parsing;
247 // GetCommandLineStringForShell() must be used to reproduce the original
248 // command-line string with single-argument switch.
249 void ParseAsSingleArgument(const StringType& single_arg_switch_string);
251 // The string returned by GetCommandLineW(), to be parsed via
252 // ParseFromString(). Empty if this command line was not parsed from a string,
253 // or if ParseFromString() has finished executing.
254 StringPieceType raw_command_line_string_;
256 // Set to true if the command line had --single-argument when initially
257 // parsed. It does not change if the command line mutates after initial
259 bool has_single_argument_switch_ = false;
262 // The singleton CommandLine representing the current process's command line.
263 static CommandLine* current_process_commandline_;
265 // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
268 // Parsed-out switch keys and values.
271 // The index after the program and switches, any arguments start here.
272 ptrdiff_t begin_args_;
275 class BASE_EXPORT DuplicateSwitchHandler {
277 // out_value contains the existing value of the switch
278 virtual void ResolveDuplicate(base::StringPiece key,
279 CommandLine::StringPieceType new_value,
280 CommandLine::StringType& out_value) = 0;
281 virtual ~DuplicateSwitchHandler() = default;
286 #endif // BASE_COMMAND_LINE_H_