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.
5 #include "base/command_line.h"
10 #include "base/basictypes.h"
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "build/build_config.h"
25 CommandLine
* CommandLine::current_process_commandline_
= NULL
;
29 const CommandLine::CharType kSwitchTerminator
[] = FILE_PATH_LITERAL("--");
30 const CommandLine::CharType kSwitchValueSeparator
[] = FILE_PATH_LITERAL("=");
32 // Since we use a lazy match, make sure that longer versions (like "--") are
33 // listed before shorter versions (like "-") of similar prefixes.
35 // By putting slash last, we can control whether it is treaded as a switch
36 // value by changing the value of switch_prefix_count to be one less than
38 const CommandLine::CharType
* const kSwitchPrefixes
[] = {L
"--", L
"-", L
"/"};
39 #elif defined(OS_POSIX)
40 // Unixes don't use slash as a switch.
41 const CommandLine::CharType
* const kSwitchPrefixes
[] = {"--", "-"};
43 size_t switch_prefix_count
= arraysize(kSwitchPrefixes
);
45 size_t GetSwitchPrefixLength(const CommandLine::StringType
& string
) {
46 for (size_t i
= 0; i
< switch_prefix_count
; ++i
) {
47 CommandLine::StringType
prefix(kSwitchPrefixes
[i
]);
48 if (string
.compare(0, prefix
.length(), prefix
) == 0)
49 return prefix
.length();
54 // Fills in |switch_string| and |switch_value| if |string| is a switch.
55 // This will preserve the input switch prefix in the output |switch_string|.
56 bool IsSwitch(const CommandLine::StringType
& string
,
57 CommandLine::StringType
* switch_string
,
58 CommandLine::StringType
* switch_value
) {
59 switch_string
->clear();
60 switch_value
->clear();
61 size_t prefix_length
= GetSwitchPrefixLength(string
);
62 if (prefix_length
== 0 || prefix_length
== string
.length())
65 const size_t equals_position
= string
.find(kSwitchValueSeparator
);
66 *switch_string
= string
.substr(0, equals_position
);
67 if (equals_position
!= CommandLine::StringType::npos
)
68 *switch_value
= string
.substr(equals_position
+ 1);
72 // Append switches and arguments, keeping switches before arguments.
73 void AppendSwitchesAndArguments(CommandLine
& command_line
,
74 const CommandLine::StringVector
& argv
) {
75 bool parse_switches
= true;
76 for (size_t i
= 1; i
< argv
.size(); ++i
) {
77 CommandLine::StringType arg
= argv
[i
];
78 TrimWhitespace(arg
, TRIM_ALL
, &arg
);
80 CommandLine::StringType switch_string
;
81 CommandLine::StringType switch_value
;
82 parse_switches
&= (arg
!= kSwitchTerminator
);
83 if (parse_switches
&& IsSwitch(arg
, &switch_string
, &switch_value
)) {
85 command_line
.AppendSwitchNative(UTF16ToASCII(switch_string
),
87 #elif defined(OS_POSIX)
88 command_line
.AppendSwitchNative(switch_string
, switch_value
);
91 command_line
.AppendArgNative(arg
);
96 // Lowercase switches for backwards compatiblity *on Windows*.
97 std::string
LowerASCIIOnWindows(const std::string
& string
) {
99 return StringToLowerASCII(string
);
100 #elif defined(OS_POSIX)
107 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
108 std::wstring
QuoteForCommandLineToArgvW(const std::wstring
& arg
) {
109 // We follow the quoting rules of CommandLineToArgvW.
110 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
111 if (arg
.find_first_of(L
" \\\"") == std::wstring::npos
) {
112 // No quoting necessary.
118 for (size_t i
= 0; i
< arg
.size(); ++i
) {
119 if (arg
[i
] == '\\') {
120 // Find the extent of this run of backslashes.
121 size_t start
= i
, end
= start
+ 1;
122 for (; end
< arg
.size() && arg
[end
] == '\\'; ++end
)
124 size_t backslash_count
= end
- start
;
126 // Backslashes are escapes only if the run is followed by a double quote.
127 // Since we also will end the string with a double quote, we escape for
128 // either a double quote or the end of the string.
129 if (end
== arg
.size() || arg
[end
] == '"') {
130 // To quote, we need to output 2x as many backslashes.
131 backslash_count
*= 2;
133 for (size_t j
= 0; j
< backslash_count
; ++j
)
136 // Advance i to one before the end to balance i++ in loop.
138 } else if (arg
[i
] == '"') {
142 out
.push_back(arg
[i
]);
153 CommandLine::CommandLine(NoProgram no_program
)
158 CommandLine::CommandLine(const FilePath
& program
)
164 CommandLine::CommandLine(int argc
, const CommandLine::CharType
* const* argv
)
167 InitFromArgv(argc
, argv
);
170 CommandLine::CommandLine(const StringVector
& argv
)
176 CommandLine::~CommandLine() {
181 void CommandLine::set_slash_is_not_a_switch() {
182 // The last switch prefix should be slash, so adjust the size to skip it.
183 DCHECK(wcscmp(kSwitchPrefixes
[arraysize(kSwitchPrefixes
) - 1], L
"/") == 0);
184 switch_prefix_count
= arraysize(kSwitchPrefixes
) - 1;
189 bool CommandLine::Init(int argc
, const char* const* argv
) {
190 if (current_process_commandline_
) {
191 // If this is intentional, Reset() must be called first. If we are using
192 // the shared build mode, we have to share a single object across multiple
197 current_process_commandline_
= new CommandLine(NO_PROGRAM
);
199 current_process_commandline_
->ParseFromString(::GetCommandLineW());
200 #elif defined(OS_POSIX)
201 current_process_commandline_
->InitFromArgv(argc
, argv
);
208 void CommandLine::Reset() {
209 DCHECK(current_process_commandline_
);
210 delete current_process_commandline_
;
211 current_process_commandline_
= NULL
;
215 CommandLine
* CommandLine::ForCurrentProcess() {
216 DCHECK(current_process_commandline_
);
217 return current_process_commandline_
;
221 bool CommandLine::InitializedForCurrentProcess() {
222 return !!current_process_commandline_
;
227 CommandLine
CommandLine::FromString(const std::wstring
& command_line
) {
228 CommandLine
cmd(NO_PROGRAM
);
229 cmd
.ParseFromString(command_line
);
234 void CommandLine::InitFromArgv(int argc
,
235 const CommandLine::CharType
* const* argv
) {
236 StringVector new_argv
;
237 for (int i
= 0; i
< argc
; ++i
)
238 new_argv
.push_back(argv
[i
]);
239 InitFromArgv(new_argv
);
242 void CommandLine::InitFromArgv(const StringVector
& argv
) {
243 argv_
= StringVector(1);
246 SetProgram(argv
.empty() ? FilePath() : FilePath(argv
[0]));
247 AppendSwitchesAndArguments(*this, argv
);
250 CommandLine::StringType
CommandLine::GetCommandLineString() const {
251 StringType
string(argv_
[0]);
253 string
= QuoteForCommandLineToArgvW(string
);
255 StringType
params(GetArgumentsString());
256 if (!params
.empty()) {
257 string
.append(StringType(FILE_PATH_LITERAL(" ")));
258 string
.append(params
);
263 CommandLine::StringType
CommandLine::GetArgumentsString() const {
265 // Append switches and arguments.
266 bool parse_switches
= true;
267 for (size_t i
= 1; i
< argv_
.size(); ++i
) {
268 StringType arg
= argv_
[i
];
269 StringType switch_string
;
270 StringType switch_value
;
271 parse_switches
&= arg
!= kSwitchTerminator
;
273 params
.append(StringType(FILE_PATH_LITERAL(" ")));
274 if (parse_switches
&& IsSwitch(arg
, &switch_string
, &switch_value
)) {
275 params
.append(switch_string
);
276 if (!switch_value
.empty()) {
278 switch_value
= QuoteForCommandLineToArgvW(switch_value
);
280 params
.append(kSwitchValueSeparator
+ switch_value
);
285 arg
= QuoteForCommandLineToArgvW(arg
);
293 FilePath
CommandLine::GetProgram() const {
294 return FilePath(argv_
[0]);
297 void CommandLine::SetProgram(const FilePath
& program
) {
298 TrimWhitespace(program
.value(), TRIM_ALL
, &argv_
[0]);
301 bool CommandLine::HasSwitch(const std::string
& switch_string
) const {
302 return switches_
.find(LowerASCIIOnWindows(switch_string
)) != switches_
.end();
305 std::string
CommandLine::GetSwitchValueASCII(
306 const std::string
& switch_string
) const {
307 StringType value
= GetSwitchValueNative(switch_string
);
308 if (!IsStringASCII(value
)) {
309 DLOG(WARNING
) << "Value of switch (" << switch_string
<< ") must be ASCII.";
310 return std::string();
313 return UTF16ToASCII(value
);
319 FilePath
CommandLine::GetSwitchValuePath(
320 const std::string
& switch_string
) const {
321 return FilePath(GetSwitchValueNative(switch_string
));
324 CommandLine::StringType
CommandLine::GetSwitchValueNative(
325 const std::string
& switch_string
) const {
326 SwitchMap::const_iterator result
=
327 switches_
.find(LowerASCIIOnWindows(switch_string
));
328 return result
== switches_
.end() ? StringType() : result
->second
;
331 void CommandLine::AppendSwitch(const std::string
& switch_string
) {
332 AppendSwitchNative(switch_string
, StringType());
335 void CommandLine::AppendSwitchPath(const std::string
& switch_string
,
336 const FilePath
& path
) {
337 AppendSwitchNative(switch_string
, path
.value());
340 void CommandLine::AppendSwitchNative(const std::string
& switch_string
,
341 const CommandLine::StringType
& value
) {
342 std::string
switch_key(LowerASCIIOnWindows(switch_string
));
344 StringType
combined_switch_string(ASCIIToWide(switch_key
));
345 #elif defined(OS_POSIX)
346 StringType
combined_switch_string(switch_string
);
348 size_t prefix_length
= GetSwitchPrefixLength(combined_switch_string
);
349 switches_
[switch_key
.substr(prefix_length
)] = value
;
350 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
351 if (prefix_length
== 0)
352 combined_switch_string
= kSwitchPrefixes
[0] + combined_switch_string
;
354 combined_switch_string
+= kSwitchValueSeparator
+ value
;
355 // Append the switch and update the switches/arguments divider |begin_args_|.
356 argv_
.insert(argv_
.begin() + begin_args_
++, combined_switch_string
);
359 void CommandLine::AppendSwitchASCII(const std::string
& switch_string
,
360 const std::string
& value_string
) {
362 AppendSwitchNative(switch_string
, ASCIIToWide(value_string
));
363 #elif defined(OS_POSIX)
364 AppendSwitchNative(switch_string
, value_string
);
368 void CommandLine::CopySwitchesFrom(const CommandLine
& source
,
369 const char* const switches
[],
371 for (size_t i
= 0; i
< count
; ++i
) {
372 if (source
.HasSwitch(switches
[i
]))
373 AppendSwitchNative(switches
[i
], source
.GetSwitchValueNative(switches
[i
]));
377 CommandLine::StringVector
CommandLine::GetArgs() const {
378 // Gather all arguments after the last switch (may include kSwitchTerminator).
379 StringVector
args(argv_
.begin() + begin_args_
, argv_
.end());
380 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
381 StringVector::iterator switch_terminator
=
382 std::find(args
.begin(), args
.end(), kSwitchTerminator
);
383 if (switch_terminator
!= args
.end())
384 args
.erase(switch_terminator
);
388 void CommandLine::AppendArg(const std::string
& value
) {
390 DCHECK(IsStringUTF8(value
));
391 AppendArgNative(UTF8ToWide(value
));
392 #elif defined(OS_POSIX)
393 AppendArgNative(value
);
397 void CommandLine::AppendArgPath(const FilePath
& path
) {
398 AppendArgNative(path
.value());
401 void CommandLine::AppendArgNative(const CommandLine::StringType
& value
) {
402 argv_
.push_back(value
);
405 void CommandLine::AppendArguments(const CommandLine
& other
,
406 bool include_program
) {
408 SetProgram(other
.GetProgram());
409 AppendSwitchesAndArguments(*this, other
.argv());
412 void CommandLine::PrependWrapper(const CommandLine::StringType
& wrapper
) {
415 // The wrapper may have embedded arguments (like "gdb --args"). In this case,
416 // we don't pretend to do anything fancy, we just split on spaces.
417 StringVector wrapper_argv
;
418 SplitString(wrapper
, FILE_PATH_LITERAL(' '), &wrapper_argv
);
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();
425 void CommandLine::ParseFromString(const std::wstring
& command_line
) {
426 std::wstring command_line_string
;
427 TrimWhitespace(command_line
, TRIM_ALL
, &command_line_string
);
428 if (command_line_string
.empty())
432 wchar_t** args
= NULL
;
433 args
= ::CommandLineToArgvW(command_line_string
.c_str(), &num_args
);
435 DPLOG_IF(FATAL
, !args
) << "CommandLineToArgvW failed on command line: "
436 << UTF16ToUTF8(command_line
);
437 InitFromArgv(num_args
, args
);