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 #include <string_view>
9
10 #include "base/check_op.h"
11 #include "base/containers/contains.h"
12 #include "base/containers/span.h"
13 #include "base/debug/debugging_buildflags.h"
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "base/notreached.h"
17 #include "base/numerics/checked_math.h"
18 #include "base/ranges/algorithm.h"
19 #include "base/strings/strcat.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;
CommandLine(CommandLine && other)191 CommandLine::CommandLine(CommandLine&& other) noexcept
192 :
193 #if BUILDFLAG(IS_WIN)
194 raw_command_line_string_(
195 std::exchange(other.raw_command_line_string_, StringPieceType())),
196 has_single_argument_switch_(
197 std::exchange(other.has_single_argument_switch_, false)),
198 #endif // BUILDFLAG(IS_WIN)
199 argv_(std::exchange(other.argv_, StringVector(1))),
200 switches_(std::move(other.switches_)),
201 begin_args_(std::exchange(other.begin_args_, 1)) {
202 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
203 other.sequence_checker_.Detach();
204 #endif
205 }
206 CommandLine& CommandLine::operator=(const CommandLine& other) = default;
operator =(CommandLine && other)207 CommandLine& CommandLine::operator=(CommandLine&& other) noexcept {
208 #if BUILDFLAG(IS_WIN)
209 raw_command_line_string_ =
210 std::exchange(other.raw_command_line_string_, StringPieceType());
211 has_single_argument_switch_ =
212 std::exchange(other.has_single_argument_switch_, false);
213 #endif // BUILDFLAG(IS_WIN)
214 argv_ = std::exchange(other.argv_, StringVector(1));
215 switches_ = std::move(other.switches_);
216 begin_args_ = std::exchange(other.begin_args_, 1);
217 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
218 other.sequence_checker_.Detach();
219 #endif
220 return *this;
221 }
222 CommandLine::~CommandLine() = default;
223
224 #if BUILDFLAG(IS_WIN)
225 // static
set_slash_is_not_a_switch()226 void CommandLine::set_slash_is_not_a_switch() {
227 // The last switch prefix should be slash, so adjust the size to skip it.
228 static_assert(base::make_span(kSwitchPrefixes).back() == L"/",
229 "Error: Last switch prefix is not a slash.");
230 switch_prefix_count = std::size(kSwitchPrefixes) - 1;
231 }
232
233 // static
InitUsingArgvForTesting(int argc,const char * const * argv)234 void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) {
235 DCHECK(!current_process_commandline_);
236 current_process_commandline_ = new CommandLine(NO_PROGRAM);
237 // On Windows we need to convert the command line arguments to std::wstring.
238 CommandLine::StringVector argv_vector;
239 for (int i = 0; i < argc; ++i)
240 argv_vector.push_back(UTF8ToWide(argv[i]));
241 current_process_commandline_->InitFromArgv(argv_vector);
242 }
243 #endif // BUILDFLAG(IS_WIN)
244
245 // static
Init(int argc,const char * const * argv)246 bool CommandLine::Init(int argc, const char* const* argv) {
247 if (current_process_commandline_) {
248 // If this is intentional, Reset() must be called first. If we are using
249 // the shared build mode, we have to share a single object across multiple
250 // shared libraries.
251 return false;
252 }
253
254 current_process_commandline_ = new CommandLine(NO_PROGRAM);
255 #if BUILDFLAG(IS_WIN)
256 current_process_commandline_->ParseFromString(::GetCommandLineW());
257 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
258 current_process_commandline_->InitFromArgv(argc, argv);
259 #else
260 #error Unsupported platform
261 #endif
262
263 return true;
264 }
265
266 // static
Reset()267 void CommandLine::Reset() {
268 DCHECK(current_process_commandline_);
269 delete current_process_commandline_;
270 current_process_commandline_ = nullptr;
271 }
272
273 // static
ForCurrentProcess()274 CommandLine* CommandLine::ForCurrentProcess() {
275 DCHECK(current_process_commandline_);
276 return current_process_commandline_;
277 }
278
279 // static
InitializedForCurrentProcess()280 bool CommandLine::InitializedForCurrentProcess() {
281 return !!current_process_commandline_;
282 }
283
284 // static
FromArgvWithoutProgram(const StringVector & argv)285 CommandLine CommandLine::FromArgvWithoutProgram(const StringVector& argv) {
286 CommandLine cmd(NO_PROGRAM);
287 cmd.AppendSwitchesAndArguments(argv);
288 return cmd;
289 }
290
291 #if BUILDFLAG(IS_WIN)
292 // static
FromString(StringPieceType command_line)293 CommandLine CommandLine::FromString(StringPieceType command_line) {
294 CommandLine cmd(NO_PROGRAM);
295 cmd.ParseFromString(command_line);
296 return cmd;
297 }
298 #endif // BUILDFLAG(IS_WIN)
299
InitFromArgv(int argc,const CommandLine::CharType * const * argv)300 void CommandLine::InitFromArgv(int argc,
301 const CommandLine::CharType* const* argv) {
302 StringVector new_argv;
303 for (int i = 0; i < argc; ++i)
304 new_argv.push_back(argv[i]);
305 InitFromArgv(new_argv);
306 }
307
InitFromArgv(const StringVector & argv)308 void CommandLine::InitFromArgv(const StringVector& argv) {
309 argv_ = StringVector(1);
310 switches_.clear();
311 begin_args_ = 1;
312 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
313 if (!argv.empty()) {
314 AppendSwitchesAndArguments(make_span(argv).subspan(1));
315 }
316 }
317
GetProgram() const318 FilePath CommandLine::GetProgram() const {
319 return FilePath(argv_[0]);
320 }
321
SetProgram(const FilePath & program)322 void CommandLine::SetProgram(const FilePath& program) {
323 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
324 sequence_checker_.Check();
325 #endif
326 #if BUILDFLAG(IS_WIN)
327 argv_[0] = StringType(TrimWhitespace(program.value(), TRIM_ALL));
328 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
329 TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]);
330 #else
331 #error Unsupported platform
332 #endif
333 }
334
HasSwitch(std::string_view switch_string) const335 bool CommandLine::HasSwitch(std::string_view switch_string) const {
336 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
337 return Contains(switches_, switch_string);
338 }
339
HasSwitch(const char switch_constant[]) const340 bool CommandLine::HasSwitch(const char switch_constant[]) const {
341 return HasSwitch(std::string_view(switch_constant));
342 }
343
GetSwitchValueASCII(std::string_view switch_string) const344 std::string CommandLine::GetSwitchValueASCII(
345 std::string_view switch_string) const {
346 StringType value = GetSwitchValueNative(switch_string);
347 #if BUILDFLAG(IS_WIN)
348 if (!IsStringASCII(base::AsStringPiece16(value))) {
349 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
350 if (!IsStringASCII(value)) {
351 #endif
352 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
353 return std::string();
354 }
355 #if BUILDFLAG(IS_WIN)
356 return WideToUTF8(value);
357 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
358 return value;
359 #endif
360 }
361
362 FilePath CommandLine::GetSwitchValuePath(std::string_view switch_string) const {
363 return FilePath(GetSwitchValueNative(switch_string));
364 }
365
366 CommandLine::StringType CommandLine::GetSwitchValueNative(
367 std::string_view switch_string) const {
368 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
369 auto result = switches_.find(switch_string);
370 return result == switches_.end() ? StringType() : result->second;
371 }
372
373 void CommandLine::AppendSwitch(std::string_view switch_string) {
374 AppendSwitchNative(switch_string, StringType());
375 }
376
377 void CommandLine::AppendSwitchPath(std::string_view switch_string,
378 const FilePath& path) {
379 AppendSwitchNative(switch_string, path.value());
380 }
381
382 void CommandLine::AppendSwitchNative(std::string_view switch_string,
383 CommandLine::StringPieceType value) {
384 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
385 sequence_checker_.Check();
386 #endif
387 #if BUILDFLAG(IS_WIN)
388 const std::string switch_key = ToLowerASCII(switch_string);
389 StringType combined_switch_string(UTF8ToWide(switch_key));
390 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
391 std::string_view switch_key = switch_string;
392 StringType combined_switch_string(switch_key);
393 #endif
394 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
395 auto key = switch_key.substr(prefix_length);
396 if (g_duplicate_switch_handler) {
397 g_duplicate_switch_handler->ResolveDuplicate(key, value,
398 switches_[std::string(key)]);
399 } else {
400 switches_[std::string(key)] = StringType(value);
401 }
402
403 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
404 if (prefix_length == 0) {
405 combined_switch_string.insert(0, kSwitchPrefixes[0].data(),
406 kSwitchPrefixes[0].size());
407 }
408 if (!value.empty())
409 base::StrAppend(&combined_switch_string, {kSwitchValueSeparator, value});
410 // Append the switch and update the switches/arguments divider |begin_args_|.
411 argv_.insert(argv_.begin() + begin_args_, combined_switch_string);
412 begin_args_ = (CheckedNumeric(begin_args_) + 1).ValueOrDie();
413 }
414
415 void CommandLine::AppendSwitchASCII(std::string_view switch_string,
416 std::string_view value_string) {
417 #if BUILDFLAG(IS_WIN)
418 AppendSwitchNative(switch_string, UTF8ToWide(value_string));
419 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
420 AppendSwitchNative(switch_string, value_string);
421 #else
422 #error Unsupported platform
423 #endif
424 }
425
426 void CommandLine::RemoveSwitch(std::string_view switch_key_without_prefix) {
427 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
428 sequence_checker_.Check();
429 #endif
430 #if BUILDFLAG(IS_WIN)
431 StringType switch_key_native = UTF8ToWide(switch_key_without_prefix);
432 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
433 StringType switch_key_native(switch_key_without_prefix);
434 #endif
435
436 DCHECK_EQ(ToLowerASCII(switch_key_without_prefix), switch_key_without_prefix);
437 DCHECK_EQ(0u, GetSwitchPrefixLength(switch_key_native));
438 auto it = switches_.find(switch_key_without_prefix);
439 if (it == switches_.end())
440 return;
441 switches_.erase(it);
442 // Also erase from the switches section of |argv_| and update |begin_args_|
443 // accordingly.
444 // Switches in |argv_| have indices [1, begin_args_).
445 auto argv_switches_begin = argv_.begin() + 1;
446 auto argv_switches_end = argv_.begin() + begin_args_;
447 DCHECK(argv_switches_begin <= argv_switches_end);
448 DCHECK(argv_switches_end <= argv_.end());
449 auto expell = std::remove_if(argv_switches_begin, argv_switches_end,
450 [&switch_key_native](const StringType& arg) {
451 return IsSwitchWithKey(arg, switch_key_native);
452 });
453 if (expell == argv_switches_end) {
454 NOTREACHED();
455 return;
456 }
457 begin_args_ -= argv_switches_end - expell;
458 argv_.erase(expell, argv_switches_end);
459 }
460
461 void CommandLine::CopySwitchesFrom(const CommandLine& source,
462 span<const char* const> switches) {
463 for (const char* entry : switches) {
464 if (source.HasSwitch(entry)) {
465 AppendSwitchNative(entry, source.GetSwitchValueNative(entry));
466 }
467 }
468 }
469
470 CommandLine::StringVector CommandLine::GetArgs() const {
471 // Gather all arguments after the last switch (may include kSwitchTerminator).
472 StringVector args(argv_.begin() + begin_args_, argv_.end());
473 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
474 auto switch_terminator = ranges::find(args, kSwitchTerminator);
475 if (switch_terminator != args.end())
476 args.erase(switch_terminator);
477 return args;
478 }
479
480 void CommandLine::AppendArg(std::string_view value) {
481 #if BUILDFLAG(IS_WIN)
482 DCHECK(IsStringUTF8(value));
483 AppendArgNative(UTF8ToWide(value));
484 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
485 AppendArgNative(value);
486 #else
487 #error Unsupported platform
488 #endif
489 }
490
491 void CommandLine::AppendArgPath(const FilePath& path) {
492 AppendArgNative(path.value());
493 }
494
495 void CommandLine::AppendArgNative(StringPieceType value) {
496 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
497 sequence_checker_.Check();
498 #endif
499 argv_.push_back(StringType(value));
500 }
501
502 void CommandLine::AppendArguments(const CommandLine& other,
503 bool include_program) {
504 if (include_program)
505 SetProgram(other.GetProgram());
506 if (!other.argv().empty()) {
507 AppendSwitchesAndArguments(make_span(other.argv()).subspan(1));
508 }
509 }
510
511 void CommandLine::PrependWrapper(StringPieceType wrapper) {
512 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
513 sequence_checker_.Check();
514 #endif
515 if (wrapper.empty())
516 return;
517 // Split the wrapper command based on whitespace (with quoting).
518 // StringPieceType does not currently work directly with StringTokenizerT.
519 using CommandLineTokenizer =
520 StringTokenizerT<StringType, StringType::const_iterator>;
521 StringType wrapper_string(wrapper);
522 CommandLineTokenizer tokenizer(wrapper_string, FILE_PATH_LITERAL(" "));
523 tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
524 std::vector<StringType> wrapper_argv;
525 while (tokenizer.GetNext())
526 wrapper_argv.emplace_back(tokenizer.token());
527
528 // Prepend the wrapper and update the switches/arguments |begin_args_|.
529 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
530 begin_args_ += wrapper_argv.size();
531 }
532
533 #if BUILDFLAG(IS_WIN)
534 void CommandLine::ParseFromString(StringPieceType command_line) {
535 command_line = TrimWhitespace(command_line, TRIM_ALL);
536 if (command_line.empty())
537 return;
538 raw_command_line_string_ = command_line;
539
540 int num_args = 0;
541 wchar_t** args = NULL;
542 // When calling CommandLineToArgvW, use the apiset if available.
543 // Doing so will bypass loading shell32.dll on Windows.
544 HMODULE downlevel_shell32_dll =
545 ::LoadLibraryEx(L"api-ms-win-downlevel-shell32-l1-1-0.dll", nullptr,
546 LOAD_LIBRARY_SEARCH_SYSTEM32);
547 if (downlevel_shell32_dll) {
548 auto command_line_to_argv_w_proc =
549 reinterpret_cast<decltype(::CommandLineToArgvW)*>(
550 ::GetProcAddress(downlevel_shell32_dll, "CommandLineToArgvW"));
551 if (command_line_to_argv_w_proc)
552 args = command_line_to_argv_w_proc(command_line.data(), &num_args);
553 } else {
554 // Since the apiset is not available, allow the delayload of shell32.dll
555 // to take place.
556 args = ::CommandLineToArgvW(command_line.data(), &num_args);
557 }
558
559 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
560 << command_line;
561 StringVector argv(args, args + num_args);
562 InitFromArgv(argv);
563 raw_command_line_string_ = StringPieceType();
564 LocalFree(args);
565
566 if (downlevel_shell32_dll)
567 ::FreeLibrary(downlevel_shell32_dll);
568 }
569
570 #endif // BUILDFLAG(IS_WIN)
571
572 void CommandLine::AppendSwitchesAndArguments(span<const StringType> argv) {
573 bool parse_switches = true;
574 #if BUILDFLAG(IS_WIN)
575 const bool is_parsed_from_string = !raw_command_line_string_.empty();
576 #endif
577 for (StringType arg : argv) {
578 #if BUILDFLAG(IS_WIN)
579 arg = CommandLine::StringType(TrimWhitespace(arg, TRIM_ALL));
580 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
581 TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
582 #endif
583
584 CommandLine::StringType switch_string;
585 CommandLine::StringType switch_value;
586 parse_switches &= (arg != kSwitchTerminator);
587 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
588 #if BUILDFLAG(IS_WIN)
589 if (is_parsed_from_string &&
590 IsSwitchWithKey(switch_string, kSingleArgument)) {
591 ParseAsSingleArgument(switch_string);
592 return;
593 }
594 AppendSwitchNative(WideToUTF8(switch_string), switch_value);
595 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
596 AppendSwitchNative(switch_string, switch_value);
597 #else
598 #error Unsupported platform
599 #endif
600 } else {
601 AppendArgNative(arg);
602 }
603 }
604 }
605
606 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
607 bool allow_unsafe_insert_sequences) const {
608 StringType params;
609 // Append switches and arguments.
610 bool parse_switches = true;
611 #if BUILDFLAG(IS_WIN)
612 bool appended_single_argument_switch = false;
613 #endif
614
615 for (size_t i = 1; i < argv_.size(); ++i) {
616 StringType arg = argv_[i];
617 StringType switch_string;
618 StringType switch_value;
619 parse_switches &= arg != kSwitchTerminator;
620 if (i > 1)
621 params.append(FILE_PATH_LITERAL(" "));
622 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
623 params.append(switch_string);
624 if (!switch_value.empty()) {
625 #if BUILDFLAG(IS_WIN)
626 switch_value = QuoteForCommandLineToArgvWInternal(
627 switch_value, allow_unsafe_insert_sequences);
628 #endif
629 params.append(kSwitchValueSeparator + switch_value);
630 }
631 } else {
632 #if BUILDFLAG(IS_WIN)
633 if (has_single_argument_switch_) {
634 // Check that we don't have multiple arguments when
635 // `has_single_argument_switch_` is true.
636 DCHECK(!appended_single_argument_switch);
637 appended_single_argument_switch = true;
638 params.append(base::StrCat(
639 {kSwitchPrefixes[0], kSingleArgument, FILE_PATH_LITERAL(" ")}));
640 } else {
641 arg = QuoteForCommandLineToArgvWInternal(arg,
642 allow_unsafe_insert_sequences);
643 }
644 #endif
645 params.append(arg);
646 }
647 }
648 return params;
649 }
650
651 CommandLine::StringType CommandLine::GetCommandLineString() const {
652 StringType string(argv_[0]);
653 #if BUILDFLAG(IS_WIN)
654 string = QuoteForCommandLineToArgvWInternal(
655 string,
656 /*allow_unsafe_insert_sequences=*/false);
657 #endif
658 StringType params(GetArgumentsString());
659 if (!params.empty()) {
660 string.append(FILE_PATH_LITERAL(" "));
661 string.append(params);
662 }
663 return string;
664 }
665
666 #if BUILDFLAG(IS_WIN)
667 // static
668 std::wstring CommandLine::QuoteForCommandLineToArgvW(const std::wstring& arg) {
669 return QuoteForCommandLineToArgvWInternal(
670 arg, /*allow_unsafe_insert_sequences=*/false);
671 }
672
673 // NOTE: this function is used to set Chrome's open command in the registry
674 // during update. Any change to the syntax must be compatible with the prior
675 // version (i.e., any new syntax must be understood by older browsers expecting
676 // the old syntax, and the new browser must still handle the old syntax), as
677 // old versions are likely to persist, e.g., immediately after background
678 // update, when parsing command lines for other channels, when uninstalling web
679 // applications installed using the old syntax, etc.
680 CommandLine::StringType CommandLine::GetCommandLineStringForShell() const {
681 DCHECK(GetArgs().empty());
682 StringType command_line_string = GetCommandLineString();
683 return command_line_string + FILE_PATH_LITERAL(" ") +
684 StringType(kSwitchPrefixes[0]) + kSingleArgument +
685 FILE_PATH_LITERAL(" %1");
686 }
687
688 CommandLine::StringType
689 CommandLine::GetCommandLineStringWithUnsafeInsertSequences() const {
690 StringType string(argv_[0]);
691 string = QuoteForCommandLineToArgvWInternal(
692 string,
693 /*allow_unsafe_insert_sequences=*/true);
694 StringType params(
695 GetArgumentsStringInternal(/*allow_unsafe_insert_sequences=*/true));
696 if (!params.empty()) {
697 string.append(FILE_PATH_LITERAL(" "));
698 string.append(params);
699 }
700 return string;
701 }
702 #endif // BUILDFLAG(IS_WIN)
703
704 CommandLine::StringType CommandLine::GetArgumentsString() const {
705 return GetArgumentsStringInternal(/*allow_unsafe_insert_sequences=*/false);
706 }
707
708 #if BUILDFLAG(IS_WIN)
709 void CommandLine::ParseAsSingleArgument(
710 const CommandLine::StringType& single_arg_switch) {
711 DCHECK(!raw_command_line_string_.empty());
712
713 // Remove any previously parsed arguments.
714 argv_.resize(static_cast<size_t>(begin_args_));
715
716 // Locate "--single-argument" in the process's raw command line. Results are
717 // unpredictable if "--single-argument" appears as part of a previous
718 // argument or switch.
719 const size_t single_arg_switch_position =
720 raw_command_line_string_.find(single_arg_switch);
721 DCHECK_NE(single_arg_switch_position, StringType::npos);
722
723 // Append the portion of the raw command line that starts one character past
724 // "--single-argument" as the one and only argument, or return if no
725 // argument is present.
726 const size_t arg_position =
727 single_arg_switch_position + single_arg_switch.length() + 1;
728 if (arg_position >= raw_command_line_string_.length())
729 return;
730 has_single_argument_switch_ = true;
731 const StringPieceType arg = raw_command_line_string_.substr(arg_position);
732 if (!arg.empty()) {
733 AppendArgNative(arg);
734 }
735 }
736 #endif // BUILDFLAG(IS_WIN)
737
738 void CommandLine::DetachFromCurrentSequence() {
739 #if BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
740 sequence_checker_.Detach();
741 #endif // BUILDFLAG(ENABLE_COMMANDLINE_SEQUENCE_CHECKS)
742 }
743
744 } // namespace base
745