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
5 #include "base/command_line.h"
6
7 #include <algorithm>
8 #include <iterator>
9 #include <ostream>
10 #include <string_view>
11
12 #include "base/files/file_path.h"
13 #include "base/logging.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 "util/build_config.h"
20
21 #if defined(OS_WIN)
22 #include <windows.h>
23
24 #include <shellapi.h>
25 #endif
26
27 namespace base {
28
29 CommandLine* CommandLine::current_process_commandline_ = nullptr;
30
31 namespace {
32
33 const CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
34 const CommandLine::CharType kSwitchValueSeparator[] = FILE_PATH_LITERAL("=");
35
36 // Since we use a lazy match, make sure that longer versions (like "--") are
37 // listed before shorter versions (like "-") of similar prefixes.
38 #if defined(OS_WIN)
39 // By putting slash last, we can control whether it is treaded as a switch
40 // value by changing the value of switch_prefix_count to be one less than
41 // the array size.
42 const CommandLine::CharType* const kSwitchPrefixes[] = {u"--", u"-", u"/"};
43 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
44 // Unixes don't use slash as a switch.
45 const CommandLine::CharType* const kSwitchPrefixes[] = {"--", "-"};
46 #endif
47 size_t switch_prefix_count = std::size(kSwitchPrefixes);
48
GetSwitchPrefixLength(const CommandLine::StringType & string)49 size_t GetSwitchPrefixLength(const CommandLine::StringType& string) {
50 for (size_t i = 0; i < switch_prefix_count; ++i) {
51 CommandLine::StringType prefix(kSwitchPrefixes[i]);
52 if (string.compare(0, prefix.length(), prefix) == 0)
53 return prefix.length();
54 }
55 return 0;
56 }
57
58 // Fills in |switch_string| and |switch_value| if |string| is a switch.
59 // 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)60 bool IsSwitch(const CommandLine::StringType& string,
61 CommandLine::StringType* switch_string,
62 CommandLine::StringType* switch_value) {
63 switch_string->clear();
64 switch_value->clear();
65 size_t prefix_length = GetSwitchPrefixLength(string);
66 if (prefix_length == 0 || prefix_length == string.length())
67 return false;
68
69 const size_t equals_position = string.find(kSwitchValueSeparator);
70 *switch_string = string.substr(0, equals_position);
71 if (equals_position != CommandLine::StringType::npos)
72 *switch_value = string.substr(equals_position + 1);
73 return true;
74 }
75
76 // Append switches and arguments, keeping switches before arguments
77 // if handle_switches is true.
AppendSwitchesAndArguments(CommandLine * command_line,const CommandLine::StringVector & argv,bool handle_switches)78 void AppendSwitchesAndArguments(CommandLine* command_line,
79 const CommandLine::StringVector& argv,
80 bool handle_switches) {
81 bool parse_switches = handle_switches;
82 for (size_t i = 1; i < argv.size(); ++i) {
83 CommandLine::StringType arg = argv[i];
84 #if defined(OS_WIN)
85 TrimWhitespace(arg, TRIM_ALL, &arg);
86 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
87 TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
88 #endif
89
90 CommandLine::StringType switch_string;
91 CommandLine::StringType switch_value;
92 parse_switches &= (arg != kSwitchTerminator);
93 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
94 #if defined(OS_WIN)
95 command_line->AppendSwitchNative(UTF16ToASCII(switch_string),
96 switch_value);
97 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
98 command_line->AppendSwitchNative(switch_string, switch_value);
99 #else
100 #error Unsupported platform
101 #endif
102 } else {
103 command_line->AppendArgNative(arg);
104 }
105 }
106 }
107
108 #if defined(OS_WIN)
109 // Quote a string as necessary for CommandLineToArgvW compatibility *on
110 // Windows*.
QuoteForCommandLineToArgvW(const std::u16string & arg,bool quote_placeholders)111 std::u16string QuoteForCommandLineToArgvW(const std::u16string& arg,
112 bool quote_placeholders) {
113 // We follow the quoting rules of CommandLineToArgvW.
114 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
115 std::u16string quotable_chars(u" \\\"");
116 // We may also be required to quote '%', which is commonly used in a command
117 // line as a placeholder. (It may be substituted for a string with spaces.)
118 if (quote_placeholders)
119 quotable_chars.push_back('%');
120 if (arg.find_first_of(quotable_chars) == std::u16string::npos) {
121 // No quoting necessary.
122 return arg;
123 }
124
125 std::u16string out;
126 out.push_back('"');
127 for (size_t i = 0; i < arg.size(); ++i) {
128 if (arg[i] == '\\') {
129 // Find the extent of this run of backslashes.
130 size_t start = i, end = start + 1;
131 for (; end < arg.size() && arg[end] == '\\'; ++end) {
132 }
133 size_t backslash_count = end - start;
134
135 // Backslashes are escapes only if the run is followed by a double quote.
136 // Since we also will end the string with a double quote, we escape for
137 // either a double quote or the end of the string.
138 if (end == arg.size() || arg[end] == '"') {
139 // To quote, we need to output 2x as many backslashes.
140 backslash_count *= 2;
141 }
142 for (size_t j = 0; j < backslash_count; ++j)
143 out.push_back('\\');
144
145 // Advance i to one before the end to balance i++ in loop.
146 i = end - 1;
147 } else if (arg[i] == '"') {
148 out.push_back('\\');
149 out.push_back('"');
150 } else {
151 out.push_back(arg[i]);
152 }
153 }
154 out.push_back('"');
155
156 return out;
157 }
158 #endif
159
160 } // namespace
161
CommandLine(NoProgram no_program)162 CommandLine::CommandLine(NoProgram no_program)
163 : argv_(1), begin_args_(1), parse_switches_(true) {}
164
CommandLine(const FilePath & program)165 CommandLine::CommandLine(const FilePath& program)
166 : argv_(1), begin_args_(1), parse_switches_(true) {
167 SetProgram(program);
168 }
169
CommandLine(int argc,const CommandLine::CharType * const * argv)170 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
171 : argv_(1), begin_args_(1), parse_switches_(true) {
172 InitFromArgv(argc, argv);
173 }
174
CommandLine(const StringVector & argv)175 CommandLine::CommandLine(const StringVector& argv)
176 : argv_(1), begin_args_(1), parse_switches_(true) {
177 InitFromArgv(argv);
178 }
179
180 CommandLine::CommandLine(const CommandLine& other) = default;
181
182 CommandLine& CommandLine::operator=(const CommandLine& other) = default;
183
184 CommandLine::~CommandLine() = default;
185
186 #if defined(OS_WIN)
187 // static
set_slash_is_not_a_switch()188 void CommandLine::set_slash_is_not_a_switch() {
189 // The last switch prefix should be slash, so adjust the size to skip it.
190 DCHECK(std::u16string_view(kSwitchPrefixes[std::size(kSwitchPrefixes) - 1]) ==
191 std::u16string_view(u"/"));
192 switch_prefix_count = std::size(kSwitchPrefixes) - 1;
193 }
194
195 // static
InitUsingArgvForTesting(int argc,const char * const * argv)196 void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) {
197 DCHECK(!current_process_commandline_);
198 current_process_commandline_ = new CommandLine(NO_PROGRAM);
199 // On Windows we need to convert the command line arguments to std::u16string.
200 base::CommandLine::StringVector argv_vector;
201 for (int i = 0; i < argc; ++i)
202 argv_vector.push_back(UTF8ToUTF16(argv[i]));
203 current_process_commandline_->InitFromArgv(argv_vector);
204 }
205 #endif
206
207 // static
Init(int argc,const char * const * argv)208 bool CommandLine::Init(int argc, const char* const* argv) {
209 if (current_process_commandline_) {
210 // If this is intentional, Reset() must be called first. If we are using
211 // the shared build mode, we have to share a single object across multiple
212 // shared libraries.
213 return false;
214 }
215
216 current_process_commandline_ = new CommandLine(NO_PROGRAM);
217 #if defined(OS_WIN)
218 current_process_commandline_->ParseFromString(
219 reinterpret_cast<const char16_t*>(::GetCommandLineW()));
220 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
221 current_process_commandline_->InitFromArgv(argc, argv);
222 #else
223 #error Unsupported platform
224 #endif
225
226 return true;
227 }
228
229 // static
Reset()230 void CommandLine::Reset() {
231 DCHECK(current_process_commandline_);
232 delete current_process_commandline_;
233 current_process_commandline_ = nullptr;
234 }
235
236 // static
ForCurrentProcess()237 CommandLine* CommandLine::ForCurrentProcess() {
238 DCHECK(current_process_commandline_);
239 return current_process_commandline_;
240 }
241
242 // static
InitializedForCurrentProcess()243 bool CommandLine::InitializedForCurrentProcess() {
244 return !!current_process_commandline_;
245 }
246
247 #if defined(OS_WIN)
248 // static
FromString(const std::u16string & command_line)249 CommandLine CommandLine::FromString(const std::u16string& command_line) {
250 CommandLine cmd(NO_PROGRAM);
251 cmd.ParseFromString(command_line);
252 return cmd;
253 }
254 #endif
255
InitFromArgv(int argc,const CommandLine::CharType * const * argv)256 void CommandLine::InitFromArgv(int argc,
257 const CommandLine::CharType* const* argv) {
258 StringVector new_argv;
259 for (int i = 0; i < argc; ++i)
260 new_argv.push_back(argv[i]);
261 InitFromArgv(new_argv);
262 }
263
InitFromArgv(const StringVector & argv)264 void CommandLine::InitFromArgv(const StringVector& argv) {
265 argv_ = StringVector(1);
266 switches_.clear();
267 begin_args_ = 1;
268 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
269 AppendSwitchesAndArguments(this, argv, parse_switches_);
270 }
271
GetProgram() const272 FilePath CommandLine::GetProgram() const {
273 return FilePath(argv_[0]);
274 }
275
SetProgram(const FilePath & program)276 void CommandLine::SetProgram(const FilePath& program) {
277 #if defined(OS_WIN)
278 TrimWhitespace(program.value(), TRIM_ALL, &argv_[0]);
279 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
280 TrimWhitespaceASCII(program.value(), TRIM_ALL, &argv_[0]);
281 #else
282 #error Unsupported platform
283 #endif
284 }
285
HasSwitch(std::string_view switch_string) const286 bool CommandLine::HasSwitch(std::string_view switch_string) const {
287 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
288 return ContainsKey(switches_, switch_string);
289 }
290
HasSwitch(const char switch_constant[]) const291 bool CommandLine::HasSwitch(const char switch_constant[]) const {
292 return HasSwitch(std::string_view(switch_constant));
293 }
294
GetSwitchValueASCII(std::string_view switch_string) const295 std::string CommandLine::GetSwitchValueASCII(
296 std::string_view switch_string) const {
297 StringType value = GetSwitchValueNative(switch_string);
298 if (!IsStringASCII(value)) {
299 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
300 return std::string();
301 }
302 #if defined(OS_WIN)
303 return UTF16ToASCII(value);
304 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
305 return value;
306 #endif
307 }
308
GetSwitchValuePath(std::string_view switch_string) const309 FilePath CommandLine::GetSwitchValuePath(std::string_view switch_string) const {
310 return FilePath(GetSwitchValueNative(switch_string));
311 }
312
GetSwitchValueNative(std::string_view switch_string) const313 CommandLine::StringType CommandLine::GetSwitchValueNative(
314 std::string_view switch_string) const {
315 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
316 auto result = switches_.find(switch_string);
317 return result == switches_.end() ? StringType() : result->second;
318 }
319
AppendSwitch(const std::string & switch_string)320 void CommandLine::AppendSwitch(const std::string& switch_string) {
321 AppendSwitchNative(switch_string, StringType());
322 }
323
AppendSwitchPath(const std::string & switch_string,const FilePath & path)324 void CommandLine::AppendSwitchPath(const std::string& switch_string,
325 const FilePath& path) {
326 AppendSwitchNative(switch_string, path.value());
327 }
328
AppendSwitchNative(const std::string & switch_string,const CommandLine::StringType & value)329 void CommandLine::AppendSwitchNative(const std::string& switch_string,
330 const CommandLine::StringType& value) {
331 #if defined(OS_WIN)
332 const std::string switch_key = ToLowerASCII(switch_string);
333 StringType combined_switch_string(ASCIIToUTF16(switch_key));
334 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
335 const std::string& switch_key = switch_string;
336 StringType combined_switch_string(switch_key);
337 #endif
338 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
339 auto insertion =
340 switches_.insert(make_pair(switch_key.substr(prefix_length), value));
341 if (!insertion.second)
342 insertion.first->second = value;
343 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
344 if (prefix_length == 0)
345 combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
346 if (!value.empty())
347 combined_switch_string += kSwitchValueSeparator + value;
348 // Append the switch and update the switches/arguments divider |begin_args_|.
349 argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
350 }
351
AppendSwitchASCII(const std::string & switch_string,const std::string & value_string)352 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
353 const std::string& value_string) {
354 #if defined(OS_WIN)
355 AppendSwitchNative(switch_string, ASCIIToUTF16(value_string));
356 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
357 AppendSwitchNative(switch_string, value_string);
358 #else
359 #error Unsupported platform
360 #endif
361 }
362
CopySwitchesFrom(const CommandLine & source,const char * const switches[],size_t count)363 void CommandLine::CopySwitchesFrom(const CommandLine& source,
364 const char* const switches[],
365 size_t count) {
366 for (size_t i = 0; i < count; ++i) {
367 if (source.HasSwitch(switches[i]))
368 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
369 }
370 }
371
GetArgs() const372 CommandLine::StringVector CommandLine::GetArgs() const {
373 // Gather all arguments after the last switch (may include kSwitchTerminator).
374 StringVector args(argv_.begin() + begin_args_, argv_.end());
375 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
376 StringVector::iterator switch_terminator =
377 std::find(args.begin(), args.end(), kSwitchTerminator);
378 if (switch_terminator != args.end())
379 args.erase(switch_terminator);
380 return args;
381 }
382
AppendArg(const std::string & value)383 void CommandLine::AppendArg(const std::string& value) {
384 #if defined(OS_WIN)
385 DCHECK(IsStringUTF8(value));
386 AppendArgNative(UTF8ToUTF16(value));
387 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
388 AppendArgNative(value);
389 #else
390 #error Unsupported platform
391 #endif
392 }
393
AppendArgPath(const FilePath & path)394 void CommandLine::AppendArgPath(const FilePath& path) {
395 AppendArgNative(path.value());
396 }
397
AppendArgNative(const CommandLine::StringType & value)398 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
399 argv_.push_back(value);
400 }
401
AppendArguments(const CommandLine & other,bool include_program)402 void CommandLine::AppendArguments(const CommandLine& other,
403 bool include_program) {
404 if (include_program)
405 SetProgram(other.GetProgram());
406 AppendSwitchesAndArguments(this, other.argv(), parse_switches_);
407 }
408
PrependWrapper(const CommandLine::StringType & wrapper)409 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
410 if (wrapper.empty())
411 return;
412 // Split the wrapper command based on whitespace (with quoting).
413 using CommandLineTokenizer =
414 StringTokenizerT<StringType, StringType::const_iterator>;
415 CommandLineTokenizer tokenizer(wrapper, FILE_PATH_LITERAL(" "));
416 tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
417 std::vector<StringType> wrapper_argv;
418 while (tokenizer.GetNext())
419 wrapper_argv.emplace_back(tokenizer.token());
420
421 // Prepend the wrapper and update the switches/arguments |begin_args_|.
422 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
423 begin_args_ += wrapper_argv.size();
424 }
425
426 #if defined(OS_WIN)
ParseFromString(const std::u16string & command_line)427 void CommandLine::ParseFromString(const std::u16string& command_line) {
428 std::u16string command_line_string;
429 TrimWhitespace(command_line, TRIM_ALL, &command_line_string);
430 if (command_line_string.empty())
431 return;
432
433 int num_args = 0;
434 char16_t** args = NULL;
435 args = reinterpret_cast<char16_t**>(::CommandLineToArgvW(
436 reinterpret_cast<LPCWSTR>(command_line_string.c_str()), &num_args));
437
438 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
439 << UTF16ToUTF8(command_line);
440 InitFromArgv(num_args, args);
441 LocalFree(args);
442 }
443 #endif
444
GetCommandLineStringInternal(bool quote_placeholders) const445 CommandLine::StringType CommandLine::GetCommandLineStringInternal(
446 bool quote_placeholders) const {
447 StringType string(argv_[0]);
448 #if defined(OS_WIN)
449 string = QuoteForCommandLineToArgvW(string, quote_placeholders);
450 #endif
451 StringType params(GetArgumentsStringInternal(quote_placeholders));
452 if (!params.empty()) {
453 string.append(StringType(FILE_PATH_LITERAL(" ")));
454 string.append(params);
455 }
456 return string;
457 }
458
GetArgumentsStringInternal(bool quote_placeholders) const459 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
460 bool quote_placeholders) const {
461 StringType params;
462 // Append switches and arguments.
463 bool parse_switches = parse_switches_;
464 for (size_t i = 1; i < argv_.size(); ++i) {
465 StringType arg = argv_[i];
466 StringType switch_string;
467 StringType switch_value;
468 parse_switches &= arg != kSwitchTerminator;
469 if (i > 1)
470 params.append(StringType(FILE_PATH_LITERAL(" ")));
471 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
472 params.append(switch_string);
473 if (!switch_value.empty()) {
474 #if defined(OS_WIN)
475 switch_value =
476 QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
477 #endif
478 params.append(kSwitchValueSeparator + switch_value);
479 }
480 } else {
481 #if defined(OS_WIN)
482 arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);
483 #endif
484 params.append(arg);
485 }
486 }
487 return params;
488 }
489
490 } // namespace base
491