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/file_path.h"
12 #include "base/logging.h"
13 #include "base/string_util.h"
14 #include "base/strings/string_split.h"
15 #include "base/utf_string_conversions.h"
16 #include "build/build_config.h"
23 CommandLine
* CommandLine::current_process_commandline_
= NULL
;
26 const CommandLine::CharType kSwitchTerminator
[] = FILE_PATH_LITERAL("--");
27 const CommandLine::CharType kSwitchValueSeparator
[] = FILE_PATH_LITERAL("=");
28 // Since we use a lazy match, make sure that longer versions (like "--") are
29 // listed before shorter versions (like "-") of similar prefixes.
31 const CommandLine::CharType
* const kSwitchPrefixes
[] = {L
"--", L
"-", L
"/"};
32 #elif defined(OS_POSIX)
33 // Unixes don't use slash as a switch.
34 const CommandLine::CharType
* const kSwitchPrefixes
[] = {"--", "-"};
37 size_t GetSwitchPrefixLength(const CommandLine::StringType
& string
) {
38 for (size_t i
= 0; i
< arraysize(kSwitchPrefixes
); ++i
) {
39 CommandLine::StringType
prefix(kSwitchPrefixes
[i
]);
40 if (string
.compare(0, prefix
.length(), prefix
) == 0)
41 return prefix
.length();
46 // Fills in |switch_string| and |switch_value| if |string| is a switch.
47 // This will preserve the input switch prefix in the output |switch_string|.
48 bool IsSwitch(const CommandLine::StringType
& string
,
49 CommandLine::StringType
* switch_string
,
50 CommandLine::StringType
* switch_value
) {
51 switch_string
->clear();
52 switch_value
->clear();
53 size_t prefix_length
= GetSwitchPrefixLength(string
);
54 if (prefix_length
== 0 || prefix_length
== string
.length())
57 const size_t equals_position
= string
.find(kSwitchValueSeparator
);
58 *switch_string
= string
.substr(0, equals_position
);
59 if (equals_position
!= CommandLine::StringType::npos
)
60 *switch_value
= string
.substr(equals_position
+ 1);
64 // Append switches and arguments, keeping switches before arguments.
65 void AppendSwitchesAndArguments(CommandLine
& command_line
,
66 const CommandLine::StringVector
& argv
) {
67 bool parse_switches
= true;
68 for (size_t i
= 1; i
< argv
.size(); ++i
) {
69 CommandLine::StringType arg
= argv
[i
];
70 TrimWhitespace(arg
, TRIM_ALL
, &arg
);
72 CommandLine::StringType switch_string
;
73 CommandLine::StringType switch_value
;
74 parse_switches
&= (arg
!= kSwitchTerminator
);
75 if (parse_switches
&& IsSwitch(arg
, &switch_string
, &switch_value
)) {
77 command_line
.AppendSwitchNative(WideToASCII(switch_string
), switch_value
);
78 #elif defined(OS_POSIX)
79 command_line
.AppendSwitchNative(switch_string
, switch_value
);
82 command_line
.AppendArgNative(arg
);
87 // Lowercase switches for backwards compatiblity *on Windows*.
88 std::string
LowerASCIIOnWindows(const std::string
& string
) {
90 return StringToLowerASCII(string
);
91 #elif defined(OS_POSIX)
98 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
99 std::wstring
QuoteForCommandLineToArgvW(const std::wstring
& arg
) {
100 // We follow the quoting rules of CommandLineToArgvW.
101 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
102 if (arg
.find_first_of(L
" \\\"") == std::wstring::npos
) {
103 // No quoting necessary.
109 for (size_t i
= 0; i
< arg
.size(); ++i
) {
110 if (arg
[i
] == '\\') {
111 // Find the extent of this run of backslashes.
112 size_t start
= i
, end
= start
+ 1;
113 for (; end
< arg
.size() && arg
[end
] == '\\'; ++end
)
115 size_t backslash_count
= end
- start
;
117 // Backslashes are escapes only if the run is followed by a double quote.
118 // Since we also will end the string with a double quote, we escape for
119 // either a double quote or the end of the string.
120 if (end
== arg
.size() || arg
[end
] == '"') {
121 // To quote, we need to output 2x as many backslashes.
122 backslash_count
*= 2;
124 for (size_t j
= 0; j
< backslash_count
; ++j
)
127 // Advance i to one before the end to balance i++ in loop.
129 } else if (arg
[i
] == '"') {
133 out
.push_back(arg
[i
]);
144 CommandLine::CommandLine(NoProgram no_program
)
149 CommandLine::CommandLine(const FilePath
& program
)
155 CommandLine::CommandLine(int argc
, const CommandLine::CharType
* const* argv
)
158 InitFromArgv(argc
, argv
);
161 CommandLine::CommandLine(const StringVector
& argv
)
167 CommandLine::~CommandLine() {
171 bool CommandLine::Init(int argc
, const char* const* argv
) {
172 if (current_process_commandline_
) {
173 // If this is intentional, Reset() must be called first. If we are using
174 // the shared build mode, we have to share a single object across multiple
179 current_process_commandline_
= new CommandLine(NO_PROGRAM
);
181 current_process_commandline_
->ParseFromString(::GetCommandLineW());
182 #elif defined(OS_POSIX)
183 current_process_commandline_
->InitFromArgv(argc
, argv
);
190 void CommandLine::Reset() {
191 DCHECK(current_process_commandline_
);
192 delete current_process_commandline_
;
193 current_process_commandline_
= NULL
;
197 CommandLine
* CommandLine::ForCurrentProcess() {
198 DCHECK(current_process_commandline_
);
199 return current_process_commandline_
;
204 CommandLine
CommandLine::FromString(const std::wstring
& command_line
) {
205 CommandLine
cmd(NO_PROGRAM
);
206 cmd
.ParseFromString(command_line
);
211 void CommandLine::InitFromArgv(int argc
,
212 const CommandLine::CharType
* const* argv
) {
213 StringVector new_argv
;
214 for (int i
= 0; i
< argc
; ++i
)
215 new_argv
.push_back(argv
[i
]);
216 InitFromArgv(new_argv
);
219 void CommandLine::InitFromArgv(const StringVector
& argv
) {
220 argv_
= StringVector(1);
222 SetProgram(argv
.empty() ? FilePath() : FilePath(argv
[0]));
223 AppendSwitchesAndArguments(*this, argv
);
226 CommandLine::StringType
CommandLine::GetCommandLineString() const {
227 StringType
string(argv_
[0]);
229 string
= QuoteForCommandLineToArgvW(string
);
231 StringType
params(GetArgumentsString());
232 if (!params
.empty()) {
233 string
.append(StringType(FILE_PATH_LITERAL(" ")));
234 string
.append(params
);
239 CommandLine::StringType
CommandLine::GetArgumentsString() const {
241 // Append switches and arguments.
242 bool parse_switches
= true;
243 for (size_t i
= 1; i
< argv_
.size(); ++i
) {
244 StringType arg
= argv_
[i
];
245 StringType switch_string
;
246 StringType switch_value
;
247 parse_switches
&= arg
!= kSwitchTerminator
;
249 params
.append(StringType(FILE_PATH_LITERAL(" ")));
250 if (parse_switches
&& IsSwitch(arg
, &switch_string
, &switch_value
)) {
251 params
.append(switch_string
);
252 if (!switch_value
.empty()) {
254 switch_value
= QuoteForCommandLineToArgvW(switch_value
);
256 params
.append(kSwitchValueSeparator
+ switch_value
);
261 arg
= QuoteForCommandLineToArgvW(arg
);
269 FilePath
CommandLine::GetProgram() const {
270 return FilePath(argv_
[0]);
273 void CommandLine::SetProgram(const FilePath
& program
) {
274 TrimWhitespace(program
.value(), TRIM_ALL
, &argv_
[0]);
277 bool CommandLine::HasSwitch(const std::string
& switch_string
) const {
278 return switches_
.find(LowerASCIIOnWindows(switch_string
)) != switches_
.end();
281 std::string
CommandLine::GetSwitchValueASCII(
282 const std::string
& switch_string
) const {
283 StringType value
= GetSwitchValueNative(switch_string
);
284 if (!IsStringASCII(value
)) {
285 DLOG(WARNING
) << "Value of switch (" << switch_string
<< ") must be ASCII.";
286 return std::string();
289 return WideToASCII(value
);
295 FilePath
CommandLine::GetSwitchValuePath(
296 const std::string
& switch_string
) const {
297 return FilePath(GetSwitchValueNative(switch_string
));
300 CommandLine::StringType
CommandLine::GetSwitchValueNative(
301 const std::string
& switch_string
) const {
302 SwitchMap::const_iterator result
= switches_
.end();
303 result
= switches_
.find(LowerASCIIOnWindows(switch_string
));
304 return result
== switches_
.end() ? StringType() : result
->second
;
307 void CommandLine::AppendSwitch(const std::string
& switch_string
) {
308 AppendSwitchNative(switch_string
, StringType());
311 void CommandLine::AppendSwitchPath(const std::string
& switch_string
,
312 const FilePath
& path
) {
313 AppendSwitchNative(switch_string
, path
.value());
316 void CommandLine::AppendSwitchNative(const std::string
& switch_string
,
317 const CommandLine::StringType
& value
) {
318 std::string
switch_key(LowerASCIIOnWindows(switch_string
));
320 StringType
combined_switch_string(ASCIIToWide(switch_key
));
321 #elif defined(OS_POSIX)
322 StringType
combined_switch_string(switch_string
);
324 size_t prefix_length
= GetSwitchPrefixLength(combined_switch_string
);
325 switches_
[switch_key
.substr(prefix_length
)] = value
;
326 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
327 if (prefix_length
== 0)
328 combined_switch_string
= kSwitchPrefixes
[0] + combined_switch_string
;
330 combined_switch_string
+= kSwitchValueSeparator
+ value
;
331 // Append the switch and update the switches/arguments divider |begin_args_|.
332 argv_
.insert(argv_
.begin() + begin_args_
++, combined_switch_string
);
335 void CommandLine::AppendSwitchASCII(const std::string
& switch_string
,
336 const std::string
& value_string
) {
338 AppendSwitchNative(switch_string
, ASCIIToWide(value_string
));
339 #elif defined(OS_POSIX)
340 AppendSwitchNative(switch_string
, value_string
);
344 void CommandLine::CopySwitchesFrom(const CommandLine
& source
,
345 const char* const switches
[],
347 for (size_t i
= 0; i
< count
; ++i
) {
348 if (source
.HasSwitch(switches
[i
]))
349 AppendSwitchNative(switches
[i
], source
.GetSwitchValueNative(switches
[i
]));
353 CommandLine::StringVector
CommandLine::GetArgs() const {
354 // Gather all arguments after the last switch (may include kSwitchTerminator).
355 StringVector
args(argv_
.begin() + begin_args_
, argv_
.end());
356 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
357 StringVector::iterator switch_terminator
=
358 std::find(args
.begin(), args
.end(), kSwitchTerminator
);
359 if (switch_terminator
!= args
.end())
360 args
.erase(switch_terminator
);
364 void CommandLine::AppendArg(const std::string
& value
) {
366 DCHECK(IsStringUTF8(value
));
367 AppendArgNative(UTF8ToWide(value
));
368 #elif defined(OS_POSIX)
369 AppendArgNative(value
);
373 void CommandLine::AppendArgPath(const FilePath
& path
) {
374 AppendArgNative(path
.value());
377 void CommandLine::AppendArgNative(const CommandLine::StringType
& value
) {
378 argv_
.push_back(value
);
381 void CommandLine::AppendArguments(const CommandLine
& other
,
382 bool include_program
) {
384 SetProgram(other
.GetProgram());
385 AppendSwitchesAndArguments(*this, other
.argv());
388 void CommandLine::PrependWrapper(const CommandLine::StringType
& wrapper
) {
391 // The wrapper may have embedded arguments (like "gdb --args"). In this case,
392 // we don't pretend to do anything fancy, we just split on spaces.
393 StringVector wrapper_argv
;
394 base::SplitString(wrapper
, FILE_PATH_LITERAL(' '), &wrapper_argv
);
395 // Prepend the wrapper and update the switches/arguments |begin_args_|.
396 argv_
.insert(argv_
.begin(), wrapper_argv
.begin(), wrapper_argv
.end());
397 begin_args_
+= wrapper_argv
.size();
401 void CommandLine::ParseFromString(const std::wstring
& command_line
) {
402 std::wstring command_line_string
;
403 TrimWhitespace(command_line
, TRIM_ALL
, &command_line_string
);
404 if (command_line_string
.empty())
408 wchar_t** args
= NULL
;
409 args
= ::CommandLineToArgvW(command_line_string
.c_str(), &num_args
);
411 DPLOG_IF(FATAL
, !args
) << "CommandLineToArgvW failed on command line: "
413 InitFromArgv(num_args
, args
);