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