diff options
author | evan@chromium.org <evan@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-01-21 01:00:22 +0000 |
---|---|---|
committer | evan@chromium.org <evan@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-01-21 01:00:22 +0000 |
commit | bb97536b768ac68fcbc4605c35461a798ef6e5ff (patch) | |
tree | 479bde96cd05a9e1f9d2746dd82313e2eb715e8e /base | |
parent | 8731a63268015f4e5d684833c11a1b44bd9ae468 (diff) | |
download | chromium_src-bb97536b768ac68fcbc4605c35461a798ef6e5ff.zip chromium_src-bb97536b768ac68fcbc4605c35461a798ef6e5ff.tar.gz chromium_src-bb97536b768ac68fcbc4605c35461a798ef6e5ff.tar.bz2 |
Make CommandLine into a normal object, with some statics for getting at the current process's command line.
One explicit goal of this change is to *not* deal with the string/wstring issues at the API on POSIX; the functions are the same as before, which means they remain as broken as before. (I did try to fix the internals, though, so migrating the callers is now possible by adding platform-appropriate hooks.)
Review URL: http://codereview.chromium.org/18248
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@8347 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'base')
-rw-r--r-- | base/command_line.cc | 468 | ||||
-rw-r--r-- | base/command_line.h | 159 | ||||
-rw-r--r-- | base/command_line_unittest.cc | 73 | ||||
-rw-r--r-- | base/logging.cc | 3 | ||||
-rw-r--r-- | base/multiprocess_test.h | 31 | ||||
-rw-r--r-- | base/perf_test_suite.h | 3 | ||||
-rw-r--r-- | base/process_util.h | 2 | ||||
-rw-r--r-- | base/process_util_linux.cc | 9 | ||||
-rw-r--r-- | base/test_suite.h | 7 |
9 files changed, 377 insertions, 378 deletions
diff --git a/base/command_line.cc b/base/command_line.cc index 6e02e1d..cf3e36f 100644 --- a/base/command_line.cc +++ b/base/command_line.cc @@ -17,302 +17,228 @@ #include "base/string_util.h" #include "base/sys_string_conversions.h" -using namespace std; +CommandLine* CommandLine::current_process_commandline_ = NULL; // Since we use a lazy match, make sure that longer versions (like L"--") // are listed before shorter versions (like L"-") of similar prefixes. #if defined(OS_WIN) -const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-", L"/"}; +const wchar_t* const kSwitchPrefixes[] = {L"--", L"-", L"/"}; +const wchar_t kSwitchTerminator[] = L"--"; +const wchar_t kSwitchValueSeparator[] = L"="; #elif defined(OS_POSIX) // Unixes don't use slash as a switch. -const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-"}; +const char* const kSwitchPrefixes[] = {"--", "-"}; +const char kSwitchTerminator[] = "--"; +const char kSwitchValueSeparator[] = "="; #endif -const wchar_t CommandLine::kSwitchValueSeparator[] = L"="; -const wchar_t CommandLine::kSwitchTerminator[] = L"--"; - -// Needed to avoid a typecast on the tolower() function pointer in Lowercase(). -// MSVC accepts it as-is but GCC requires the typecast. -static int ToLower(int c) { - return tolower(c); -} - -static void Lowercase(wstring* parameter) { - transform(parameter->begin(), parameter->end(), parameter->begin(), - ToLower); +#if defined(OS_WIN) +// Lowercase a string. This is used to lowercase switch names. +// Is this what we really want? It seems crazy to me. I've left it in +// for backwards compatibility on Windows. +static void Lowercase(std::wstring* parameter) { + transform(parameter->begin(), parameter->end(), parameter->begin(), + tolower); } +#endif -// CommandLine::Data -// -// This object holds the parsed data for a command line. We hold this in a -// separate object from |CommandLine| so that we can share the parsed data -// across multiple |CommandLine| objects. When we share |Data|, we might be -// accessing this object on multiple threads. To ensure thread safety, the -// public interface of this object is const only. -// -// Do NOT add any non-const methods to this object. You have been warned. -class CommandLine::Data { - public: #if defined(OS_WIN) - Data() { - Init(GetCommandLineW()); - } +void CommandLine::ParseFromString(const std::wstring& command_line) { + TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); - Data(const wstring& command_line) { - Init(command_line); - } -#elif defined(OS_POSIX) - Data() { - // Owner must call Init(). - } + if (command_line_string_.empty()) + return; - Data(int argc, const char* const* argv) { - Init(argc, argv); - } -#endif // defined(OS_POSIX) + int num_args = 0; + wchar_t** args = NULL; -#if defined(OS_WIN) - // Does the actual parsing of the command line. - void Init(const std::wstring& command_line) { - TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); - - if (command_line_string_.empty()) - return; - - int num_args = 0; - wchar_t** args = NULL; - - args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); - - // Populate program_ with the trimmed version of the first arg. - TrimWhitespace(args[0], TRIM_ALL, &program_); - - bool parse_switches = true; - for (int i = 1; i < num_args; ++i) { - wstring arg; - TrimWhitespace(args[i], TRIM_ALL, &arg); - - if (!parse_switches) { - loose_values_.push_back(arg); - continue; - } - - if (arg == kSwitchTerminator) { - parse_switches = false; - continue; - } - - wstring switch_string; - wstring switch_value; - if (IsSwitch(arg, &switch_string, &switch_value)) { - switches_[switch_string] = switch_value; - } else { - loose_values_.push_back(arg); - } - } + args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); - if (args) - LocalFree(args); - } -#elif defined(OS_POSIX) - // Does the actual parsing of the command line. - void Init(int argc, const char* const* argv) { - if (argc < 1) - return; - program_ = base::SysNativeMBToWide(argv[0]); - argv_.push_back(std::string(argv[0])); - command_line_string_ = program_; - - bool parse_switches = true; - for (int i = 1; i < argc; ++i) { - std::wstring arg = base::SysNativeMBToWide(argv[i]); - argv_.push_back(argv[i]); - command_line_string_.append(L" "); - command_line_string_.append(arg); - - if (!parse_switches) { - loose_values_.push_back(arg); - continue; - } - - if (arg == kSwitchTerminator) { - parse_switches = false; - continue; - } - - wstring switch_string; - wstring switch_value; - if (IsSwitch(arg, &switch_string, &switch_value)) { - switches_[switch_string] = switch_value; - } else { - loose_values_.push_back(arg); - } + // Populate program_ with the trimmed version of the first arg. + TrimWhitespace(args[0], TRIM_ALL, &program_); + + bool parse_switches = true; + for (int i = 1; i < num_args; ++i) { + std::wstring arg; + TrimWhitespace(args[i], TRIM_ALL, &arg); + + if (!parse_switches) { + loose_values_.push_back(arg); + continue; } - } -#endif - const std::wstring& command_line_string() const { - return command_line_string_; - } + if (arg == kSwitchTerminator) { + parse_switches = false; + continue; + } - const std::wstring& program() const { - return program_; + std::string switch_string; + std::wstring switch_value; + if (IsSwitch(arg, &switch_string, &switch_value)) { + switches_[switch_string] = switch_value; + } else { + loose_values_.push_back(arg); + } } - const std::map<std::wstring, std::wstring>& switches() const { - return switches_; + if (args) + LocalFree(args); +} +CommandLine::CommandLine(const std::wstring& program) { + if (!program.empty()) { + program_ = program; + command_line_string_ = L'"' + program + L'"'; } +} +#elif defined(OS_POSIX) +CommandLine::CommandLine(int argc, const char* const* argv) { + for (int i = 0; i < argc; ++i) + argv_.push_back(argv[i]); + InitFromArgv(); +} +CommandLine::CommandLine(const std::vector<std::string>& argv) { + argv_ = argv; + InitFromArgv(); +} - const std::vector<std::wstring>& loose_values() const { - return loose_values_; - } +void CommandLine::InitFromArgv() { + bool parse_switches = true; + for (size_t i = 1; i < argv_.size(); ++i) { + const std::string& arg = argv_[i]; -#if defined(OS_POSIX) - const std::vector<std::string>& argv() const { - return argv_; - } -#endif + if (!parse_switches) { + loose_values_.push_back(arg); + continue; + } - private: - // Returns true if parameter_string represents a switch. If true, - // switch_string and switch_value are set. (If false, both are - // set to the empty string.) - static bool IsSwitch(const wstring& parameter_string, - wstring* switch_string, - wstring* switch_value) { - - *switch_string = L""; - *switch_value = L""; - - for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { - std::wstring prefix(kSwitchPrefixes[i]); - if (parameter_string.find(prefix) != 0) // check prefix - continue; - - const size_t switch_start = prefix.length(); - const size_t equals_position = parameter_string.find( - kSwitchValueSeparator, switch_start); - if (equals_position == wstring::npos) { - *switch_string = parameter_string.substr(switch_start); - } else { - *switch_string = parameter_string.substr( - switch_start, equals_position - switch_start); - *switch_value = parameter_string.substr(equals_position + 1); - } - Lowercase(switch_string); - - return true; + if (arg == kSwitchTerminator) { + parse_switches = false; + continue; } - return false; + std::string switch_string; + std::string switch_value; + if (IsSwitch(arg, &switch_string, &switch_value)) { + switches_[switch_string] = switch_value; + } else { + loose_values_.push_back(arg); + } } +} - std::wstring command_line_string_; - std::wstring program_; - std::map<std::wstring, std::wstring> switches_; - std::vector<std::wstring> loose_values_; - std::vector<std::string> argv_; - - DISALLOW_EVIL_CONSTRUCTORS(Data); -}; - -CommandLine::CommandLine() - : we_own_data_(false), // The Singleton class will manage it for us. - data_(Singleton<Data>::get()) { - DCHECK(!data_->command_line_string().empty()) << - "You must call CommandLine::SetArgcArgv before making any CommandLine " - "calls."; +CommandLine::CommandLine(const std::wstring& program) { + argv_.push_back(WideToASCII(program)); } +#endif +// static +bool CommandLine::IsSwitch(const StringType& parameter_string, + std::string* switch_string, + StringType* switch_value) { + switch_string->clear(); + switch_value->clear(); + + for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { + StringType prefix(kSwitchPrefixes[i]); + if (parameter_string.find(prefix) != 0) + continue; + + const size_t switch_start = prefix.length(); + const size_t equals_position = parameter_string.find( + kSwitchValueSeparator, switch_start); + StringType switch_native; + if (equals_position == StringType::npos) { + switch_native = parameter_string.substr(switch_start); + } else { + switch_native = parameter_string.substr( + switch_start, equals_position - switch_start); + *switch_value = parameter_string.substr(equals_position + 1); + } #if defined(OS_WIN) -CommandLine::CommandLine(const wstring& command_line) - : we_own_data_(true), - data_(new Data(command_line)) { -} -#elif defined(OS_POSIX) -CommandLine::CommandLine(const int argc, const char* const* argv) - : we_own_data_(true), - data_(new Data(argc, argv)) { -} + Lowercase(&switch_native); + *switch_string = WideToASCII(switch_native); +#else + *switch_string = switch_native; +#endif -CommandLine::CommandLine(const std::vector<std::string>& argv) - : we_own_data_(true) { - const char* argv_copy[argv.size()]; - for (size_t i = 0; i < argv.size(); i++) { - argv_copy[i] = argv[i].c_str(); + return true; } - data_ = new Data(argv.size(), argv_copy); -} -#endif -CommandLine::~CommandLine() { - if (we_own_data_) - delete data_; + return false; } // static -void CommandLine::SetArgcArgv(int argc, const char* const* argv) { -#if !defined(OS_WIN) - Singleton<Data>::get()->Init(argc, argv); +void CommandLine::Init(int argc, const char* const* argv) { + DCHECK(current_process_commandline_ == NULL); +#if defined(OS_WIN) + current_process_commandline_ = new CommandLine; + current_process_commandline_->ParseFromString(::GetCommandLineW()); +#elif defined(OS_POSIX) + current_process_commandline_ = new CommandLine(argc, argv); #endif } -bool CommandLine::HasSwitch(const wstring& switch_string) const { - wstring lowercased_switch(switch_string); +bool CommandLine::HasSwitch(const std::wstring& switch_string) const { + std::wstring lowercased_switch(switch_string); +#if defined(OS_WIN) Lowercase(&lowercased_switch); - return data_->switches().find(lowercased_switch) != data_->switches().end(); +#endif + return switches_.find(WideToASCII(lowercased_switch)) != switches_.end(); } -wstring CommandLine::GetSwitchValue(const wstring& switch_string) const { - wstring lowercased_switch(switch_string); +std::wstring CommandLine::GetSwitchValue( + const std::wstring& switch_string) const { + std::wstring lowercased_switch(switch_string); +#if defined(OS_WIN) Lowercase(&lowercased_switch); +#endif - const map<wstring, wstring>::const_iterator result = - data_->switches().find(lowercased_switch); + std::map<std::string, StringType>::const_iterator result = + switches_.find(WideToASCII(lowercased_switch)); - if (result == data_->switches().end()) { + if (result == switches_.end()) { return L""; } else { +#if defined(OS_WIN) return result->second; +#else + return ASCIIToWide(result->second); +#endif } } -size_t CommandLine::GetLooseValueCount() const { - return data_->loose_values().size(); -} - -CommandLine::LooseValueIterator CommandLine::GetLooseValuesBegin() const { - return data_->loose_values().begin(); +#if defined(OS_WIN) +std::vector<std::wstring> CommandLine::GetLooseValues() const { + return loose_values_; } - -CommandLine::LooseValueIterator CommandLine::GetLooseValuesEnd() const { - return data_->loose_values().end(); +std::wstring CommandLine::program() const { + return program_; } - -std::wstring CommandLine::command_line_string() const { - return data_->command_line_string(); +#else +std::vector<std::wstring> CommandLine::GetLooseValues() const { + std::vector<std::wstring> values; + for (size_t i = 0; i < loose_values_.size(); ++i) + values.push_back(ASCIIToWide(loose_values_[i])); + return values; } - -#if defined(OS_POSIX) -const std::vector<std::string>& CommandLine::argv() const { - return data_->argv(); +std::wstring CommandLine::program() const { + DCHECK(argv_.size() > 0); + return ASCIIToWide(argv_[0]); } #endif -std::wstring CommandLine::program() const { - return data_->program(); -} // static -wstring CommandLine::PrefixedSwitchString(const wstring& switch_string) { +std::wstring CommandLine::PrefixedSwitchString( + const std::wstring& switch_string) { return StringPrintf(L"%ls%ls", kSwitchPrefixes[0], switch_string.c_str()); } // static -wstring CommandLine::PrefixedSwitchStringWithValue( - const wstring& switch_string, const wstring& value_string) { +std::wstring CommandLine::PrefixedSwitchStringWithValue( + const std::wstring& switch_string, const std::wstring& value_string) { if (value_string.empty()) { return PrefixedSwitchString(switch_string); } @@ -324,20 +250,17 @@ wstring CommandLine::PrefixedSwitchStringWithValue( value_string.c_str()); } -// static -void CommandLine::AppendSwitch(wstring* command_line_string, - const wstring& switch_string) { - DCHECK(command_line_string); - wstring prefixed_switch_string = PrefixedSwitchString(switch_string); - command_line_string->append(L" "); - command_line_string->append(prefixed_switch_string); +#if defined(OS_WIN) +void CommandLine::AppendSwitch(const std::wstring& switch_string) { + std::wstring prefixed_switch_string = PrefixedSwitchString(switch_string); + command_line_string_.append(L" "); + command_line_string_.append(prefixed_switch_string); + switches_[WideToASCII(switch_string)] = L""; } -// static -void CommandLine::AppendSwitchWithValue(wstring* command_line_string, - const wstring& switch_string, - const wstring& value_string) { - wstring value_string_edit; +void CommandLine::AppendSwitchWithValue(const std::wstring& switch_string, + const std::wstring& value_string) { + std::wstring value_string_edit; // NOTE(jhughes): If the value contains a quotation mark at one // end but not both, you may get unusable output. @@ -351,10 +274,65 @@ void CommandLine::AppendSwitchWithValue(wstring* command_line_string, value_string_edit = value_string; } - wstring combined_switch_string = + std::wstring combined_switch_string = PrefixedSwitchStringWithValue(switch_string, value_string_edit); - command_line_string->append(L" "); - command_line_string->append(combined_switch_string); + command_line_string_.append(L" "); + command_line_string_.append(combined_switch_string); + + switches_[WideToASCII(switch_string)] = value_string; +} + +void CommandLine::AppendLooseValue(const std::wstring& value) { + // TODO(evan): quoting? + command_line_string_.append(L" "); + command_line_string_.append(value); +} + +void CommandLine::AppendArguments(const CommandLine& other, + bool include_program) { + // Verify include_program is used correctly. + // Logic could be shorter but this is clearer. + DCHECK(include_program ? !other.program().empty() : other.program().empty()); + command_line_string_ += L" " + other.command_line_string_; + std::map<std::string, StringType>::const_iterator i; + for (i = other.switches_.begin(); i != other.switches_.end(); ++i) + switches_[i->first] = i->second; } +#elif defined(OS_POSIX) +void CommandLine::AppendSwitch(const std::wstring& switch_string) { + std::string ascii_switch = WideToASCII(switch_string); + argv_.push_back(kSwitchPrefixes[0] + ascii_switch); + switches_[ascii_switch] = ""; +} + +void CommandLine::AppendSwitchWithValue(const std::wstring& switch_string, + const std::wstring& value_string) { + std::string ascii_switch = WideToASCII(switch_string); + std::string ascii_value = WideToASCII(value_string); + + argv_.push_back(kSwitchPrefixes[0] + ascii_switch + + kSwitchValueSeparator + ascii_value); + switches_[ascii_switch] = ascii_value; +} + +void CommandLine::AppendLooseValue(const std::wstring& value) { + argv_.push_back(WideToASCII(value)); +} + +void CommandLine::AppendArguments(const CommandLine& other, + bool include_program) { + // Verify include_program is used correctly. + // Logic could be shorter but this is clearer. + DCHECK(include_program ? !other.program().empty() : other.program().empty()); + + size_t first_arg = include_program ? 0 : 1; + for (size_t i = first_arg; i < other.argv_.size(); ++i) + argv_.push_back(other.argv_[i]); + std::map<std::string, StringType>::const_iterator i; + for (i = other.switches_.begin(); i != other.switches_.end(); ++i) + switches_[i->first] = i->second; +} +#endif + diff --git a/base/command_line.h b/base/command_line.h index 56aa2fc..f1a2005 100644 --- a/base/command_line.h +++ b/base/command_line.h @@ -2,46 +2,60 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// This file contains a class that can be used to extract the salient -// elements of a command line in a relatively lightweight manner. +// This class works with command lines: building and parsing. // Switches can optionally have a value attached using an equals sign, // as in "-switch=value". Arguments that aren't prefixed with a -// switch prefix are considered "loose parameters". Switch names -// are case-insensitive. An argument of "--" will terminate switch parsing, -// causing everything after to be considered as loose parameters. +// switch prefix are considered "loose parameters". Switch names are +// case-insensitive. An argument of "--" will terminate switch +// parsing, causing everything after to be considered as loose +// parameters. + +// There is a singleton read-only CommandLine that represents the command +// line that the current process was started with. It must be initialized +// in main() (or whatever the platform's equivalent function is). #ifndef BASE_COMMAND_LINE_H_ #define BASE_COMMAND_LINE_H_ +#include "build/build_config.h" + #include <map> #include <string> #include <vector> #include "base/basictypes.h" +#include "base/logging.h" #include "base/scoped_ptr.h" class CommandLine { public: - // Creates a parsed version of the command line used to launch - // the current process. - CommandLine(); - #if defined(OS_WIN) // Creates a parsed version of the given command-line string. - // The program name is assumed to be the first item in the string. - CommandLine(const std::wstring& command_line); + // The program name is assumed to be the first item in the string. + void ParseFromString(const std::wstring& command_line); #elif defined(OS_POSIX) + // Initialize from an argv vector (or directly from main()'s argv). CommandLine(int argc, const char* const* argv); - CommandLine(const std::vector<std::string>& argv); + explicit CommandLine(const std::vector<std::string>& argv); #endif - ~CommandLine(); + // Construct a new, empty command line. + // |program| is the name of the program to run (aka argv[0]). + // TODO(port): should be a FilePath. + explicit CommandLine(const std::wstring& program); + + // Initialize the current process CommandLine singleton. On Windows, + // ignores its arguments (we instead parse GetCommandLineW() + // directly) because we don't trust the CRT's parsing of the command + // line, but it still must be called to set up the command line. + static void Init(int argc, const char* const* argv); - // On non-Windows platforms, main() must call SetArgcArgv() before accessing - // any members of this class. - // On Windows, this call is a no-op (we instead parse GetCommandLineW() - // directly) because we don't trust the CRT's parsing of the command line. - static void SetArgcArgv(int argc, const char* const* argv); + // Get the singleton CommandLine representing the current process's + // command line. + static const CommandLine* ForCurrentProcess() { + DCHECK(current_process_commandline_); + return current_process_commandline_; + } // Returns true if this command line contains the given switch. // (Switch names are case-insensitive.) @@ -52,40 +66,25 @@ class CommandLine { // the empty string. std::wstring GetSwitchValue(const std::wstring& switch_string) const; - // Returns the number of "loose values" found in the command line. - // Loose values are arguments that aren't switches. - // (The program name is also excluded from the set of loose values.) - size_t GetLooseValueCount() const; - - typedef std::vector<std::wstring>::const_iterator LooseValueIterator; - - // Returns a const_iterator to the list of loose values. - LooseValueIterator GetLooseValuesBegin() const; - - // Returns the end const_iterator for the list of loose values. - LooseValueIterator GetLooseValuesEnd() const; + // Get the remaining arguments to the command. + // WARNING: this is incorrect on POSIX; we must do string conversions. + std::vector<std::wstring> GetLooseValues() const; - // Simply returns the original command line string. - std::wstring command_line_string() const; - -#if defined(OS_POSIX) +#if defined(OS_WIN) + // Returns the original command line string. + const std::wstring& command_line_string() const { + return command_line_string_; + } +#elif defined(OS_POSIX) // Returns the original command line string as a vector of strings. - const std::vector<std::string>& argv() const; + const std::vector<std::string>& argv() const { + return argv_; + } #endif // Returns the program part of the command line string (the first item). std::wstring program() const; - // An array containing the prefixes that identify an argument as - // a switch. - static const wchar_t* const kSwitchPrefixes[]; - - // The string that's used to separate switches from their values. - static const wchar_t kSwitchValueSeparator[]; - - // Treat everything after this argument as loose parameters. - static const wchar_t kSwitchTerminator[]; - // Return a copy of the string prefixed with a switch prefix. // Used internally. static std::wstring PrefixedSwitchString(const std::wstring& switch_string); @@ -98,27 +97,69 @@ class CommandLine { // Appends the given switch string (preceded by a space and a switch // prefix) to the given string. - static void AppendSwitch(std::wstring* command_line_string, - const std::wstring& switch_string); + void AppendSwitch(const std::wstring& switch_string); // Appends the given switch string (preceded by a space and a switch // prefix) to the given string, with the given value attached. - static void AppendSwitchWithValue(std::wstring* command_line_string, - const std::wstring& switch_string, - const std::wstring& value_string); + void AppendSwitchWithValue(const std::wstring& switch_string, + const std::wstring& value_string); + + // Append a loose value to the command line. + void AppendLooseValue(const std::wstring& value); + + // Append the arguments from another command line to this one. + // If |include_program| is true, include |other|'s program as well. + void AppendArguments(const CommandLine& other, + bool include_program); private: - class Data; + CommandLine() {} + + // The singleton CommandLine instance representing the current process's + // command line. + static CommandLine* current_process_commandline_; + + // We store a platform-native version of the command line, used when building + // up a new command line to be executed. This ifdef delimits that code. + +#if defined(OS_WIN) + // The quoted, space-separated command-line string. + std::wstring command_line_string_; + + // The name of the program. + std::wstring program_; + + // The type of native command line arguments. + typedef std::wstring StringType; + +#elif defined(OS_POSIX) + // The argv array, with the program name in argv_[0]. + std::vector<std::string> argv_; + + // The type of native command line arguments. + typedef std::string StringType; + + // Shared by the two POSIX constructor forms. Initalize from argv_. + void InitFromArgv(); +#endif + + // Returns true and fills in |switch_string| and |switch_value| + // if |parameter_string| represents a switch. + static bool IsSwitch(const StringType& parameter_string, + std::string* switch_string, + StringType* switch_value); + + // Parsed-out values. + std::map<std::string, StringType> switches_; - // True if we are responsible for deleting our |data_| pointer. In some cases - // we cache the result of parsing the command line and |data_|'s lifetime is - // managed by someone else (e.g., the |Singleton| class). - bool we_own_data_; + // Non-switch command-line arguments. + std::vector<StringType> loose_values_; - // A pointer to the parsed version of the command line. - Data* data_; - - DISALLOW_EVIL_CONSTRUCTORS(CommandLine); + // We allow copy constructors, because a common pattern is to grab a + // copy of the current process's command line and then add some + // flags to it. E.g.: + // CommandLine cl(*CommandLine::ForCurrentProcess()); + // cl.AppendSwitch(...); }; #endif // BASE_COMMAND_LINE_H_ diff --git a/base/command_line_unittest.cc b/base/command_line_unittest.cc index 504c852..563b060 100644 --- a/base/command_line_unittest.cc +++ b/base/command_line_unittest.cc @@ -11,22 +11,19 @@ #include "base/string_util.h" #include "testing/gtest/include/gtest/gtest.h" -namespace { - class CommandLineTest : public testing::Test { - }; -}; - TEST(CommandLineTest, CommandLineConstructor) { -#ifdef OS_WIN - CommandLine cl(L"program --foo= -bAr /Spaetzel=pierogi /Baz flim " - L"--other-switches=\"--dog=canine --cat=feline\" " - L"-spaetzle=Crepe -=loosevalue flan " - L"--input-translation=\"45\"--output-rotation " - L"-- -- --not-a-switch " - L"\"in the time of submarines...\""); +#if defined(OS_WIN) + CommandLine cl(L""); + cl.ParseFromString(L"program --foo= -bAr /Spaetzel=pierogi /Baz flim " + L"--other-switches=\"--dog=canine --cat=feline\" " + L"-spaetzle=Crepe -=loosevalue flan " + L"--input-translation=\"45\"--output-rotation " + L"-- -- --not-a-switch " + L"\"in the time of submarines...\""); + EXPECT_FALSE(cl.command_line_string().empty()); #elif defined(OS_POSIX) - const char* argv[] = {"program", "--foo=", "-bAr", - "-Spaetzel=pierogi", "-Baz", "flim", + const char* argv[] = {"program", "--foo=", "-bar", + "-spaetzel=pierogi", "-baz", "flim", "--other-switches=--dog=canine --cat=feline", "-spaetzle=Crepe", "-=loosevalue", "flan", "--input-translation=45--output-rotation", @@ -34,7 +31,6 @@ TEST(CommandLineTest, CommandLineConstructor) { "in the time of submarines..."}; CommandLine cl(arraysize(argv), argv); #endif - EXPECT_FALSE(cl.command_line_string().empty()); EXPECT_FALSE(cl.HasSwitch(L"cruller")); EXPECT_FALSE(cl.HasSwitch(L"flim")); EXPECT_FALSE(cl.HasSwitch(L"program")); @@ -50,7 +46,9 @@ TEST(CommandLineTest, CommandLineConstructor) { EXPECT_TRUE(cl.HasSwitch(L"bar")); EXPECT_TRUE(cl.HasSwitch(L"baz")); EXPECT_TRUE(cl.HasSwitch(L"spaetzle")); +#if defined(OS_WIN) EXPECT_TRUE(cl.HasSwitch(L"SPAETZLE")); +#endif EXPECT_TRUE(cl.HasSwitch(L"other-switches")); EXPECT_TRUE(cl.HasSwitch(L"input-translation")); @@ -61,9 +59,10 @@ TEST(CommandLineTest, CommandLineConstructor) { EXPECT_EQ(L"--dog=canine --cat=feline", cl.GetSwitchValue(L"other-switches")); EXPECT_EQ(L"45--output-rotation", cl.GetSwitchValue(L"input-translation")); - EXPECT_EQ(5U, cl.GetLooseValueCount()); + std::vector<std::wstring> loose_values = cl.GetLooseValues(); + ASSERT_EQ(5U, loose_values.size()); - CommandLine::LooseValueIterator iter = cl.GetLooseValuesBegin(); + std::vector<std::wstring>::const_iterator iter = loose_values.begin(); EXPECT_EQ(L"flim", *iter); ++iter; EXPECT_EQ(L"flan", *iter); @@ -74,9 +73,9 @@ TEST(CommandLineTest, CommandLineConstructor) { ++iter; EXPECT_EQ(L"in the time of submarines...", *iter); ++iter; - EXPECT_TRUE(iter == cl.GetLooseValuesEnd()); + EXPECT_TRUE(iter == loose_values.end()); #if defined(OS_POSIX) - std::vector<std::string> argvec = cl.argv(); + const std::vector<std::string>& argvec = cl.argv(); for (size_t i = 0; i < argvec.size(); i++) { EXPECT_EQ(0, argvec[i].compare(argv[i])); @@ -84,27 +83,20 @@ TEST(CommandLineTest, CommandLineConstructor) { #endif } -// These test the command line used to invoke the unit test. -TEST(CommandLineTest, DefaultConstructor) { - CommandLine cl; - EXPECT_FALSE(cl.command_line_string().empty()); - EXPECT_FALSE(cl.program().empty()); -} - // Tests behavior with an empty input string. TEST(CommandLineTest, EmptyString) { #if defined(OS_WIN) CommandLine cl(L""); + EXPECT_TRUE(cl.command_line_string().empty()); + EXPECT_TRUE(cl.program().empty()); #elif defined(OS_POSIX) CommandLine cl(0, NULL); EXPECT_TRUE(cl.argv().size() == 0); #endif - EXPECT_TRUE(cl.command_line_string().empty()); - EXPECT_TRUE(cl.program().empty()); - EXPECT_EQ(0U, cl.GetLooseValueCount()); + EXPECT_EQ(0U, cl.GetLooseValues().size()); } -// Test static functions for appending switches to a command line. +// Test methods for appending switches to a command line. TEST(CommandLineTest, AppendSwitches) { std::wstring switch1 = L"switch1"; std::wstring switch2 = L"switch2"; @@ -115,31 +107,24 @@ TEST(CommandLineTest, AppendSwitches) { std::wstring value4 = L"\"a value with quotes\""; #if defined(OS_WIN) - std::wstring cl_string = L"Program"; - CommandLine::AppendSwitch(&cl_string, switch1); - CommandLine::AppendSwitchWithValue(&cl_string, switch2, value); - CommandLine::AppendSwitchWithValue(&cl_string, switch3, value3); - CommandLine::AppendSwitchWithValue(&cl_string, switch4, value4); - CommandLine cl(cl_string); + CommandLine cl(L"Program"); #elif defined(OS_POSIX) std::vector<std::string> argv; argv.push_back(std::string("Program")); - argv.push_back(WideToUTF8(CommandLine::PrefixedSwitchString(switch1))); - argv.push_back(WideToUTF8(CommandLine::PrefixedSwitchStringWithValue( - switch2, value))); - argv.push_back(WideToUTF8(CommandLine::PrefixedSwitchStringWithValue( - switch3, value3))); - argv.push_back(WideToUTF8(CommandLine::PrefixedSwitchStringWithValue( - switch4, value4.substr(1, value4.length() - 2)))); CommandLine cl(argv); #endif + cl.AppendSwitch(switch1); + cl.AppendSwitchWithValue(switch2, value); + cl.AppendSwitchWithValue(switch3, value3); + cl.AppendSwitchWithValue(switch4, value4); + EXPECT_TRUE(cl.HasSwitch(switch1)); EXPECT_TRUE(cl.HasSwitch(switch2)); EXPECT_EQ(value, cl.GetSwitchValue(switch2)); EXPECT_TRUE(cl.HasSwitch(switch3)); EXPECT_EQ(value3, cl.GetSwitchValue(switch3)); EXPECT_TRUE(cl.HasSwitch(switch4)); - EXPECT_EQ(value4.substr(1, value4.length() - 2), cl.GetSwitchValue(switch4)); + EXPECT_EQ(value4, cl.GetSwitchValue(switch4)); } diff --git a/base/logging.cc b/base/logging.cc index 7ddbe15..cc9c7db 100644 --- a/base/logging.cc +++ b/base/logging.cc @@ -228,7 +228,8 @@ void InitLogMutex() { void InitLogging(const PathChar* new_log_file, LoggingDestination logging_dest, LogLockingState lock_log, OldFileDeletionState delete_old) { - g_enable_dcheck = CommandLine().HasSwitch(switches::kEnableDCHECK); + g_enable_dcheck = + CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableDCHECK); if (log_file) { // calling InitLogging twice or after some log call has already opened the diff --git a/base/multiprocess_test.h b/base/multiprocess_test.h index 4f3200e..99c2c79 100644 --- a/base/multiprocess_test.h +++ b/base/multiprocess_test.h @@ -81,7 +81,6 @@ class MultiProcessTest : public PlatformTest { bool debug_on_start) { return SpawnChildImpl(procname, fds_to_map, debug_on_start); } - #endif private: @@ -89,37 +88,31 @@ class MultiProcessTest : public PlatformTest { base::ProcessHandle SpawnChildImpl( const std::wstring& procname, bool debug_on_start) { - CommandLine cl; + CommandLine cl(*CommandLine::ForCurrentProcess()); base::ProcessHandle handle = static_cast<base::ProcessHandle>(NULL); - std::wstring clstr = cl.command_line_string(); - CommandLine::AppendSwitchWithValue(&clstr, kRunClientProcess, procname); + cl.AppendSwitchWithValue(kRunClientProcess, procname); - if (debug_on_start) { - CommandLine::AppendSwitch(&clstr, switches::kDebugOnStart); - } + if (debug_on_start) + cl.AppendSwitch(switches::kDebugOnStart); - base::LaunchApp(clstr, false, true, &handle); + base::LaunchApp(cl, false, true, &handle); return handle; } #elif defined(OS_POSIX) + // TODO(port): with the CommandLine refactoring, this code is very similar + // to the Windows code. Investigate whether this can be made shorter. base::ProcessHandle SpawnChildImpl( const std::wstring& procname, const base::file_handle_mapping_vector& fds_to_map, bool debug_on_start) { - CommandLine cl; + CommandLine cl(*CommandLine::ForCurrentProcess()); base::ProcessHandle handle = static_cast<base::ProcessHandle>(NULL); + cl.AppendSwitchWithValue(kRunClientProcess, procname); - std::vector<std::string> clvec(cl.argv()); - std::wstring wswitchstr = - CommandLine::PrefixedSwitchStringWithValue(kRunClientProcess, - procname); - if (debug_on_start) { - CommandLine::AppendSwitch(&wswitchstr, switches::kDebugOnStart); - } + if (debug_on_start) + cl.AppendSwitch(switches::kDebugOnStart); - std::string switchstr = WideToUTF8(wswitchstr); - clvec.push_back(switchstr.c_str()); - base::LaunchApp(clvec, fds_to_map, false, &handle); + base::LaunchApp(cl.argv(), fds_to_map, false, &handle); return handle; } #endif diff --git a/base/perf_test_suite.h b/base/perf_test_suite.h index 444a099..ea6846a 100644 --- a/base/perf_test_suite.h +++ b/base/perf_test_suite.h @@ -23,7 +23,8 @@ class PerfTestSuite : public TestSuite { // Initialize the perf timer log FilePath log_path; - std::wstring log_file = CommandLine().GetSwitchValue(L"log-file"); + std::wstring log_file = + CommandLine::ForCurrentProcess()->GetSwitchValue(L"log-file"); if (log_file.empty()) { FilePath exe; PathService::Get(base::FILE_EXE, &exe); diff --git a/base/process_util.h b/base/process_util.h index 7eabdbe..ae38c5a 100644 --- a/base/process_util.h +++ b/base/process_util.h @@ -91,8 +91,6 @@ bool LaunchApp(const std::wstring& cmdline, bool wait, bool start_hidden, ProcessHandle* process_handle); #elif defined(OS_POSIX) // Runs the application specified in argv[0] with the command line argv. -// Both the elements of argv and argv itself must be terminated with a null -// byte. // Before launching all FDs open in the parent process will be marked as // close-on-exec. |fds_to_remap| defines a mapping of src fd->dest fd to // propagate FDs into the child process. diff --git a/base/process_util_linux.cc b/base/process_util_linux.cc index aa8ba94..d23f78c 100644 --- a/base/process_util_linux.cc +++ b/base/process_util_linux.cc @@ -76,7 +76,7 @@ bool LaunchApp(const std::vector<std::string>& argv, if (wait) waitpid(pid, 0, 0); - if(process_handle) + if (process_handle) *process_handle = pid; } @@ -85,9 +85,9 @@ bool LaunchApp(const std::vector<std::string>& argv, return retval; } - bool LaunchApp(const CommandLine& cl, - bool wait, bool start_hidden, ProcessHandle* process_handle) { + bool wait, bool start_hidden, + ProcessHandle* process_handle) { file_handle_mapping_vector no_files; return LaunchApp(cl.argv(), no_files, wait, process_handle); } @@ -101,7 +101,8 @@ bool DidProcessCrash(ProcessHandle handle) { if (WIFSIGNALED(status)) { int signum = WTERMSIG(status); - return (signum == SIGSEGV || signum == SIGILL || signum == SIGABRT || signum == SIGFPE); + return (signum == SIGSEGV || signum == SIGILL || signum == SIGABRT || + signum == SIGFPE); } if (WIFEXITED(status)) { diff --git a/base/test_suite.h b/base/test_suite.h index 01b39fa..2aacecd 100644 --- a/base/test_suite.h +++ b/base/test_suite.h @@ -31,7 +31,7 @@ class TestSuite { public: TestSuite(int argc, char** argv) { base::EnableTerminationOnHeapCorruption(); - CommandLine::SetArgcArgv(argc, argv); + CommandLine::Init(argc, argv); testing::InitGoogleTest(&argc, argv); #if defined(OS_LINUX) gtk_init_check(&argc, &argv); @@ -48,7 +48,8 @@ class TestSuite { base::ScopedNSAutoreleasePool scoped_pool; Initialize(); - std::wstring client_func = CommandLine().GetSwitchValue(kRunClientProcess); + std::wstring client_func = + CommandLine::ForCurrentProcess()->GetSwitchValue(kRunClientProcess); // Check to see if we are being run as a client process. if (!client_func.empty()) { // Convert our function name to a usable string for GetProcAddress. @@ -101,7 +102,7 @@ class TestSuite { #if defined(OS_WIN) // In some cases, we do not want to see standard error dialogs. if (!IsDebuggerPresent() && - !CommandLine().HasSwitch(L"show-error-dialogs")) { + !CommandLine::ForCurrentProcess()->HasSwitch(L"show-error-dialogs")) { SuppressErrorDialogs(); logging::SetLogAssertHandler(UnitTestAssertHandler); } |