command_line.h 12 KB

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