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/containers/span.h"
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/notreached.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_tokenizer.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "build/build_config.h"
25 #include "base/strings/string_util_win.h"
30 CommandLine* CommandLine::current_process_commandline_ = nullptr;
34 constexpr CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
35 constexpr CommandLine::CharType kSwitchValueSeparator[] =
36 FILE_PATH_LITERAL("=");
38 // Since we use a lazy match, make sure that longer versions (like "--") are
39 // listed before shorter versions (like "-") of similar prefixes.
41 // By putting slash last, we can control whether it is treaded as a switch
42 // value by changing the value of switch_prefix_count to be one less than
44 constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {L"--", L"-", L"/"};
45 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
46 // Unixes don't use slash as a switch.
47 constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {"--", "-"};
49 size_t switch_prefix_count = base::size(kSwitchPrefixes);
51 size_t GetSwitchPrefixLength(CommandLine::StringPieceType string) {
52 for (size_t i = 0; i < switch_prefix_count; ++i) {
53 CommandLine::StringType prefix(kSwitchPrefixes[i]);
54 if (string.substr(0, prefix.length()) == prefix)
55 return prefix.length();
60 // Fills in |switch_string| and |switch_value| if |string| is a switch.
61 // This will preserve the input switch prefix in the output |switch_string|.
62 bool IsSwitch(const CommandLine::StringType& string,
63 CommandLine::StringType* switch_string,
64 CommandLine::StringType* switch_value) {
65 switch_string->clear();
66 switch_value->clear();
67 size_t prefix_length = GetSwitchPrefixLength(string);
68 if (prefix_length == 0 || prefix_length == string.length())
71 const size_t equals_position = string.find(kSwitchValueSeparator);
72 *switch_string = string.substr(0, equals_position);
73 if (equals_position != CommandLine::StringType::npos)
74 *switch_value = string.substr(equals_position + 1);
78 // Returns true iff |string| represents a switch with key
79 // |switch_key_without_prefix|, regardless of value.
80 bool IsSwitchWithKey(CommandLine::StringPieceType string,
81 CommandLine::StringPieceType switch_key_without_prefix) {
82 size_t prefix_length = GetSwitchPrefixLength(string);
83 if (prefix_length == 0 || prefix_length == string.length())
86 const size_t equals_position = string.find(kSwitchValueSeparator);
87 return string.substr(prefix_length, equals_position - prefix_length) ==
88 switch_key_without_prefix;
91 // Append switches and arguments, keeping switches before arguments.
92 void AppendSwitchesAndArguments(CommandLine* command_line,
93 const CommandLine::StringVector& argv) {
94 bool parse_switches = true;
95 for (size_t i = 1; i < argv.size(); ++i) {
96 CommandLine::StringType arg = argv[i];
98 arg = CommandLine::StringType(TrimWhitespace(arg, TRIM_ALL));
99 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
100 TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
103 CommandLine::StringType switch_string;
104 CommandLine::StringType switch_value;
105 parse_switches &= (arg != kSwitchTerminator);
106 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
108 command_line->AppendSwitchNative(WideToUTF8(switch_string), switch_value);
109 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
110 command_line->AppendSwitchNative(switch_string, switch_value);
112 #error Unsupported platform
115 command_line->AppendArgNative(arg);
121 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
122 std::wstring QuoteForCommandLineToArgvW(const std::wstring& arg,
123 bool quote_placeholders) {
124 // We follow the quoting rules of CommandLineToArgvW.
125 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
126 std::wstring quotable_chars(L" \\\"");
127 // We may also be required to quote '%', which is commonly used in a command
128 // line as a placeholder. (It may be substituted for a string with spaces.)
129 if (quote_placeholders)
130 quotable_chars.push_back('%');
131 if (arg.find_first_of(quotable_chars) == std::wstring::npos) {
132 // No quoting necessary.
138 for (size_t i = 0; i < arg.size(); ++i) {
139 if (arg[i] == '\\') {
140 // Find the extent of this run of backslashes.
141 size_t start = i, end = start + 1;
142 for (; end < arg.size() && arg[end] == '\\'; ++end) {}
143 size_t backslash_count = end - start;
145 // Backslashes are escapes only if the run is followed by a double quote.
146 // Since we also will end the string with a double quote, we escape for
147 // either a double quote or the end of the string.
148 if (end == arg.size() || arg[end] == '"') {
149 // To quote, we need to output 2x as many backslashes.
150 backslash_count *= 2;
152 for (size_t j = 0; j < backslash_count; ++j)
155 // Advance i to one before the end to balance i++ in loop.
157 } else if (arg[i] == '"') {
161 out.push_back(arg[i]);
172 CommandLine::CommandLine(NoProgram no_program)
177 CommandLine::CommandLine(const FilePath& program)
183 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
186 InitFromArgv(argc, argv);
189 CommandLine::CommandLine(const StringVector& argv)
195 CommandLine::CommandLine(const CommandLine& other) = default;
197 CommandLine& CommandLine::operator=(const CommandLine& other) = default;
199 CommandLine::~CommandLine() = default;
203 void CommandLine::set_slash_is_not_a_switch() {
204 // The last switch prefix should be slash, so adjust the size to skip it.
205 static_assert(base::make_span(kSwitchPrefixes).back() == L"/",
206 "Error: Last switch prefix is not a slash.");
207 switch_prefix_count = base::size(kSwitchPrefixes) - 1;
211 void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) {
212 DCHECK(!current_process_commandline_);
213 current_process_commandline_ = new CommandLine(NO_PROGRAM);
214 // On Windows we need to convert the command line arguments to std::wstring.
215 CommandLine::StringVector argv_vector;
216 for (int i = 0; i < argc; ++i)
217 argv_vector.push_back(UTF8ToWide(argv[i]));
218 current_process_commandline_->InitFromArgv(argv_vector);
223 bool CommandLine::Init(int argc, const char* const* argv) {
224 if (current_process_commandline_) {
225 // If this is intentional, Reset() must be called first. If we are using
226 // the shared build mode, we have to share a single object across multiple
231 current_process_commandline_ = new CommandLine(NO_PROGRAM);
233 current_process_commandline_->ParseFromString(::GetCommandLineW());
234 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
235 current_process_commandline_->InitFromArgv(argc, argv);
237 #error Unsupported platform
244 void CommandLine::Reset() {
245 DCHECK(current_process_commandline_);
246 delete current_process_commandline_;
247 current_process_commandline_ = nullptr;
251 CommandLine* CommandLine::ForCurrentProcess() {
252 DCHECK(current_process_commandline_);
253 return current_process_commandline_;
257 bool CommandLine::InitializedForCurrentProcess() {
258 return !!current_process_commandline_;
263 CommandLine CommandLine::FromString(StringPieceType command_line) {
264 CommandLine cmd(NO_PROGRAM);
265 cmd.ParseFromString(command_line);
270 void CommandLine::InitFromArgv(int argc,
271 const CommandLine::CharType* const* argv) {
272 StringVector new_argv;
273 for (int i = 0; i < argc; ++i)
274 new_argv.push_back(argv[i]);
275 InitFromArgv(new_argv);
278 void CommandLine::InitFromArgv(const StringVector& argv) {
279 argv_ = StringVector(1);
282 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
283 AppendSwitchesAndArguments(this, argv);
286 FilePath CommandLine::GetProgram() const {
287 return FilePath(argv_[0]);
290 void CommandLine::SetProgram(const FilePath& program) {
292 argv_[0] = StringType(TrimWhitespace(program.value(), TRIM_ALL));
293 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
294 TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]);
296 #error Unsupported platform
300 bool CommandLine::HasSwitch(const StringPiece& switch_string) const {
301 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
302 return Contains(switches_, switch_string);
305 bool CommandLine::HasSwitch(const char switch_constant[]) const {
306 return HasSwitch(StringPiece(switch_constant));
309 std::string CommandLine::GetSwitchValueASCII(
310 const StringPiece& switch_string) const {
311 StringType value = GetSwitchValueNative(switch_string);
313 if (!IsStringASCII(base::AsStringPiece16(value))) {
314 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
315 if (!IsStringASCII(value)) {
317 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
318 return std::string();
321 return WideToUTF8(value);
322 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
327 FilePath CommandLine::GetSwitchValuePath(
328 const StringPiece& switch_string) const {
329 return FilePath(GetSwitchValueNative(switch_string));
332 CommandLine::StringType CommandLine::GetSwitchValueNative(
333 const StringPiece& switch_string) const {
334 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
335 auto result = switches_.find(switch_string);
336 return result == switches_.end() ? StringType() : result->second;
339 void CommandLine::AppendSwitch(const std::string& switch_string) {
340 AppendSwitchNative(switch_string, StringType());
343 void CommandLine::AppendSwitchPath(const std::string& switch_string,
344 const FilePath& path) {
345 AppendSwitchNative(switch_string, path.value());
348 void CommandLine::AppendSwitchNative(const std::string& switch_string,
349 const CommandLine::StringType& value) {
351 const std::string switch_key = ToLowerASCII(switch_string);
352 StringType combined_switch_string(UTF8ToWide(switch_key));
353 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
354 const std::string& switch_key = switch_string;
355 StringType combined_switch_string(switch_key);
357 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
359 switches_.insert(make_pair(switch_key.substr(prefix_length), value));
360 if (!insertion.second)
361 insertion.first->second = value;
362 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
363 if (prefix_length == 0) {
364 combined_switch_string.insert(0, kSwitchPrefixes[0].data(),
365 kSwitchPrefixes[0].size());
368 combined_switch_string += kSwitchValueSeparator + value;
369 // Append the switch and update the switches/arguments divider |begin_args_|.
370 argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
373 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
374 const std::string& value_string) {
376 AppendSwitchNative(switch_string, UTF8ToWide(value_string));
377 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
378 AppendSwitchNative(switch_string, value_string);
380 #error Unsupported platform
384 void CommandLine::RemoveSwitch(base::StringPiece switch_key_without_prefix) {
386 StringType switch_key_native = UTF8ToWide(switch_key_without_prefix);
387 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
388 StringType switch_key_native = switch_key_without_prefix.as_string();
391 DCHECK_EQ(ToLowerASCII(switch_key_without_prefix), switch_key_without_prefix);
392 DCHECK_EQ(0u, GetSwitchPrefixLength(switch_key_native));
393 size_t erased_from_switches =
394 switches_.erase(switch_key_without_prefix.as_string());
395 DCHECK(erased_from_switches <= 1);
396 if (!erased_from_switches)
399 // Also erase from the switches section of |argv_| and update |begin_args_|
401 // Switches in |argv_| have indices [1, begin_args_).
402 auto argv_switches_begin = argv_.begin() + 1;
403 auto argv_switches_end = argv_.begin() + begin_args_;
404 DCHECK(argv_switches_begin <= argv_switches_end);
405 DCHECK(argv_switches_end <= argv_.end());
406 auto expell = std::remove_if(argv_switches_begin, argv_switches_end,
407 [&switch_key_native](const StringType& arg) {
408 return IsSwitchWithKey(arg, switch_key_native);
410 if (expell == argv_switches_end) {
414 begin_args_ -= argv_switches_end - expell;
415 argv_.erase(expell, argv_switches_end);
418 void CommandLine::CopySwitchesFrom(const CommandLine& source,
419 const char* const switches[],
421 for (size_t i = 0; i < count; ++i) {
422 if (source.HasSwitch(switches[i]))
423 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
427 CommandLine::StringVector CommandLine::GetArgs() const {
428 // Gather all arguments after the last switch (may include kSwitchTerminator).
429 StringVector args(argv_.begin() + begin_args_, argv_.end());
430 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
431 auto switch_terminator =
432 std::find(args.begin(), args.end(), kSwitchTerminator);
433 if (switch_terminator != args.end())
434 args.erase(switch_terminator);
438 void CommandLine::AppendArg(const std::string& value) {
440 DCHECK(IsStringUTF8(value));
441 AppendArgNative(UTF8ToWide(value));
442 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
443 AppendArgNative(value);
445 #error Unsupported platform
449 void CommandLine::AppendArgPath(const FilePath& path) {
450 AppendArgNative(path.value());
453 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
454 argv_.push_back(value);
457 void CommandLine::AppendArguments(const CommandLine& other,
458 bool include_program) {
460 SetProgram(other.GetProgram());
461 AppendSwitchesAndArguments(this, other.argv());
464 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
467 // Split the wrapper command based on whitespace (with quoting).
468 using CommandLineTokenizer =
469 StringTokenizerT<StringType, StringType::const_iterator>;
470 CommandLineTokenizer tokenizer(wrapper, FILE_PATH_LITERAL(" "));
471 tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
472 std::vector<StringType> wrapper_argv;
473 while (tokenizer.GetNext())
474 wrapper_argv.emplace_back(tokenizer.token());
476 // Prepend the wrapper and update the switches/arguments |begin_args_|.
477 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
478 begin_args_ += wrapper_argv.size();
482 void CommandLine::ParseFromString(StringPieceType command_line) {
483 command_line = TrimWhitespace(command_line, TRIM_ALL);
484 if (command_line.empty())
488 wchar_t** args = NULL;
489 // When calling CommandLineToArgvW, use the apiset if available.
490 // Doing so will bypass loading shell32.dll on Win8+.
491 HMODULE downlevel_shell32_dll =
492 ::LoadLibraryEx(L"api-ms-win-downlevel-shell32-l1-1-0.dll", nullptr,
493 LOAD_LIBRARY_SEARCH_SYSTEM32);
494 if (downlevel_shell32_dll) {
495 auto command_line_to_argv_w_proc =
496 reinterpret_cast<decltype(::CommandLineToArgvW)*>(
497 ::GetProcAddress(downlevel_shell32_dll, "CommandLineToArgvW"));
498 if (command_line_to_argv_w_proc)
499 args = command_line_to_argv_w_proc(command_line.data(), &num_args);
501 // Since the apiset is not available, allow the delayload of shell32.dll
503 args = ::CommandLineToArgvW(command_line.data(), &num_args);
506 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
508 StringVector argv(args, args + num_args);
512 if (downlevel_shell32_dll)
513 ::FreeLibrary(downlevel_shell32_dll);
517 CommandLine::StringType CommandLine::GetCommandLineStringInternal(
518 bool quote_placeholders) const {
519 StringType string(argv_[0]);
521 string = QuoteForCommandLineToArgvW(string, quote_placeholders);
523 StringType params(GetArgumentsStringInternal(quote_placeholders));
524 if (!params.empty()) {
525 string.append(FILE_PATH_LITERAL(" "));
526 string.append(params);
531 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
532 bool quote_placeholders) const {
534 // Append switches and arguments.
535 bool parse_switches = true;
536 for (size_t i = 1; i < argv_.size(); ++i) {
537 StringType arg = argv_[i];
538 StringType switch_string;
539 StringType switch_value;
540 parse_switches &= arg != kSwitchTerminator;
542 params.append(FILE_PATH_LITERAL(" "));
543 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
544 params.append(switch_string);
545 if (!switch_value.empty()) {
548 QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
550 params.append(kSwitchValueSeparator + switch_value);
554 arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);