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