command_line.cc revision 4a5e2dc747d50c653511c68ccb2cfbfb740bd5a7
1// Copyright (c) 2010 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#if defined(OS_WIN) 8#include <windows.h> 9#include <shellapi.h> 10#elif defined(OS_POSIX) 11#include <limits.h> 12#include <stdlib.h> 13#include <unistd.h> 14#endif 15#if defined(OS_LINUX) 16#include <sys/prctl.h> 17#endif 18 19#include <algorithm> 20 21#include "base/file_path.h" 22#include "base/logging.h" 23#include "base/singleton.h" 24#include "base/string_split.h" 25#include "base/string_util.h" 26#include "base/sys_string_conversions.h" 27#include "base/utf_string_conversions.h" 28 29#if defined(OS_LINUX) 30// Linux/glibc doesn't natively have setproctitle(). 31#include "base/setproctitle_linux.h" 32#endif 33 34CommandLine* CommandLine::current_process_commandline_ = NULL; 35 36// Since we use a lazy match, make sure that longer versions (like L"--") 37// are listed before shorter versions (like L"-") of similar prefixes. 38#if defined(OS_WIN) 39const wchar_t* const kSwitchPrefixes[] = {L"--", L"-", L"/"}; 40const wchar_t kSwitchTerminator[] = L"--"; 41const wchar_t kSwitchValueSeparator[] = L"="; 42#elif defined(OS_POSIX) 43// Unixes don't use slash as a switch. 44const char* const kSwitchPrefixes[] = {"--", "-"}; 45const char kSwitchTerminator[] = "--"; 46const char kSwitchValueSeparator[] = "="; 47#endif 48 49#if defined(OS_WIN) 50// Lowercase a string. This is used to lowercase switch names. 51// Is this what we really want? It seems crazy to me. I've left it in 52// for backwards compatibility on Windows. 53static void Lowercase(std::string* parameter) { 54 transform(parameter->begin(), parameter->end(), parameter->begin(), 55 tolower); 56} 57#endif 58 59CommandLine::~CommandLine() { 60} 61 62#if defined(OS_WIN) 63CommandLine::CommandLine(NoProgram no_program) { 64} 65 66void CommandLine::ParseFromString(const std::wstring& command_line) { 67 TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); 68 69 if (command_line_string_.empty()) 70 return; 71 72 int num_args = 0; 73 wchar_t** args = NULL; 74 75 args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); 76 77 // Populate program_ with the trimmed version of the first arg. 78 TrimWhitespace(args[0], TRIM_ALL, &program_); 79 80 bool parse_switches = true; 81 for (int i = 1; i < num_args; ++i) { 82 std::wstring arg; 83 TrimWhitespace(args[i], TRIM_ALL, &arg); 84 85 if (!parse_switches) { 86 args_.push_back(arg); 87 continue; 88 } 89 90 if (arg == kSwitchTerminator) { 91 parse_switches = false; 92 continue; 93 } 94 95 std::string switch_string; 96 std::wstring switch_value; 97 if (IsSwitch(arg, &switch_string, &switch_value)) { 98 switches_[switch_string] = switch_value; 99 } else { 100 args_.push_back(arg); 101 } 102 } 103 104 if (args) 105 LocalFree(args); 106} 107 108// static 109CommandLine CommandLine::FromString(const std::wstring& command_line) { 110 CommandLine cmd; 111 cmd.ParseFromString(command_line); 112 return cmd; 113} 114 115CommandLine::CommandLine(const FilePath& program) { 116 if (!program.empty()) { 117 program_ = program.value(); 118 // TODO(evanm): proper quoting here. 119 command_line_string_ = L'"' + program.value() + L'"'; 120 } 121} 122 123#elif defined(OS_POSIX) 124CommandLine::CommandLine(NoProgram no_program) { 125 // Push an empty argument, because we always assume argv_[0] is a program. 126 argv_.push_back(""); 127} 128 129CommandLine::CommandLine(int argc, const char* const* argv) { 130 InitFromArgv(argc, argv); 131} 132 133CommandLine::CommandLine(const std::vector<std::string>& argv) { 134 InitFromArgv(argv); 135} 136 137void CommandLine::InitFromArgv(int argc, const char* const* argv) { 138 for (int i = 0; i < argc; ++i) 139 argv_.push_back(argv[i]); 140 InitFromArgv(argv_); 141} 142 143void CommandLine::InitFromArgv(const std::vector<std::string>& argv) { 144 argv_ = argv; 145 bool parse_switches = true; 146 for (size_t i = 1; i < argv_.size(); ++i) { 147 const std::string& arg = argv_[i]; 148 149 if (!parse_switches) { 150 args_.push_back(arg); 151 continue; 152 } 153 154 if (arg == kSwitchTerminator) { 155 parse_switches = false; 156 continue; 157 } 158 159 std::string switch_string; 160 std::string switch_value; 161 if (IsSwitch(arg, &switch_string, &switch_value)) { 162 switches_[switch_string] = switch_value; 163 } else { 164 args_.push_back(arg); 165 } 166 } 167} 168 169CommandLine::CommandLine(const FilePath& program) { 170 argv_.push_back(program.value()); 171} 172 173#endif 174 175// static 176bool CommandLine::IsSwitch(const StringType& parameter_string, 177 std::string* switch_string, 178 StringType* switch_value) { 179 switch_string->clear(); 180 switch_value->clear(); 181 182 for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { 183 StringType prefix(kSwitchPrefixes[i]); 184 if (parameter_string.find(prefix) != 0) 185 continue; 186 187 const size_t switch_start = prefix.length(); 188 const size_t equals_position = parameter_string.find( 189 kSwitchValueSeparator, switch_start); 190 StringType switch_native; 191 if (equals_position == StringType::npos) { 192 switch_native = parameter_string.substr(switch_start); 193 } else { 194 switch_native = parameter_string.substr( 195 switch_start, equals_position - switch_start); 196 *switch_value = parameter_string.substr(equals_position + 1); 197 } 198#if defined(OS_WIN) 199 *switch_string = WideToASCII(switch_native); 200 Lowercase(switch_string); 201#else 202 *switch_string = switch_native; 203#endif 204 205 return true; 206 } 207 208 return false; 209} 210 211// static 212void CommandLine::Init(int argc, const char* const* argv) { 213 delete current_process_commandline_; 214 current_process_commandline_ = new CommandLine; 215#if defined(OS_WIN) 216 current_process_commandline_->ParseFromString(::GetCommandLineW()); 217#elif defined(OS_POSIX) 218 current_process_commandline_->InitFromArgv(argc, argv); 219#endif 220 221#if defined(OS_LINUX) 222 if (argv) 223 setproctitle_init(const_cast<char**>(argv)); 224#endif 225} 226 227#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_NACL) 228// static 229void CommandLine::SetProcTitle() { 230 // Build a single string which consists of all the arguments separated 231 // by spaces. We can't actually keep them separate due to the way the 232 // setproctitle() function works. 233 std::string title; 234 bool have_argv0 = false; 235#if defined(OS_LINUX) 236 // In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us 237 // show up as "exe" in process listings. Read the symlink /proc/self/exe and 238 // use the path it points at for our process title. Note that this is only for 239 // display purposes and has no TOCTTOU security implications. 240 char buffer[PATH_MAX]; 241 // Note: readlink() does not append a null byte to terminate the string. 242 ssize_t length = readlink("/proc/self/exe", buffer, sizeof(buffer)); 243 DCHECK(length <= static_cast<ssize_t>(sizeof(buffer))); 244 if (length > 0) { 245 have_argv0 = true; 246 title.assign(buffer, length); 247 // If the binary has since been deleted, Linux appends " (deleted)" to the 248 // symlink target. Remove it, since this is not really part of our name. 249 const std::string kDeletedSuffix = " (deleted)"; 250 if (EndsWith(title, kDeletedSuffix, true)) 251 title.resize(title.size() - kDeletedSuffix.size()); 252#if defined(PR_SET_NAME) 253 // If PR_SET_NAME is available at compile time, we try using it. We ignore 254 // any errors if the kernel does not support it at runtime though. When 255 // available, this lets us set the short process name that shows when the 256 // full command line is not being displayed in most process listings. 257 prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str()); 258#endif 259 } 260#endif 261 for (size_t i = 1; i < current_process_commandline_->argv_.size(); ++i) { 262 if (!title.empty()) 263 title += " "; 264 title += current_process_commandline_->argv_[i]; 265 } 266 // Disable prepending argv[0] with '-' if we prepended it ourselves above. 267 setproctitle(have_argv0 ? "-%s" : "%s", title.c_str()); 268} 269#endif 270 271void CommandLine::Reset() { 272 DCHECK(current_process_commandline_ != NULL); 273 delete current_process_commandline_; 274 current_process_commandline_ = NULL; 275} 276 277// static 278CommandLine* CommandLine::ForCurrentProcess() { 279 DCHECK(current_process_commandline_); 280 return current_process_commandline_; 281} 282 283bool CommandLine::HasSwitch(const std::string& switch_string) const { 284 std::string lowercased_switch(switch_string); 285#if defined(OS_WIN) 286 Lowercase(&lowercased_switch); 287#endif 288 return switches_.find(lowercased_switch) != switches_.end(); 289} 290 291#if defined(OS_WIN) 292// Deprecated; still temporarily available on Windows. 293bool CommandLine::HasSwitch(const std::wstring& switch_string) const { 294 return HasSwitch(WideToASCII(switch_string)); 295} 296#endif 297 298std::string CommandLine::GetSwitchValueASCII( 299 const std::string& switch_string) const { 300 CommandLine::StringType value = GetSwitchValueNative(switch_string); 301 if (!IsStringASCII(value)) { 302 LOG(WARNING) << "Value of --" << switch_string << " must be ASCII."; 303 return ""; 304 } 305#if defined(OS_WIN) 306 return WideToASCII(value); 307#else 308 return value; 309#endif 310} 311 312FilePath CommandLine::GetSwitchValuePath( 313 const std::string& switch_string) const { 314 return FilePath(GetSwitchValueNative(switch_string)); 315} 316 317CommandLine::StringType CommandLine::GetSwitchValueNative( 318 const std::string& switch_string) const { 319 std::string lowercased_switch(switch_string); 320#if defined(OS_WIN) 321 Lowercase(&lowercased_switch); 322#endif 323 324 std::map<std::string, StringType>::const_iterator result = 325 switches_.find(lowercased_switch); 326 327 if (result == switches_.end()) { 328 return CommandLine::StringType(); 329 } else { 330 return result->second; 331 } 332} 333 334FilePath CommandLine::GetProgram() const { 335#if defined(OS_WIN) 336 return FilePath(program_); 337#else 338 DCHECK_GT(argv_.size(), 0U); 339 return FilePath(argv_[0]); 340#endif 341} 342 343#if defined(OS_POSIX) 344std::string CommandLine::command_line_string() const { 345 return JoinString(argv_, ' '); 346} 347#endif 348 349#if defined(OS_WIN) 350void CommandLine::AppendSwitch(const std::string& switch_string) { 351 command_line_string_.append(L" "); 352 command_line_string_.append(kSwitchPrefixes[0] + ASCIIToWide(switch_string)); 353 switches_[switch_string] = L""; 354} 355 356void CommandLine::AppendSwitchASCII(const std::string& switch_string, 357 const std::string& value_string) { 358 AppendSwitchNative(switch_string, ASCIIToWide(value_string)); 359} 360 361// Quote a string if necessary, such that CommandLineToArgvW() will 362// always process it as a single argument. 363static std::wstring WindowsStyleQuote(const std::wstring& arg) { 364 // We follow the quoting rules of CommandLineToArgvW. 365 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx 366 if (arg.find_first_of(L" \\\"") == std::wstring::npos) { 367 // No quoting necessary. 368 return arg; 369 } 370 371 std::wstring out; 372 out.push_back(L'"'); 373 for (size_t i = 0; i < arg.size(); ++i) { 374 if (arg[i] == '\\') { 375 // Find the extent of this run of backslashes. 376 size_t start = i, end = start + 1; 377 for (; end < arg.size() && arg[end] == '\\'; ++end) 378 /* empty */; 379 size_t backslash_count = end - start; 380 381 // Backslashes are escapes only if the run is followed by a double quote. 382 // Since we also will end the string with a double quote, we escape for 383 // either a double quote or the end of the string. 384 if (end == arg.size() || arg[end] == '"') { 385 // To quote, we need to output 2x as many backslashes. 386 backslash_count *= 2; 387 } 388 for (size_t j = 0; j < backslash_count; ++j) 389 out.push_back('\\'); 390 391 // Advance i to one before the end to balance i++ in loop. 392 i = end - 1; 393 } else if (arg[i] == '"') { 394 out.push_back('\\'); 395 out.push_back('"'); 396 } else { 397 out.push_back(arg[i]); 398 } 399 } 400 out.push_back('"'); 401 402 return out; 403} 404 405void CommandLine::AppendSwitchNative(const std::string& switch_string, 406 const std::wstring& value) { 407 std::wstring combined_switch_string = 408 kSwitchPrefixes[0] + ASCIIToWide(switch_string); 409 if (!value.empty()) 410 combined_switch_string += kSwitchValueSeparator + WindowsStyleQuote(value); 411 412 command_line_string_.append(L" "); 413 command_line_string_.append(combined_switch_string); 414 415 switches_[switch_string] = value; 416} 417 418void CommandLine::AppendArg(const std::string& value) { 419 DCHECK(IsStringUTF8(value)); 420 AppendArgNative(UTF8ToWide(value)); 421} 422 423void CommandLine::AppendArgNative(const std::wstring& value) { 424 command_line_string_.append(L" "); 425 command_line_string_.append(WindowsStyleQuote(value)); 426 args_.push_back(value); 427} 428 429void CommandLine::AppendArguments(const CommandLine& other, 430 bool include_program) { 431 // Verify include_program is used correctly. 432 // Logic could be shorter but this is clearer. 433 DCHECK_EQ(include_program, !other.GetProgram().empty()); 434 if (include_program) 435 program_ = other.program_; 436 437 if (!command_line_string_.empty()) 438 command_line_string_ += L' '; 439 440 command_line_string_ += other.command_line_string_; 441 442 std::map<std::string, StringType>::const_iterator i; 443 for (i = other.switches_.begin(); i != other.switches_.end(); ++i) 444 switches_[i->first] = i->second; 445} 446 447void CommandLine::PrependWrapper(const std::wstring& wrapper) { 448 if (wrapper.empty()) 449 return; 450 // The wrapper may have embedded arguments (like "gdb --args"). In this case, 451 // we don't pretend to do anything fancy, we just split on spaces. 452 std::vector<std::wstring> wrapper_and_args; 453 base::SplitString(wrapper, ' ', &wrapper_and_args); 454 program_ = wrapper_and_args[0]; 455 command_line_string_ = wrapper + L" " + command_line_string_; 456} 457 458#elif defined(OS_POSIX) 459void CommandLine::AppendSwitch(const std::string& switch_string) { 460 argv_.push_back(kSwitchPrefixes[0] + switch_string); 461 switches_[switch_string] = ""; 462} 463 464void CommandLine::AppendSwitchNative(const std::string& switch_string, 465 const std::string& value) { 466 std::string combined_switch_string = kSwitchPrefixes[0] + switch_string; 467 if (!value.empty()) 468 combined_switch_string += kSwitchValueSeparator + value; 469 argv_.push_back(combined_switch_string); 470 switches_[switch_string] = value; 471} 472 473void CommandLine::AppendSwitchASCII(const std::string& switch_string, 474 const std::string& value_string) { 475 AppendSwitchNative(switch_string, value_string); 476} 477 478void CommandLine::AppendArg(const std::string& value) { 479 AppendArgNative(value); 480} 481 482void CommandLine::AppendArgNative(const std::string& value) { 483 DCHECK(IsStringUTF8(value)); 484 argv_.push_back(value); 485} 486 487void CommandLine::AppendArguments(const CommandLine& other, 488 bool include_program) { 489 // Verify include_program is used correctly. 490 // Logic could be shorter but this is clearer. 491 DCHECK_EQ(include_program, !other.GetProgram().empty()); 492 493 if (include_program) 494 argv_[0] = other.argv_[0]; 495 496 // Skip the first arg when copying since it's the program but push all 497 // arguments to our arg vector. 498 for (size_t i = 1; i < other.argv_.size(); ++i) 499 argv_.push_back(other.argv_[i]); 500 501 std::map<std::string, StringType>::const_iterator i; 502 for (i = other.switches_.begin(); i != other.switches_.end(); ++i) 503 switches_[i->first] = i->second; 504} 505 506void CommandLine::PrependWrapper(const std::string& wrapper) { 507 // The wrapper may have embedded arguments (like "gdb --args"). In this case, 508 // we don't pretend to do anything fancy, we just split on spaces. 509 std::vector<std::string> wrapper_and_args; 510 base::SplitString(wrapper, ' ', &wrapper_and_args); 511 argv_.insert(argv_.begin(), wrapper_and_args.begin(), wrapper_and_args.end()); 512} 513 514#endif 515 516void CommandLine::AppendArgPath(const FilePath& path) { 517 AppendArgNative(path.value()); 518} 519 520void CommandLine::AppendSwitchPath(const std::string& switch_string, 521 const FilePath& path) { 522 AppendSwitchNative(switch_string, path.value()); 523} 524 525void CommandLine::CopySwitchesFrom(const CommandLine& source, 526 const char* const switches[], 527 size_t count) { 528 for (size_t i = 0; i < count; ++i) { 529 if (source.HasSwitch(switches[i])) { 530 StringType value = source.GetSwitchValueNative(switches[i]); 531 AppendSwitchNative(switches[i], value); 532 } 533 } 534} 535 536// private 537CommandLine::CommandLine() { 538} 539 540// static 541CommandLine* CommandLine::ForCurrentProcessMutable() { 542 DCHECK(current_process_commandline_); 543 return current_process_commandline_; 544} 545