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.
5 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/logging.h"
12 #include "base/macros.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_tokenizer.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "build/build_config.h"
27 CommandLine* CommandLine::current_process_commandline_ = nullptr;
31 const CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
32 const CommandLine::CharType kSwitchValueSeparator[] = FILE_PATH_LITERAL("=");
34 // Since we use a lazy match, make sure that longer versions (like "--") are
35 // listed before shorter versions (like "-") of similar prefixes.
37 // By putting slash last, we can control whether it is treaded as a switch
38 // value by changing the value of switch_prefix_count to be one less than
40 const CommandLine::CharType* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
41 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
42 // Unixes don't use slash as a switch.
43 const CommandLine::CharType* const kSwitchPrefixes[] = {"--", "-"};
45 size_t switch_prefix_count = arraysize(kSwitchPrefixes);
47 size_t GetSwitchPrefixLength(const CommandLine::StringType& string) {
48 for (size_t i = 0; i < switch_prefix_count; ++i) {
49 CommandLine::StringType prefix(kSwitchPrefixes[i]);
50 if (string.compare(0, prefix.length(), prefix) == 0)
51 return prefix.length();
56 // Fills in |switch_string| and |switch_value| if |string| is a switch.
57 // This will preserve the input switch prefix in the output |switch_string|.
58 bool IsSwitch(const CommandLine::StringType& string,
59 CommandLine::StringType* switch_string,
60 CommandLine::StringType* switch_value) {
61 switch_string->clear();
62 switch_value->clear();
63 size_t prefix_length = GetSwitchPrefixLength(string);
64 if (prefix_length == 0 || prefix_length == string.length())
67 const size_t equals_position = string.find(kSwitchValueSeparator);
68 *switch_string = string.substr(0, equals_position);
69 if (equals_position != CommandLine::StringType::npos)
70 *switch_value = string.substr(equals_position + 1);
74 // Append switches and arguments, keeping switches before arguments.
75 void AppendSwitchesAndArguments(CommandLine* command_line,
76 const CommandLine::StringVector& argv) {
77 bool parse_switches = true;
78 for (size_t i = 1; i < argv.size(); ++i) {
79 CommandLine::StringType arg = argv[i];
81 TrimWhitespace(arg, TRIM_ALL, &arg);
82 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
83 TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
86 CommandLine::StringType switch_string;
87 CommandLine::StringType switch_value;
88 parse_switches &= (arg != kSwitchTerminator);
89 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
91 command_line->AppendSwitchNative(UTF16ToASCII(switch_string),
93 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
94 command_line->AppendSwitchNative(switch_string, switch_value);
96 #error Unsupported platform
99 command_line->AppendArgNative(arg);
105 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
106 string16 QuoteForCommandLineToArgvW(const string16& arg,
107 bool quote_placeholders) {
108 // We follow the quoting rules of CommandLineToArgvW.
109 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
110 string16 quotable_chars(L" \\\"");
111 // We may also be required to quote '%', which is commonly used in a command
112 // line as a placeholder. (It may be substituted for a string with spaces.)
113 if (quote_placeholders)
114 quotable_chars.push_back(L'%');
115 if (arg.find_first_of(quotable_chars) == string16::npos) {
116 // No quoting necessary.
122 for (size_t i = 0; i < arg.size(); ++i) {
123 if (arg[i] == '\\') {
124 // Find the extent of this run of backslashes.
125 size_t start = i, end = start + 1;
126 for (; end < arg.size() && arg[end] == '\\'; ++end) {}
127 size_t backslash_count = end - start;
129 // Backslashes are escapes only if the run is followed by a double quote.
130 // Since we also will end the string with a double quote, we escape for
131 // either a double quote or the end of the string.
132 if (end == arg.size() || arg[end] == '"') {
133 // To quote, we need to output 2x as many backslashes.
134 backslash_count *= 2;
136 for (size_t j = 0; j < backslash_count; ++j)
139 // Advance i to one before the end to balance i++ in loop.
141 } else if (arg[i] == '"') {
145 out.push_back(arg[i]);
156 CommandLine::CommandLine(NoProgram no_program)
161 CommandLine::CommandLine(const FilePath& program)
167 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
170 InitFromArgv(argc, argv);
173 CommandLine::CommandLine(const StringVector& argv)
179 CommandLine::CommandLine(const CommandLine& other) = default;
181 CommandLine& CommandLine::operator=(const CommandLine& other) = default;
183 CommandLine::~CommandLine() = default;
187 void CommandLine::set_slash_is_not_a_switch() {
188 // The last switch prefix should be slash, so adjust the size to skip it.
189 DCHECK_EQ(wcscmp(kSwitchPrefixes[arraysize(kSwitchPrefixes) - 1], L"/"), 0);
190 switch_prefix_count = arraysize(kSwitchPrefixes) - 1;
194 void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) {
195 DCHECK(!current_process_commandline_);
196 current_process_commandline_ = new CommandLine(NO_PROGRAM);
197 // On Windows we need to convert the command line arguments to string16.
198 base::CommandLine::StringVector argv_vector;
199 for (int i = 0; i < argc; ++i)
200 argv_vector.push_back(UTF8ToUTF16(argv[i]));
201 current_process_commandline_->InitFromArgv(argv_vector);
206 bool CommandLine::Init(int argc, const char* const* argv) {
207 if (current_process_commandline_) {
208 // If this is intentional, Reset() must be called first. If we are using
209 // the shared build mode, we have to share a single object across multiple
214 current_process_commandline_ = new CommandLine(NO_PROGRAM);
216 current_process_commandline_->ParseFromString(::GetCommandLineW());
217 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
218 current_process_commandline_->InitFromArgv(argc, argv);
220 #error Unsupported platform
227 void CommandLine::Reset() {
228 DCHECK(current_process_commandline_);
229 delete current_process_commandline_;
230 current_process_commandline_ = nullptr;
234 CommandLine* CommandLine::ForCurrentProcess() {
235 DCHECK(current_process_commandline_);
236 return current_process_commandline_;
240 bool CommandLine::InitializedForCurrentProcess() {
241 return !!current_process_commandline_;
246 CommandLine CommandLine::FromString(const string16& command_line) {
247 CommandLine cmd(NO_PROGRAM);
248 cmd.ParseFromString(command_line);
253 void CommandLine::InitFromArgv(int argc,
254 const CommandLine::CharType* const* argv) {
255 StringVector new_argv;
256 for (int i = 0; i < argc; ++i)
257 new_argv.push_back(argv[i]);
258 InitFromArgv(new_argv);
261 void CommandLine::InitFromArgv(const StringVector& argv) {
262 argv_ = StringVector(1);
265 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
266 AppendSwitchesAndArguments(this, argv);
269 FilePath CommandLine::GetProgram() const {
270 return FilePath(argv_[0]);
273 void CommandLine::SetProgram(const FilePath& program) {
275 TrimWhitespace(program.value(), TRIM_ALL, &argv_[0]);
276 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
277 TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]);
279 #error Unsupported platform
283 bool CommandLine::HasSwitch(const base::StringPiece& switch_string) const {
284 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
285 return ContainsKey(switches_, switch_string);
288 bool CommandLine::HasSwitch(const char switch_constant[]) const {
289 return HasSwitch(base::StringPiece(switch_constant));
292 std::string CommandLine::GetSwitchValueASCII(
293 const base::StringPiece& switch_string) const {
294 StringType value = GetSwitchValueNative(switch_string);
295 if (!IsStringASCII(value)) {
296 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
297 return std::string();
300 return UTF16ToASCII(value);
301 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
306 FilePath CommandLine::GetSwitchValuePath(
307 const base::StringPiece& switch_string) const {
308 return FilePath(GetSwitchValueNative(switch_string));
311 CommandLine::StringType CommandLine::GetSwitchValueNative(
312 const base::StringPiece& switch_string) const {
313 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
314 auto result = switches_.find(switch_string);
315 return result == switches_.end() ? StringType() : result->second;
318 void CommandLine::AppendSwitch(const std::string& switch_string) {
319 AppendSwitchNative(switch_string, StringType());
322 void CommandLine::AppendSwitchPath(const std::string& switch_string,
323 const FilePath& path) {
324 AppendSwitchNative(switch_string, path.value());
327 void CommandLine::AppendSwitchNative(const std::string& switch_string,
328 const CommandLine::StringType& value) {
330 const std::string switch_key = ToLowerASCII(switch_string);
331 StringType combined_switch_string(ASCIIToUTF16(switch_key));
332 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
333 const std::string& switch_key = switch_string;
334 StringType combined_switch_string(switch_key);
336 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
338 switches_.insert(make_pair(switch_key.substr(prefix_length), value));
339 if (!insertion.second)
340 insertion.first->second = value;
341 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
342 if (prefix_length == 0)
343 combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
345 combined_switch_string += kSwitchValueSeparator + value;
346 // Append the switch and update the switches/arguments divider |begin_args_|.
347 argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
350 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
351 const std::string& value_string) {
353 AppendSwitchNative(switch_string, ASCIIToUTF16(value_string));
354 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
355 AppendSwitchNative(switch_string, value_string);
357 #error Unsupported platform
361 void CommandLine::CopySwitchesFrom(const CommandLine& source,
362 const char* const switches[],
364 for (size_t i = 0; i < count; ++i) {
365 if (source.HasSwitch(switches[i]))
366 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
370 CommandLine::StringVector CommandLine::GetArgs() const {
371 // Gather all arguments after the last switch (may include kSwitchTerminator).
372 StringVector args(argv_.begin() + begin_args_, argv_.end());
373 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
374 StringVector::iterator switch_terminator =
375 std::find(args.begin(), args.end(), kSwitchTerminator);
376 if (switch_terminator != args.end())
377 args.erase(switch_terminator);
381 void CommandLine::AppendArg(const std::string& value) {
383 DCHECK(IsStringUTF8(value));
384 AppendArgNative(UTF8ToWide(value));
385 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
386 AppendArgNative(value);
388 #error Unsupported platform
392 void CommandLine::AppendArgPath(const FilePath& path) {
393 AppendArgNative(path.value());
396 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
397 argv_.push_back(value);
400 void CommandLine::AppendArguments(const CommandLine& other,
401 bool include_program) {
403 SetProgram(other.GetProgram());
404 AppendSwitchesAndArguments(this, other.argv());
407 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
410 // Split the wrapper command based on whitespace (with quoting).
411 using CommandLineTokenizer =
412 StringTokenizerT<StringType, StringType::const_iterator>;
413 CommandLineTokenizer tokenizer(wrapper, FILE_PATH_LITERAL(" "));
414 tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
415 std::vector<StringType> wrapper_argv;
416 while (tokenizer.GetNext())
417 wrapper_argv.emplace_back(tokenizer.token());
419 // Prepend the wrapper and update the switches/arguments |begin_args_|.
420 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
421 begin_args_ += wrapper_argv.size();
425 void CommandLine::ParseFromString(const string16& command_line) {
426 string16 command_line_string;
427 TrimWhitespace(command_line, TRIM_ALL, &command_line_string);
428 if (command_line_string.empty())
432 wchar_t** args = NULL;
433 args = ::CommandLineToArgvW(command_line_string.c_str(), &num_args);
435 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
436 << UTF16ToUTF8(command_line);
437 InitFromArgv(num_args, args);
442 CommandLine::StringType CommandLine::GetCommandLineStringInternal(
443 bool quote_placeholders) const {
444 StringType string(argv_[0]);
446 string = QuoteForCommandLineToArgvW(string, quote_placeholders);
448 StringType params(GetArgumentsStringInternal(quote_placeholders));
449 if (!params.empty()) {
450 string.append(StringType(FILE_PATH_LITERAL(" ")));
451 string.append(params);
456 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
457 bool quote_placeholders) const {
459 // Append switches and arguments.
460 bool parse_switches = true;
461 for (size_t i = 1; i < argv_.size(); ++i) {
462 StringType arg = argv_[i];
463 StringType switch_string;
464 StringType switch_value;
465 parse_switches &= arg != kSwitchTerminator;
467 params.append(StringType(FILE_PATH_LITERAL(" ")));
468 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
469 params.append(switch_string);
470 if (!switch_value.empty()) {
473 QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
475 params.append(kSwitchValueSeparator + switch_value);
479 arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);