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/macros.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_split.h"
17 #include "base/strings/string_tokenizer.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "util/build_config.h"
21
22 #if defined(OS_WIN)
23 #include <windows.h>
24
25 #include <shellapi.h>
26 #endif
27
28 namespace base {
29
30 CommandLine* CommandLine::current_process_commandline_ = nullptr;
31
32 namespace {
33
34 const CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
35 const CommandLine::CharType kSwitchValueSeparator[] = FILE_PATH_LITERAL("=");
36
37 // Since we use a lazy match, make sure that longer versions (like "--") are
38 // listed before shorter versions (like "-") of similar prefixes.
39 #if defined(OS_WIN)
40 // By putting slash last, we can control whether it is treaded as a switch
41 // value by changing the value of switch_prefix_count to be one less than
42 // the array size.
43 const CommandLine::CharType* const kSwitchPrefixes[] = {u"--", u"-", u"/"};
44 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
45 // Unixes don't use slash as a switch.
46 const CommandLine::CharType* const kSwitchPrefixes[] = {"--", "-"};
47 #endif
48 size_t switch_prefix_count = std::size(kSwitchPrefixes);
49
GetSwitchPrefixLength(const CommandLine::StringType & string)50 size_t GetSwitchPrefixLength(const CommandLine::StringType& string) {
51 for (size_t i = 0; i < switch_prefix_count; ++i) {
52 CommandLine::StringType prefix(kSwitchPrefixes[i]);
53 if (string.compare(0, prefix.length(), prefix) == 0)
54 return prefix.length();
55 }
56 return 0;
57 }
58
59 // Fills in |switch_string| and |switch_value| if |string| is a switch.
60 // 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)61 bool IsSwitch(const CommandLine::StringType& string,
62 CommandLine::StringType* switch_string,
63 CommandLine::StringType* switch_value) {
64 switch_string->clear();
65 switch_value->clear();
66 size_t prefix_length = GetSwitchPrefixLength(string);
67 if (prefix_length == 0 || prefix_length == string.length())
68 return false;
69
70 const size_t equals_position = string.find(kSwitchValueSeparator);
71 *switch_string = string.substr(0, equals_position);
72 if (equals_position != CommandLine::StringType::npos)
73 *switch_value = string.substr(equals_position + 1);
74 return true;
75 }
76
77 // Append switches and arguments, keeping switches before arguments
78 // if handle_switches is true.
AppendSwitchesAndArguments(CommandLine * command_line,const CommandLine::StringVector & argv,bool handle_switches)79 void AppendSwitchesAndArguments(CommandLine* command_line,
80 const CommandLine::StringVector& argv,
81 bool handle_switches) {
82 bool parse_switches = handle_switches;
83 for (size_t i = 1; i < argv.size(); ++i) {
84 CommandLine::StringType arg = argv[i];
85 #if defined(OS_WIN)
86 TrimWhitespace(arg, TRIM_ALL, &arg);
87 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
88 TrimWhitespaceASCII(arg, TRIM_ALL, &arg);
89 #endif
90
91 CommandLine::StringType switch_string;
92 CommandLine::StringType switch_value;
93 parse_switches &= (arg != kSwitchTerminator);
94 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
95 #if defined(OS_WIN)
96 command_line->AppendSwitchNative(UTF16ToASCII(switch_string),
97 switch_value);
98 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
99 command_line->AppendSwitchNative(switch_string, switch_value);
100 #else
101 #error Unsupported platform
102 #endif
103 } else {
104 command_line->AppendArgNative(arg);
105 }
106 }
107 }
108
109 #if defined(OS_WIN)
110 // Quote a string as necessary for CommandLineToArgvW compatiblity *on 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(const std::string_view & switch_string) const286 bool CommandLine::HasSwitch(const 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(const std::string_view & switch_string) const295 std::string CommandLine::GetSwitchValueASCII(
296 const 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(const std::string_view & switch_string) const309 FilePath CommandLine::GetSwitchValuePath(
310 const std::string_view& switch_string) const {
311 return FilePath(GetSwitchValueNative(switch_string));
312 }
313
GetSwitchValueNative(const std::string_view & switch_string) const314 CommandLine::StringType CommandLine::GetSwitchValueNative(
315 const std::string_view& switch_string) const {
316 DCHECK_EQ(ToLowerASCII(switch_string), switch_string);
317 auto result = switches_.find(switch_string);
318 return result == switches_.end() ? StringType() : result->second;
319 }
320
AppendSwitch(const std::string & switch_string)321 void CommandLine::AppendSwitch(const std::string& switch_string) {
322 AppendSwitchNative(switch_string, StringType());
323 }
324
AppendSwitchPath(const std::string & switch_string,const FilePath & path)325 void CommandLine::AppendSwitchPath(const std::string& switch_string,
326 const FilePath& path) {
327 AppendSwitchNative(switch_string, path.value());
328 }
329
AppendSwitchNative(const std::string & switch_string,const CommandLine::StringType & value)330 void CommandLine::AppendSwitchNative(const std::string& switch_string,
331 const CommandLine::StringType& value) {
332 #if defined(OS_WIN)
333 const std::string switch_key = ToLowerASCII(switch_string);
334 StringType combined_switch_string(ASCIIToUTF16(switch_key));
335 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
336 const std::string& switch_key = switch_string;
337 StringType combined_switch_string(switch_key);
338 #endif
339 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
340 auto insertion =
341 switches_.insert(make_pair(switch_key.substr(prefix_length), value));
342 if (!insertion.second)
343 insertion.first->second = value;
344 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
345 if (prefix_length == 0)
346 combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
347 if (!value.empty())
348 combined_switch_string += kSwitchValueSeparator + value;
349 // Append the switch and update the switches/arguments divider |begin_args_|.
350 argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
351 }
352
AppendSwitchASCII(const std::string & switch_string,const std::string & value_string)353 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
354 const std::string& value_string) {
355 #if defined(OS_WIN)
356 AppendSwitchNative(switch_string, ASCIIToUTF16(value_string));
357 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
358 AppendSwitchNative(switch_string, value_string);
359 #else
360 #error Unsupported platform
361 #endif
362 }
363
CopySwitchesFrom(const CommandLine & source,const char * const switches[],size_t count)364 void CommandLine::CopySwitchesFrom(const CommandLine& source,
365 const char* const switches[],
366 size_t count) {
367 for (size_t i = 0; i < count; ++i) {
368 if (source.HasSwitch(switches[i]))
369 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
370 }
371 }
372
GetArgs() const373 CommandLine::StringVector CommandLine::GetArgs() const {
374 // Gather all arguments after the last switch (may include kSwitchTerminator).
375 StringVector args(argv_.begin() + begin_args_, argv_.end());
376 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
377 StringVector::iterator switch_terminator =
378 std::find(args.begin(), args.end(), kSwitchTerminator);
379 if (switch_terminator != args.end())
380 args.erase(switch_terminator);
381 return args;
382 }
383
AppendArg(const std::string & value)384 void CommandLine::AppendArg(const std::string& value) {
385 #if defined(OS_WIN)
386 DCHECK(IsStringUTF8(value));
387 AppendArgNative(UTF8ToUTF16(value));
388 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
389 AppendArgNative(value);
390 #else
391 #error Unsupported platform
392 #endif
393 }
394
AppendArgPath(const FilePath & path)395 void CommandLine::AppendArgPath(const FilePath& path) {
396 AppendArgNative(path.value());
397 }
398
AppendArgNative(const CommandLine::StringType & value)399 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
400 argv_.push_back(value);
401 }
402
AppendArguments(const CommandLine & other,bool include_program)403 void CommandLine::AppendArguments(const CommandLine& other,
404 bool include_program) {
405 if (include_program)
406 SetProgram(other.GetProgram());
407 AppendSwitchesAndArguments(this, other.argv(), parse_switches_);
408 }
409
PrependWrapper(const CommandLine::StringType & wrapper)410 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
411 if (wrapper.empty())
412 return;
413 // Split the wrapper command based on whitespace (with quoting).
414 using CommandLineTokenizer =
415 StringTokenizerT<StringType, StringType::const_iterator>;
416 CommandLineTokenizer tokenizer(wrapper, FILE_PATH_LITERAL(" "));
417 tokenizer.set_quote_chars(FILE_PATH_LITERAL("'\""));
418 std::vector<StringType> wrapper_argv;
419 while (tokenizer.GetNext())
420 wrapper_argv.emplace_back(tokenizer.token());
421
422 // Prepend the wrapper and update the switches/arguments |begin_args_|.
423 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
424 begin_args_ += wrapper_argv.size();
425 }
426
427 #if defined(OS_WIN)
ParseFromString(const std::u16string & command_line)428 void CommandLine::ParseFromString(const std::u16string& command_line) {
429 std::u16string command_line_string;
430 TrimWhitespace(command_line, TRIM_ALL, &command_line_string);
431 if (command_line_string.empty())
432 return;
433
434 int num_args = 0;
435 char16_t** args = NULL;
436 args = reinterpret_cast<char16_t**>(::CommandLineToArgvW(
437 reinterpret_cast<LPCWSTR>(command_line_string.c_str()), &num_args));
438
439 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
440 << UTF16ToUTF8(command_line);
441 InitFromArgv(num_args, args);
442 LocalFree(args);
443 }
444 #endif
445
GetCommandLineStringInternal(bool quote_placeholders) const446 CommandLine::StringType CommandLine::GetCommandLineStringInternal(
447 bool quote_placeholders) const {
448 StringType string(argv_[0]);
449 #if defined(OS_WIN)
450 string = QuoteForCommandLineToArgvW(string, quote_placeholders);
451 #endif
452 StringType params(GetArgumentsStringInternal(quote_placeholders));
453 if (!params.empty()) {
454 string.append(StringType(FILE_PATH_LITERAL(" ")));
455 string.append(params);
456 }
457 return string;
458 }
459
GetArgumentsStringInternal(bool quote_placeholders) const460 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
461 bool quote_placeholders) const {
462 StringType params;
463 // Append switches and arguments.
464 bool parse_switches = parse_switches_;
465 for (size_t i = 1; i < argv_.size(); ++i) {
466 StringType arg = argv_[i];
467 StringType switch_string;
468 StringType switch_value;
469 parse_switches &= arg != kSwitchTerminator;
470 if (i > 1)
471 params.append(StringType(FILE_PATH_LITERAL(" ")));
472 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
473 params.append(switch_string);
474 if (!switch_value.empty()) {
475 #if defined(OS_WIN)
476 switch_value =
477 QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
478 #endif
479 params.append(kSwitchValueSeparator + switch_value);
480 }
481 } else {
482 #if defined(OS_WIN)
483 arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);
484 #endif
485 params.append(arg);
486 }
487 }
488 return params;
489 }
490
491 } // namespace base
492