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