Supervised users: Re-check ManagementPolicy when ProfileIsSupervised changes.
[chromium-blink-merge.git] / base / command_line.cc
blob3e143cc5d449f358936726f33c8d3fda95064f03
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"
7 #include <algorithm>
8 #include <ostream>
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"
18 #if defined(OS_WIN)
19 #include <windows.h>
20 #include <shellapi.h>
21 #endif
23 namespace base {
25 CommandLine* CommandLine::current_process_commandline_ = NULL;
27 namespace {
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.
34 #if defined(OS_WIN)
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
37 // the array size.
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[] = {"--", "-"};
42 #endif
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();
51 return 0;
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())
63 return false;
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);
69 return true;
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)) {
84 #if defined(OS_WIN)
85 command_line->AppendSwitchNative(UTF16ToASCII(switch_string),
86 switch_value);
87 #elif defined(OS_POSIX)
88 command_line->AppendSwitchNative(switch_string, switch_value);
89 #endif
90 } else {
91 command_line->AppendArgNative(arg);
96 // Lowercase switches for backwards compatiblity *on Windows*.
97 #if defined(OS_WIN)
98 std::string LowerASCIIOnWindows(const std::string& string) {
99 return StringToLowerASCII(string);
101 #elif defined(OS_POSIX)
102 const std::string& LowerASCIIOnWindows(const std::string& string) {
103 return string;
105 #endif
108 #if defined(OS_WIN)
109 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
110 string16 QuoteForCommandLineToArgvW(const string16& arg,
111 bool quote_placeholders) {
112 // We follow the quoting rules of CommandLineToArgvW.
113 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
114 string16 quotable_chars(L" \\\"");
115 // We may also be required to quote '%', which is commonly used in a command
116 // line as a placeholder. (It may be substituted for a string with spaces.)
117 if (quote_placeholders)
118 quotable_chars.push_back(L'%');
119 if (arg.find_first_of(quotable_chars) == string16::npos) {
120 // No quoting necessary.
121 return arg;
124 string16 out;
125 out.push_back(L'"');
126 for (size_t i = 0; i < arg.size(); ++i) {
127 if (arg[i] == '\\') {
128 // Find the extent of this run of backslashes.
129 size_t start = i, end = start + 1;
130 for (; end < arg.size() && arg[end] == '\\'; ++end) {}
131 size_t backslash_count = end - start;
133 // Backslashes are escapes only if the run is followed by a double quote.
134 // Since we also will end the string with a double quote, we escape for
135 // either a double quote or the end of the string.
136 if (end == arg.size() || arg[end] == '"') {
137 // To quote, we need to output 2x as many backslashes.
138 backslash_count *= 2;
140 for (size_t j = 0; j < backslash_count; ++j)
141 out.push_back('\\');
143 // Advance i to one before the end to balance i++ in loop.
144 i = end - 1;
145 } else if (arg[i] == '"') {
146 out.push_back('\\');
147 out.push_back('"');
148 } else {
149 out.push_back(arg[i]);
152 out.push_back('"');
154 return out;
156 #endif
158 } // namespace
160 CommandLine::CommandLine(NoProgram no_program)
161 : argv_(1),
162 begin_args_(1) {
165 CommandLine::CommandLine(const FilePath& program)
166 : argv_(1),
167 begin_args_(1) {
168 SetProgram(program);
171 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
172 : argv_(1),
173 begin_args_(1) {
174 InitFromArgv(argc, argv);
177 CommandLine::CommandLine(const StringVector& argv)
178 : argv_(1),
179 begin_args_(1) {
180 InitFromArgv(argv);
183 CommandLine::~CommandLine() {
186 #if defined(OS_WIN)
187 // static
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_EQ(wcscmp(kSwitchPrefixes[arraysize(kSwitchPrefixes) - 1], L"/"), 0);
191 switch_prefix_count = arraysize(kSwitchPrefixes) - 1;
193 #endif
195 // static
196 bool CommandLine::Init(int argc, const char* const* argv) {
197 if (current_process_commandline_) {
198 // If this is intentional, Reset() must be called first. If we are using
199 // the shared build mode, we have to share a single object across multiple
200 // shared libraries.
201 return false;
204 current_process_commandline_ = new CommandLine(NO_PROGRAM);
205 #if defined(OS_WIN)
206 current_process_commandline_->ParseFromString(::GetCommandLineW());
207 #elif defined(OS_POSIX)
208 current_process_commandline_->InitFromArgv(argc, argv);
209 #endif
211 return true;
214 // static
215 void CommandLine::Reset() {
216 DCHECK(current_process_commandline_);
217 delete current_process_commandline_;
218 current_process_commandline_ = NULL;
221 // static
222 CommandLine* CommandLine::ForCurrentProcess() {
223 DCHECK(current_process_commandline_);
224 return current_process_commandline_;
227 // static
228 bool CommandLine::InitializedForCurrentProcess() {
229 return !!current_process_commandline_;
232 #if defined(OS_WIN)
233 // static
234 CommandLine CommandLine::FromString(const string16& command_line) {
235 CommandLine cmd(NO_PROGRAM);
236 cmd.ParseFromString(command_line);
237 return cmd;
239 #endif
241 void CommandLine::InitFromArgv(int argc,
242 const CommandLine::CharType* const* argv) {
243 StringVector new_argv;
244 for (int i = 0; i < argc; ++i)
245 new_argv.push_back(argv[i]);
246 InitFromArgv(new_argv);
249 void CommandLine::InitFromArgv(const StringVector& argv) {
250 argv_ = StringVector(1);
251 switches_.clear();
252 begin_args_ = 1;
253 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
254 AppendSwitchesAndArguments(this, argv);
257 FilePath CommandLine::GetProgram() const {
258 return FilePath(argv_[0]);
261 void CommandLine::SetProgram(const FilePath& program) {
262 TrimWhitespace(program.value(), TRIM_ALL, &argv_[0]);
265 bool CommandLine::HasSwitch(const std::string& switch_string) const {
266 return switches_.find(LowerASCIIOnWindows(switch_string)) != switches_.end();
269 bool CommandLine::HasSwitch(const char string_constant[]) const {
270 return HasSwitch(std::string(string_constant));
273 std::string CommandLine::GetSwitchValueASCII(
274 const std::string& switch_string) const {
275 StringType value = GetSwitchValueNative(switch_string);
276 if (!IsStringASCII(value)) {
277 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
278 return std::string();
280 #if defined(OS_WIN)
281 return UTF16ToASCII(value);
282 #else
283 return value;
284 #endif
287 FilePath CommandLine::GetSwitchValuePath(
288 const std::string& switch_string) const {
289 return FilePath(GetSwitchValueNative(switch_string));
292 CommandLine::StringType CommandLine::GetSwitchValueNative(
293 const std::string& switch_string) const {
294 SwitchMap::const_iterator result =
295 switches_.find(LowerASCIIOnWindows(switch_string));
296 return result == switches_.end() ? StringType() : result->second;
299 void CommandLine::AppendSwitch(const std::string& switch_string) {
300 AppendSwitchNative(switch_string, StringType());
303 void CommandLine::AppendSwitchPath(const std::string& switch_string,
304 const FilePath& path) {
305 AppendSwitchNative(switch_string, path.value());
308 void CommandLine::AppendSwitchNative(const std::string& switch_string,
309 const CommandLine::StringType& value) {
310 std::string switch_key(LowerASCIIOnWindows(switch_string));
311 #if defined(OS_WIN)
312 StringType combined_switch_string(ASCIIToUTF16(switch_key));
313 #elif defined(OS_POSIX)
314 StringType combined_switch_string(switch_string);
315 #endif
316 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
317 switches_[switch_key.substr(prefix_length)] = value;
318 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
319 if (prefix_length == 0)
320 combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
321 if (!value.empty())
322 combined_switch_string += kSwitchValueSeparator + value;
323 // Append the switch and update the switches/arguments divider |begin_args_|.
324 argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
327 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
328 const std::string& value_string) {
329 #if defined(OS_WIN)
330 AppendSwitchNative(switch_string, ASCIIToUTF16(value_string));
331 #elif defined(OS_POSIX)
332 AppendSwitchNative(switch_string, value_string);
333 #endif
336 void CommandLine::CopySwitchesFrom(const CommandLine& source,
337 const char* const switches[],
338 size_t count) {
339 for (size_t i = 0; i < count; ++i) {
340 if (source.HasSwitch(switches[i]))
341 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
345 CommandLine::StringVector CommandLine::GetArgs() const {
346 // Gather all arguments after the last switch (may include kSwitchTerminator).
347 StringVector args(argv_.begin() + begin_args_, argv_.end());
348 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
349 StringVector::iterator switch_terminator =
350 std::find(args.begin(), args.end(), kSwitchTerminator);
351 if (switch_terminator != args.end())
352 args.erase(switch_terminator);
353 return args;
356 void CommandLine::AppendArg(const std::string& value) {
357 #if defined(OS_WIN)
358 DCHECK(IsStringUTF8(value));
359 AppendArgNative(UTF8ToWide(value));
360 #elif defined(OS_POSIX)
361 AppendArgNative(value);
362 #endif
365 void CommandLine::AppendArgPath(const FilePath& path) {
366 AppendArgNative(path.value());
369 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
370 argv_.push_back(value);
373 void CommandLine::AppendArguments(const CommandLine& other,
374 bool include_program) {
375 if (include_program)
376 SetProgram(other.GetProgram());
377 AppendSwitchesAndArguments(this, other.argv());
380 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
381 if (wrapper.empty())
382 return;
383 // The wrapper may have embedded arguments (like "gdb --args"). In this case,
384 // we don't pretend to do anything fancy, we just split on spaces.
385 StringVector wrapper_argv;
386 SplitString(wrapper, FILE_PATH_LITERAL(' '), &wrapper_argv);
387 // Prepend the wrapper and update the switches/arguments |begin_args_|.
388 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
389 begin_args_ += wrapper_argv.size();
392 #if defined(OS_WIN)
393 void CommandLine::ParseFromString(const string16& command_line) {
394 string16 command_line_string;
395 TrimWhitespace(command_line, TRIM_ALL, &command_line_string);
396 if (command_line_string.empty())
397 return;
399 int num_args = 0;
400 wchar_t** args = NULL;
401 args = ::CommandLineToArgvW(command_line_string.c_str(), &num_args);
403 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
404 << UTF16ToUTF8(command_line);
405 InitFromArgv(num_args, args);
406 LocalFree(args);
408 #endif
410 CommandLine::StringType CommandLine::GetCommandLineStringInternal(
411 bool quote_placeholders) const {
412 StringType string(argv_[0]);
413 #if defined(OS_WIN)
414 string = QuoteForCommandLineToArgvW(string, quote_placeholders);
415 #endif
416 StringType params(GetArgumentsStringInternal(quote_placeholders));
417 if (!params.empty()) {
418 string.append(StringType(FILE_PATH_LITERAL(" ")));
419 string.append(params);
421 return string;
424 CommandLine::StringType CommandLine::GetArgumentsStringInternal(
425 bool quote_placeholders) const {
426 StringType params;
427 // Append switches and arguments.
428 bool parse_switches = true;
429 for (size_t i = 1; i < argv_.size(); ++i) {
430 StringType arg = argv_[i];
431 StringType switch_string;
432 StringType switch_value;
433 parse_switches &= arg != kSwitchTerminator;
434 if (i > 1)
435 params.append(StringType(FILE_PATH_LITERAL(" ")));
436 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
437 params.append(switch_string);
438 if (!switch_value.empty()) {
439 #if defined(OS_WIN)
440 switch_value =
441 QuoteForCommandLineToArgvW(switch_value, quote_placeholders);
442 #endif
443 params.append(kSwitchValueSeparator + switch_value);
445 } else {
446 #if defined(OS_WIN)
447 arg = QuoteForCommandLineToArgvW(arg, quote_placeholders);
448 #endif
449 params.append(arg);
452 return params;
455 } // namespace base