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.
4
5 #include "base/command_line.h"
6
7 #include <ostream>
8
9 #include "base/check_op.h"
10 #include "base/containers/contains.h"
11 #include "base/containers/span.h"
12 #include "base/debug/debugging_buildflags.h"
13 #include "base/files/file_path.h"
14 #include "base/logging.h"
15 #include "base/notreached.h"
16 #include "base/numerics/checked_math.h"
17 #include "base/ranges/algorithm.h"
18 #include "base/strings/strcat.h"
19 #include "base/strings/string_piece.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/string_tokenizer.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "build/build_config.h"
25
26 #if BUILDFLAG(IS_WIN)
27 #include <windows.h>
28
29 #include <shellapi.h>
30
31 #include "base/strings/string_util_win.h"
32 #endif // BUILDFLAG(IS_WIN)
33
34 namespace base {
35
36 CommandLine* CommandLine::current_process_commandline_ = nullptr;
37
38 namespace {
39
40 DuplicateSwitchHandler* g_duplicate_switch_handler = nullptr;
41
42 constexpr CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
43 constexpr CommandLine::CharType kSwitchValueSeparator[] =
44 FILE_PATH_LITERAL("=");
45
46 // Since we use a lazy match, make sure that longer versions (like "--") are
47 // listed before shorter versions (like "-") of similar prefixes.
48 #if BUILDFLAG(IS_WIN)
49 // By putting slash last, we can control whether it is treaded as a switch
50 // value by changing the value of switch_prefix_count to be one less than
51 // the array size.
52 constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {L"--", L"-", L"/"};
53 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
54 // Unixes don't use slash as a switch.
55 constexpr CommandLine::StringPieceType kSwitchPrefixes[] = {"--", "-"};
56 #endif
57 size_t switch_prefix_count = std::size(kSwitchPrefixes);
58
59 #if BUILDFLAG(IS_WIN)
60 // Switch string that specifies the single argument to the command line.
61 // If present, everything after this switch is interpreted as a single
62 // argument regardless of whitespace, quotes, etc. Used for launches from the
63 // Windows shell, which may have arguments with unencoded quotes that could
64 // otherwise unexpectedly be split into multiple arguments
65 // (https://crbug.com/937179).
66 constexpr CommandLine::CharType kSingleArgument[] =
67 FILE_PATH_LITERAL("single-argument");
68 #endif // BUILDFLAG(IS_WIN)
69
GetSwitchPrefixLength(CommandLine::StringPieceType string)70 size_t GetSwitchPrefixLength(CommandLine::StringPieceType string) {
71 for (size_t i = 0; i < switch_prefix_count; ++i) {
72 CommandLine::StringType prefix(kSwitchPrefixes[i]);
73 if (string.substr(0, prefix.length()) == prefix)
74 return prefix.length();
75 }
76 return 0;
77 }
78
79 // Fills in |switch_string| and |switch_value| if |string| is a switch.
80 // This will preserve the input switch prefix in the output |switch_string|.
IsSwitch(const CommandLine::StringType & string,CommandLine::StringType * switch_string,CommandLine::StringType * switch_value)81 bool IsSwitch(const CommandLine::StringType& string,
82 CommandLine::StringType* switch_string,
83 CommandLine::StringType* switch_value) {
84 switch_string->clear();
85 switch_value->clear();
86 size_t prefix_length = GetSwitchPrefixLength(string);
87 if (prefix_length == 0 || prefix_length == string.length())
88 return false;
89
90 const size_t equals_position = string.find(kSwitchValueSeparator);
91 *switch_string = string.substr(0, equals_position);
92 if (equals_position != CommandLine::StringType::npos)
93 *switch_value = string.substr(equals_position + 1);
94 return true;
95 }
96
97 // Returns true iff |string| represents a switch with key
98 // |switch_key_without_prefix|, regardless of value.
IsSwitchWithKey(CommandLine::StringPieceType string,CommandLine::StringPieceType switch_key_without_prefix)99 bool IsSwitchWithKey(CommandLine::StringPieceType string,
100 CommandLine::StringPieceType switch_key_without_prefix) {
101 size_t prefix_length = GetSwitchPrefixLength(string);
102 if (prefix_length == 0 || prefix_length == string.length())
103 return false;
104
105 const size_t equals_position = string.find(kSwitchValueSeparator);
106 return string.substr(prefix_length, equals_position - prefix_length) ==
107 switch_key_without_prefix;
108 }
109
110 #if BUILDFLAG(IS_WIN)
111 // Quotes a string as necessary for CommandLineToArgvW compatibility *on
112 // Windows*.
113 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx#parsing-c-command-line-arguments.
QuoteForCommandLineToArgvWInternal(const std::wstring & arg,bool allow_unsafe_insert_sequences)114 std::wstring QuoteForCommandLineToArgvWInternal(
115 const std::wstring& arg,
116 bool allow_unsafe_insert_sequences) {
117 // Ensures that GetCommandLineString isn't used to generate command-line
118 // strings for the Windows shell by checking for Windows insert sequences like
119 // "%1". GetCommandLineStringForShell should be used instead to get a string
120 // with the correct placeholder format for the shell.
121 DCHECK(arg.size() != 2 || arg[0] != L'%' || allow_unsafe_insert_sequences);
122
123 constexpr wchar_t kQuotableCharacters[] = L" \t\\\"";
124 if (arg.find_first_of(kQuotableCharacters) == std::wstring::npos) {
125 return arg;
126 }
127
128 std::wstring out(1, L'"');
129 for (size_t i = 0; i < arg.size(); ++i) {
130 if (arg[i] == L'\\') {
131 // Finds the extent of this run of backslashes.
132 size_t end = i + 1;
133 while (end < arg.size() && arg[end] == L'\\') {
134 ++end;
135 }
136
137 const size_t backslash_count = end - i;
138
139 // Backslashes are escaped only if the run is followed by a double quote.
140 // Since we also will end the string with a double quote, we escape for
141 // either a double quote or the end of the string.
142 const size_t backslash_multiplier =
143 (end == arg.size() || arg[end] == L'"') ? 2 : 1;
144
145 out.append(std::wstring(backslash_count * backslash_multiplier, L'\\'));
146
147 // Advances `i` to one before `end` to balance `++i` in loop.
148 i = end - 1;
149 } else if (arg[i] == L'"') {
150 out.append(LR"(\")");
151 } else {
152 out.push_back(arg[i]);
153 }
154 }
155
156 out.push_back(L'"');
157
158 return out;
159 }
160 #endif // BUILDFLAG(IS_WIN)
161
162 } // namespace
163
164 // static
SetDuplicateSwitchHandler(std::unique_ptr<DuplicateSwitchHandler> new_duplicate_switch_handler)165 void CommandLine::SetDuplicateSwitchHandler(
166 std::unique_ptr<DuplicateSwitchHandler> new_duplicate_switch_handler) {
167 delete g_duplicate_switch_handler;
168 g_duplicate_switch_handler = new_duplicate_switch_handler.release();
169 }
170
CommandLine(NoProgram no_program)171 CommandLine::CommandLine(NoProgram no_program) : argv_(1), begin_args_(1) {}
172
CommandLine(const FilePath & program)173 CommandLine::CommandLine(const FilePath& program)
174 : argv_(1),
175 begin_args_(1) {
176 SetProgram(program);
177 }
178
CommandLine(int argc,const CommandLine::CharType * const * argv)179 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
180 : argv_(1), begin_args_(1) {
181 InitFromArgv(argc, argv);
182 }
183
CommandLine(const StringVector & argv)184 CommandLine::CommandLine(const StringVector& argv)
185 : argv_(1),
186 begin_args_(1) {
187 InitFromArgv(argv);
188 }
189
190 CommandLine::CommandLine(const CommandLine& other) = default;
191
192 CommandLine& CommandLine::operator=(const CommandLine& other) = default;
193
194 CommandLine::~CommandLine() = default;
195
196 #if BUILDFLAG(IS_WIN)
197 // static
set_slash_is_not_a_switch()198 void CommandLine::set_slash_is_not_a_switch() {
199 // The last switch prefix should be slash, so adjust the size to skip it.
200 static_assert(base::make_span(kSwitchPrefixes).back() == L"/",
201 "Error: Last switch prefix is not a slash.");
202 switch_prefix_count = std::size(kSwitchPrefixes) - 1;
203 }
204
205 // static
InitUsingArgvForTesting(int argc,const char * const * argv)206 void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) {
207 DCHECK(!current_process_commandline_);
208 current_process_commandline_ = new CommandLine(NO_PROGRAM);
209 // On Windows we need to convert the command line arguments to std::wstring.
210 CommandLine::StringVector argv_vector;
211 for (int i = 0; i < argc; ++i)
212 argv_vector.push_back(UTF8ToWide(argv[i]));
213 current_process_commandline_->InitFromArgv(argv_vector);
214 }
215 #endif // BUILDFLAG(IS_WIN)
216
217 // static
Init(int argc,const char * const * argv)218 bool CommandLine::Init(int argc, const char* const* argv) {
219 if (current_process_commandline_) {
220 // If this is intentional, Reset() must be called first. If we are using
221 // the shared build mode, we have to share a single object across multiple
222 // shared libraries.
223 return false;
224 }
225
226 current_process_commandline_ = new CommandLine(NO_PROGRAM);
227 #if BUILDFLAG(IS_WIN)
228 current_process_commandline_->ParseFromString(::GetCommandLineW());
229 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
230 current_process_commandline_->InitFromArgv(argc, argv);
231 #else
232 #error Unsupported platform
233 #endif
234
235 return true;
236 }
237
238 // static
Reset()239 void CommandLine::Reset() {
240 DCHECK(current_process_commandline_);
241 delete current_process_commandline_;
242 current_process_commandline_ = nullptr;
243 }
244
245 // static
ForCurrentProcess()246 CommandLine* CommandLine::ForCurrentProcess() {
247 DCHECK(current_process_commandline_);
248 return current_process_commandline_;
249 }
250
251 // static
InitializedForCurrentProcess()252 bool CommandLine::InitializedForCurrentProcess() {
253 return !!current_process_commandline_;
254 }
255
256 #if BUILDFLAG(IS_WIN)
257 // static
FromString(StringPieceType command_line)258 CommandLine CommandLine::FromString(StringPieceType command_line) {
259 CommandLine cmd(NO_PROGRAM);
260 cmd.ParseFromString(command_line);
261 return cmd;
262 }
263 #endif // BUILDFLAG(IS_WIN)
264
InitFromArgv(int argc,const CommandLine::CharType * const * argv)265 void CommandLine::InitFromArgv(int argc,
266 const CommandLine::CharType* const* argv) {
267 StringVector new_argv;
268 for (int i = 0; i < argc; ++i)
269 new_argv.push_back(argv[i]);
270 InitFromArgv(new_argv);
271 }
272
InitFromArgv(const StringVector & argv)273 void CommandLine::InitFromArgv(const StringVector& argv) {
274 argv_ = StringVector(1);
275 switches_.clear();
276 begin_args_ = 1;
277 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
278 AppendSwitchesAndArguments(argv);
279 }
280
GetProgram() const281 FilePath CommandLine::GetProgram() const {
282 return FilePath(argv_[0]);
283 }
284
SetProgram(const FilePath & program)285 void CommandLine::SetProgram(const FilePath& program) {
286 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
287 sequence_checker_.Check();
288 #endif
289 #if BUILDFLAG(IS_WIN)
290 argv_[0] = StringType(TrimWhitespace(program.value(), TRIM_ALL));
291 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
292 TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]);
293 #else
294 #error Unsupported platform
295 #endif
296 }
297
HasSwitch(StringPiece switch_string) const298 bool CommandLine::HasSwitch(StringPiece switch_string) const {
299 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
300 return Contains(switches_, switch_string);
301 }
302
HasSwitch(const char switch_constant[]) const303 bool CommandLine::HasSwitch(const char switch_constant[]) const {
304 return HasSwitch(StringPiece(switch_constant));
305 }
306
GetSwitchValueASCII(StringPiece switch_string) const307 std::string CommandLine::GetSwitchValueASCII(StringPiece switch_string) const {
308 StringType value = GetSwitchValueNative(switch_string);
309 #if BUILDFLAG(IS_WIN)
310 if (!IsStringASCII(base::AsStringPiece16(value))) {
311 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
312 if (!IsStringASCII(value)) {
313 #endif
314 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
315 return std::string();
316 }
317 #if BUILDFLAG(IS_WIN)
318 return WideToUTF8(value);
319 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
320 return value;
321 #endif
322 }
323
324 FilePath CommandLine::GetSwitchValuePath(StringPiece switch_string) const {
325 return FilePath(GetSwitchValueNative(switch_string));
326 }
327
328 CommandLine::StringType CommandLine::GetSwitchValueNative(
329 StringPiece switch_string) const {
330 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
331 auto result = switches_.find(switch_string);
332 return result == switches_.end() ? StringType() : result->second;
333 }
334
335 void CommandLine::AppendSwitch(StringPiece switch_string) {
336 AppendSwitchNative(switch_string, StringType());
337 }
338
339 void CommandLine::AppendSwitchPath(StringPiece switch_string,
340 const FilePath& path) {
341 AppendSwitchNative(switch_string, path.value());
342 }
343
344 void CommandLine::AppendSwitchNative(StringPiece switch_string,
345 CommandLine::StringPieceType value) {
346 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
347 sequence_checker_.Check();
348 #endif
349 #if BUILDFLAG(IS_WIN)
350 const std::string switch_key = ToLowerASCII(switch_string);
351 StringType combined_switch_string(UTF8ToWide(switch_key));
352 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
353 StringPiece switch_key = switch_string;
354 StringType combined_switch_string(switch_key);
355 #endif
356 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
357 auto key = switch_key.substr(prefix_length);
358 if (g_duplicate_switch_handler) {
359 g_duplicate_switch_handler->ResolveDuplicate(key, value,
360 switches_[std::string(key)]);
361 } else {
362 switches_[std::string(key)] = StringType(value);
363 }
364
365 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
366 if (prefix_length == 0) {
367 combined_switch_string.insert(0, kSwitchPrefixes[0].data(),
368 kSwitchPrefixes[0].size());
369 }
370 if (!value.empty())
371 base::StrAppend(&combined_switch_string, {kSwitchValueSeparator, value});
372 // Append the switch and update the switches/arguments divider |begin_args_|.
373 argv_.insert(argv_.begin() + begin_args_, combined_switch_string);
374 begin_args_ = (CheckedNumeric(begin_args_) + 1).ValueOrDie();
375 }
376
377 void CommandLine::AppendSwitchASCII(StringPiece switch_string,
378 StringPiece value_string) {
379 #if BUILDFLAG(IS_WIN)
380 AppendSwitchNative(switch_string, UTF8ToWide(value_string));
381 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
382 AppendSwitchNative(switch_string, value_string);
383 #else
384 #error Unsupported platform
385 #endif
386 }
387
388 void CommandLine::RemoveSwitch(base::StringPiece switch_key_without_prefix) {
389 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
390 sequence_checker_.Check();
391 #endif
392 #if BUILDFLAG(IS_WIN)
393 StringType switch_key_native = UTF8ToWide(switch_key_without_prefix);
394 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
395 StringType switch_key_native(switch_key_without_prefix);
396 #endif
397
398 DCHECK_EQ(ToLowerASCII(switch_key_without_prefix), switch_key_without_prefix);
399 DCHECK_EQ(0u, GetSwitchPrefixLength(switch_key_native));
400 auto it = switches_.find(switch_key_without_prefix);
401 if (it == switches_.end())
402 return;
403 switches_.erase(it);
404 // Also erase from the switches section of |argv_| and update |begin_args_|
405 // accordingly.
406 // Switches in |argv_| have indices [1, begin_args_).
407 auto argv_switches_begin = argv_.begin() + 1;
408 auto argv_switches_end = argv_.begin() + begin_args_;
409 DCHECK(argv_switches_begin <= argv_switches_end);
410 DCHECK(argv_switches_end <= argv_.end());
411 auto expell = std::remove_if(argv_switches_begin, argv_switches_end,
412 [&switch_key_native](const StringType& arg) {
413 return IsSwitchWithKey(arg, switch_key_native);
414 });
415 if (expell == argv_switches_end) {
416 NOTREACHED();
417 return;
418 }
419 begin_args_ -= argv_switches_end - expell;
420 argv_.erase(expell, argv_switches_end);
421 }
422
423 void CommandLine::CopySwitchesFrom(const CommandLine& source,
424 const char* const switches[],
425 size_t count) {
426 for (size_t i = 0; i < count; ++i) {
427 if (source.HasSwitch(switches[i]))
428 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
429 }
430 }
431
432 CommandLine::StringVector CommandLine::GetArgs() const {
433 // Gather all arguments after the last switch (may include kSwitchTerminator).
434 StringVector args(argv_.begin() + begin_args_, argv_.end());
435 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
436 auto switch_terminator = ranges::find(args, kSwitchTerminator);
437 if (switch_terminator != args.end())
438 args.erase(switch_terminator);
439 return args;
440 }
441
442 void CommandLine::AppendArg(StringPiece value) {
443 #if BUILDFLAG(IS_WIN)
444 DCHECK(IsStringUTF8(value));
445 AppendArgNative(UTF8ToWide(value));
446 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
447 AppendArgNative(value);
448 #else
449 #error Unsupported platform
450 #endif
451 }
452
453 void CommandLine::AppendArgPath(const FilePath& path) {
454 AppendArgNative(path.value());
455 }
456
457 void CommandLine::AppendArgNative(StringPieceType value) {
458 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
459 sequence_checker_.Check();
460 #endif
461 argv_.push_back(StringType(value));
462 }
463
464 void CommandLine::AppendArguments(const CommandLine& other,
465 bool include_program) {
466 if (include_program)
467 SetProgram(other.GetProgram());
468 AppendSwitchesAndArguments(other.argv());
469 }
470
471 void CommandLine::PrependWrapper(StringPieceType wrapper) {
472 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
473 sequence_checker_.Check();
474 #endif
475 if (wrapper.empty())
476 return;
477 // Split the wrapper command based on whitespace (with quoting).
478 // StringPieceType does not currently work directly with StringTokenizerT.
479 using CommandLineTokenizer =
480 StringTokenizerT<StringType, StringType::const_iterator>;
481 StringType wrapper_string(wrapper);
482 CommandLineTokenizer tokenizer(wrapper_string, FILE_PATH_LITERAL(" "));
483 tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
484 std::vector<StringType> wrapper_argv;
485 while (tokenizer.GetNext())
486 wrapper_argv.emplace_back(tokenizer.token());
487
488 // Prepend the wrapper and update the switches/arguments |begin_args_|.
489 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
490 begin_args_ += wrapper_argv.size();
491 }
492
493 #if BUILDFLAG(IS_WIN)
494 void CommandLine::ParseFromString(StringPieceType command_line) {
495 command_line = TrimWhitespace(command_line, TRIM_ALL);
496 if (command_line.empty())
497 return;
498 raw_command_line_string_ = command_line;
499
500 int num_args = 0;
501 wchar_t** args = NULL;
502 // When calling CommandLineToArgvW, use the apiset if available.
503 // Doing so will bypass loading shell32.dll on Windows.
504 HMODULE downlevel_shell32_dll =
505 ::LoadLibraryEx(L"api-ms-win-downlevel-shell32-l1-1-0.dll", nullptr,
506 LOAD_LIBRARY_SEARCH_SYSTEM32);
507 if (downlevel_shell32_dll) {
508 auto command_line_to_argv_w_proc =
509 reinterpret_cast<decltype(::CommandLineToArgvW)*>(
510 ::GetProcAddress(downlevel_shell32_dll, "CommandLineToArgvW"));
511 if (command_line_to_argv_w_proc)
512 args = command_line_to_argv_w_proc(command_line.data(), &num_args);
513 } else {
514 // Since the apiset is not available, allow the delayload of shell32.dll
515 // to take place.
516 args = ::CommandLineToArgvW(command_line.data(), &num_args);
517 }
518
519 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
520 << command_line;
521 StringVector argv(args, args + num_args);
522 InitFromArgv(argv);
523 raw_command_line_string_ = StringPieceType();
524 LocalFree(args);
525
526 if (downlevel_shell32_dll)
527 ::FreeLibrary(downlevel_shell32_dll);
528 }
529
530 #endif // BUILDFLAG(IS_WIN)
531
532 void CommandLine::AppendSwitchesAndArguments(
533 const CommandLine::StringVector& argv) {
534 bool parse_switches = true;
535 #if BUILDFLAG(IS_WIN)
536 const bool is_parsed_from_string = !raw_command_line_string_.empty();
537 #endif
538 for (size_t i = 1; i < argv.size(); ++i) {
539 CommandLine::StringType arg = argv[i];
540 #if BUILDFLAG(IS_WIN)
541 arg = CommandLine::StringType(TrimWhitespace(arg, TRIM_ALL));
542 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
543 TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
544 #endif
545
546 CommandLine::StringType switch_string;
547 CommandLine::StringType switch_value;
548 parse_switches &= (arg != kSwitchTerminator);
549 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
550 #if BUILDFLAG(IS_WIN)
551 if (is_parsed_from_string &&
552 IsSwitchWithKey(switch_string, kSingleArgument)) {
553 ParseAsSingleArgument(switch_string);
554 return;
555 }
556 AppendSwitchNative(WideToUTF8(switch_string), switch_value);
557 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
558 AppendSwitchNative(switch_string, switch_value);
559 #else
560 #error Unsupported platform
561 #endif
562 } else {
563 AppendArgNative(arg);
564 }
565 }
566 }
567
568 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
569 bool allow_unsafe_insert_sequences) const {
570 StringType params;
571 // Append switches and arguments.
572 bool parse_switches = true;
573 #if BUILDFLAG(IS_WIN)
574 bool appended_single_argument_switch = false;
575 #endif
576
577 for (size_t i = 1; i < argv_.size(); ++i) {
578 StringType arg = argv_[i];
579 StringType switch_string;
580 StringType switch_value;
581 parse_switches &= arg != kSwitchTerminator;
582 if (i > 1)
583 params.append(FILE_PATH_LITERAL(" "));
584 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
585 params.append(switch_string);
586 if (!switch_value.empty()) {
587 #if BUILDFLAG(IS_WIN)
588 switch_value = QuoteForCommandLineToArgvWInternal(
589 switch_value, allow_unsafe_insert_sequences);
590 #endif
591 params.append(kSwitchValueSeparator + switch_value);
592 }
593 } else {
594 #if BUILDFLAG(IS_WIN)
595 if (has_single_argument_switch_) {
596 // Check that we don't have multiple arguments when
597 // `has_single_argument_switch_` is true.
598 DCHECK(!appended_single_argument_switch);
599 appended_single_argument_switch = true;
600 params.append(base::StrCat(
601 {kSwitchPrefixes[0], kSingleArgument, FILE_PATH_LITERAL(" ")}));
602 } else {
603 arg = QuoteForCommandLineToArgvWInternal(arg,
604 allow_unsafe_insert_sequences);
605 }
606 #endif
607 params.append(arg);
608 }
609 }
610 return params;
611 }
612
613 CommandLine::StringType CommandLine::GetCommandLineString() const {
614 StringType string(argv_[0]);
615 #if BUILDFLAG(IS_WIN)
616 string = QuoteForCommandLineToArgvWInternal(
617 string,
618 /*allow_unsafe_insert_sequences=*/false);
619 #endif
620 StringType params(GetArgumentsString());
621 if (!params.empty()) {
622 string.append(FILE_PATH_LITERAL(" "));
623 string.append(params);
624 }
625 return string;
626 }
627
628 #if BUILDFLAG(IS_WIN)
629 // static
630 std::wstring CommandLine::QuoteForCommandLineToArgvW(const std::wstring& arg) {
631 return QuoteForCommandLineToArgvWInternal(
632 arg, /*allow_unsafe_insert_sequences=*/false);
633 }
634
635 // NOTE: this function is used to set Chrome's open command in the registry
636 // during update. Any change to the syntax must be compatible with the prior
637 // version (i.e., any new syntax must be understood by older browsers expecting
638 // the old syntax, and the new browser must still handle the old syntax), as
639 // old versions are likely to persist, e.g., immediately after background
640 // update, when parsing command lines for other channels, when uninstalling web
641 // applications installed using the old syntax, etc.
642 CommandLine::StringType CommandLine::GetCommandLineStringForShell() const {
643 DCHECK(GetArgs().empty());
644 StringType command_line_string = GetCommandLineString();
645 return command_line_string + FILE_PATH_LITERAL(" ") +
646 StringType(kSwitchPrefixes[0]) + kSingleArgument +
647 FILE_PATH_LITERAL(" %1");
648 }
649
650 CommandLine::StringType
651 CommandLine::GetCommandLineStringWithUnsafeInsertSequences() const {
652 StringType string(argv_[0]);
653 string = QuoteForCommandLineToArgvWInternal(
654 string,
655 /*allow_unsafe_insert_sequences=*/true);
656 StringType params(
657 GetArgumentsStringInternal(/*allow_unsafe_insert_sequences=*/true));
658 if (!params.empty()) {
659 string.append(FILE_PATH_LITERAL(" "));
660 string.append(params);
661 }
662 return string;
663 }
664 #endif // BUILDFLAG(IS_WIN)
665
666 CommandLine::StringType CommandLine::GetArgumentsString() const {
667 return GetArgumentsStringInternal(/*allow_unsafe_insert_sequences=*/false);
668 }
669
670 #if BUILDFLAG(IS_WIN)
671 void CommandLine::ParseAsSingleArgument(
672 const CommandLine::StringType& single_arg_switch) {
673 DCHECK(!raw_command_line_string_.empty());
674
675 // Remove any previously parsed arguments.
676 argv_.resize(static_cast<size_t>(begin_args_));
677
678 // Locate "--single-argument" in the process's raw command line. Results are
679 // unpredictable if "--single-argument" appears as part of a previous
680 // argument or switch.
681 const size_t single_arg_switch_position =
682 raw_command_line_string_.find(single_arg_switch);
683 DCHECK_NE(single_arg_switch_position, StringType::npos);
684
685 // Append the portion of the raw command line that starts one character past
686 // "--single-argument" as the one and only argument, or return if no
687 // argument is present.
688 const size_t arg_position =
689 single_arg_switch_position + single_arg_switch.length() + 1;
690 if (arg_position >= raw_command_line_string_.length())
691 return;
692 has_single_argument_switch_ = true;
693 const StringPieceType arg = raw_command_line_string_.substr(arg_position);
694 if (!arg.empty()) {
695 AppendArgNative(arg);
696 }
697 }
698 #endif // BUILDFLAG(IS_WIN)
699
700 void CommandLine::DetachFromCurrentSequence() {
701 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
702 sequence_checker_.Detach();
703 #endif // BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
704 }
705
706 } // namespace base
707