art: Refactor RuntimeOptions/ParsedOptions
Refactor the RuntimeOptions to be a
type-safe map (VariantMap, see runtime_options.h) and the ParsedOptions
to delegate the parsing to CmdlineParser (see cmdline/cmdline_parser.h).
This is the start of a command line parsing refactor, and may include
more in the future (dex2oat, patchoat, etc).
For more details of the command line parsing generator usage see cmdline/README.md
Change-Id: Ic67c6bca5e1f33bf2ec60e2e3ff8c366bab91563
diff --git a/runtime/Android.mk b/runtime/Android.mk
index 30cf580..907d884 100644
--- a/runtime/Android.mk
+++ b/runtime/Android.mk
@@ -139,6 +139,7 @@
reference_table.cc \
reflection.cc \
runtime.cc \
+ runtime_options.cc \
signal_catcher.cc \
stack.cc \
thread.cc \
@@ -457,7 +458,9 @@
endif
LOCAL_C_INCLUDES += $$(ART_C_INCLUDES)
+ LOCAL_C_INCLUDES += art/cmdline
LOCAL_C_INCLUDES += art/sigchainlib
+ LOCAL_C_INCLUDES += art
LOCAL_SHARED_LIBRARIES := libnativehelper libnativebridge libsigchain
LOCAL_SHARED_LIBRARIES += libbacktrace
diff --git a/runtime/base/variant_map.h b/runtime/base/variant_map.h
new file mode 100644
index 0000000..cf7977e
--- /dev/null
+++ b/runtime/base/variant_map.h
@@ -0,0 +1,453 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ART_RUNTIME_BASE_VARIANT_MAP_H_
+#define ART_RUNTIME_BASE_VARIANT_MAP_H_
+
+#include <memory.h>
+#include <map>
+#include <utility>
+
+namespace art {
+
+//
+// A variant map is a heterogenous, type safe key->value map. It allows
+// for multiple different value types to be stored dynamically in the same map.
+//
+// It provides the following interface in a nutshell:
+//
+// struct VariantMap {
+// template <typename TValue>
+// TValue* Get(Key<T> key); // nullptr if the value was never set, otherwise the value.
+//
+// template <typename TValue>
+// void Set(Key<T> key, TValue value);
+// };
+//
+// Since the key is strongly typed at compile-time, it is impossible to accidentally
+// read/write a value with a different type than the key at either compile-time or run-time.
+//
+// Do not use VariantMap/VariantMapKey directly. Instead subclass each of them and use
+// the subclass, for example:
+//
+// template <typename TValue>
+// struct FruitMapKey : VariantMapKey<TValue> {
+// FruitMapKey() {}
+// };
+//
+// struct FruitMap : VariantMap<FruitMap, FruitMapKey> {
+// // This 'using' line is necessary to inherit the variadic constructor.
+// using VariantMap<FruitMap, FruitMapKey>::VariantMap;
+//
+// // Make the next '4' usages of Key slightly shorter to type.
+// template <typename TValue>
+// using Key = FruitMapKey<TValue>;
+//
+// static const Key<int> Apple;
+// static const Key<double> Orange;
+// static const Key<std::string> Banana;
+// };
+//
+// const FruitMap::Key<int> FruitMap::Apple;
+// const FruitMap::Key<double> FruitMap::Orange;
+// const FruitMap::Key<std::string> Banana;
+//
+// See variant_map_test.cc for more examples.
+//
+
+// Implementation details for VariantMap.
+namespace detail {
+ // Allocate a unique counter value each time it's called.
+ struct VariantMapKeyCounterAllocator {
+ static size_t AllocateCounter() {
+ static size_t counter = 0;
+ counter++;
+
+ return counter;
+ }
+ };
+
+ // Type-erased version of VariantMapKey<T>
+ struct VariantMapKeyRaw {
+ // TODO: this may need to call a virtual function to support string comparisons
+ bool operator<(const VariantMapKeyRaw& other) const {
+ return key_counter_ < other.key_counter_;
+ }
+
+ // The following functions need to be virtual since we don't know the compile-time type anymore:
+
+ // Clone the key, creating a copy of the contents.
+ virtual VariantMapKeyRaw* Clone() const = 0;
+
+ // Delete a value whose runtime type is that of the non-erased key's TValue.
+ virtual void ValueDelete(void* value) const = 0;
+
+ // Clone a value whose runtime type is that of the non-erased key's TValue.
+ virtual void* ValueClone(void* value) const = 0;
+
+ // Compare one key to another (same as operator<).
+ virtual bool Compare(const VariantMapKeyRaw* other) const {
+ if (other == nullptr) {
+ return false;
+ }
+ return key_counter_ < other->key_counter_;
+ }
+
+ virtual ~VariantMapKeyRaw() {}
+
+ protected:
+ VariantMapKeyRaw()
+ : key_counter_(VariantMapKeyCounterAllocator::AllocateCounter()) {}
+ // explicit VariantMapKeyRaw(size_t counter)
+ // : key_counter_(counter) {}
+
+ size_t GetCounter() const {
+ return key_counter_;
+ }
+
+ protected:
+ // Avoid the object slicing problem; use Clone() instead.
+ VariantMapKeyRaw(const VariantMapKeyRaw& other) = default;
+ VariantMapKeyRaw(VariantMapKeyRaw&& other) = default;
+
+ private:
+ size_t key_counter_; // Runtime type ID. Unique each time a new type is reified.
+ };
+} // namespace detail
+
+// The base type for keys used by the VariantMap. Users must subclass this type.
+template <typename TValue>
+struct VariantMapKey : detail::VariantMapKeyRaw {
+ // Instantiate a default value for this key. If an explicit default value was provided
+ // then that is used. Otherwise, the default value for the type TValue{} is returned.
+ TValue CreateDefaultValue() const {
+ if (default_value_ == nullptr) {
+ return TValue{}; // NOLINT [readability/braces] [4]
+ } else {
+ return TValue(*default_value_);
+ }
+ }
+
+ protected:
+ // explicit VariantMapKey(size_t counter) : detail::VariantMapKeyRaw(counter) {}
+ explicit VariantMapKey(const TValue& default_value)
+ : default_value_(std::make_shared<TValue>(default_value)) {}
+ explicit VariantMapKey(TValue&& default_value)
+ : default_value_(std::make_shared<TValue>(default_value)) {}
+ VariantMapKey() {}
+ virtual ~VariantMapKey() {}
+
+ private:
+ virtual VariantMapKeyRaw* Clone() const {
+ return new VariantMapKey<TValue>(*this);
+ }
+
+ virtual void* ValueClone(void* value) const {
+ if (value == nullptr) {
+ return nullptr;
+ }
+
+ TValue* strong_value = reinterpret_cast<TValue*>(value);
+ return new TValue(*strong_value);
+ }
+
+ virtual void ValueDelete(void* value) const {
+ if (value == nullptr) {
+ return;
+ }
+
+ // Smartly invoke the proper delete/delete[]/etc
+ const std::default_delete<TValue> deleter = std::default_delete<TValue>();
+ deleter(reinterpret_cast<TValue*>(value));
+ }
+
+ VariantMapKey(const VariantMapKey& other) = default;
+ VariantMapKey(VariantMapKey&& other) = default;
+
+ template <typename Base, template <typename TV> class TKey> friend struct VariantMap;
+
+ // Store a prototype of the key's default value, for usage with VariantMap::GetOrDefault
+ std::shared_ptr<TValue> default_value_;
+};
+
+// Implementation details for a stringified VariantMapStringKey.
+namespace detail {
+ struct VariantMapStringKeyRegistry {
+ // TODO
+ };
+} // namespace detail
+
+// Alternative base type for all keys used by VariantMap, supports runtime strings as the name.
+template <typename TValue>
+struct VariantMapStringKey : VariantMapKey<TValue> {
+ explicit VariantMapStringKey(const char* name)
+ : // VariantMapKey(/*std::hash<std::string>()(name)*/),
+ name_(name) {
+ }
+
+ private:
+ const char* name_;
+};
+
+// A variant map allows type-safe heteregeneous key->value mappings.
+// All possible key types must be specified at compile-time. Values may be added/removed
+// at runtime.
+template <typename Base, template <typename TV> class TKey>
+struct VariantMap {
+ // Allow users of this static interface to use the key type.
+ template <typename TValue>
+ using Key = TKey<TValue>;
+
+ // Look up the value from the key. The pointer becomes invalid if this key is overwritten/removed.
+ // A null value is returned only when the key does not exist in this map.
+ template <typename TValue>
+ const TValue* Get(const TKey<TValue>& key) const {
+ return GetValuePtr(key);
+ }
+
+ // Look up the value from the key. The pointer becomes invalid if this key is overwritten/removed.
+ // A null value is returned only when the key does not exist in this map.
+ template <typename TValue>
+ TValue* Get(const TKey<TValue>& key) {
+ return GetValuePtr(key);
+ }
+
+ // Lookup the value from the key. If it was not set in the map, return the default value.
+ // The default value is either the key's default, or TValue{} if the key doesn't have a default.
+ template <typename TValue>
+ TValue GetOrDefault(const TKey<TValue>& key) const {
+ auto* ptr = Get(key);
+ return (ptr == nullptr) ? key.CreateDefaultValue() : *ptr;
+ }
+
+ private:
+ // TODO: move to detail, or make it more generic like a ScopeGuard(function)
+ template <typename TValue>
+ struct ScopedRemove {
+ ScopedRemove(VariantMap& map, const TKey<TValue>& key) : map_(map), key_(key) {}
+ ~ScopedRemove() {
+ map_.Remove(key_);
+ }
+
+ VariantMap& map_;
+ const TKey<TValue>& key_;
+ };
+
+ public:
+ // Release the value from the key. If it was not set in the map, returns the default value.
+ // If the key was set, it is removed as a side effect.
+ template <typename TValue>
+ TValue ReleaseOrDefault(const TKey<TValue>& key) {
+ ScopedRemove<TValue> remove_on_return(*this, key);
+
+ TValue* ptr = Get(key);
+ if (ptr != nullptr) {
+ return std::move(*ptr);
+ } else {
+ TValue default_value = key.CreateDefaultValue();
+ return std::move(default_value);
+ }
+ }
+
+ // See if a value is stored for this key.
+ template <typename TValue>
+ bool Exists(const TKey<TValue>& key) const {
+ return GetKeyValueIterator(key) != storage_map_.end();
+ }
+
+ // Set a value for a given key, overwriting the previous value if any.
+ template <typename TValue>
+ void Set(const TKey<TValue>& key, const TValue& value) {
+ Remove(key);
+ storage_map_.insert({{key.Clone(), new TValue(value)}});
+ }
+
+ // Set a value for a given key, only if there was no previous value before.
+ // Returns true if the value was set, false if a previous value existed.
+ template <typename TValue>
+ bool SetIfMissing(const TKey<TValue>& key, const TValue& value) {
+ TValue* ptr = Get(key);
+ if (ptr == nullptr) {
+ Set(key, value);
+ return true;
+ }
+ return false;
+ }
+
+ // Remove the value for a given key, or a no-op if there was no previously set value.
+ template <typename TValue>
+ void Remove(const TKey<TValue>& key) {
+ StaticAssertKeyType<TValue>();
+
+ auto&& it = GetKeyValueIterator(key);
+ if (it != storage_map_.end()) {
+ key.ValueDelete(it->second);
+ delete it->first;
+ storage_map_.erase(it);
+ }
+ }
+
+ // Remove all key/value pairs.
+ void Clear() {
+ DeleteStoredValues();
+ storage_map_.clear();
+ }
+
+ // How many key/value pairs are stored in this map.
+ size_t Size() const {
+ return storage_map_.size();
+ }
+
+ // Construct an empty map.
+ explicit VariantMap() {}
+
+ template <typename ... TKeyValue>
+ explicit VariantMap(const TKeyValue& ... key_value_list) {
+ static_assert(sizeof...(TKeyValue) % 2 == 0, "Must be an even number of key/value elements");
+ InitializeParameters(key_value_list...);
+ }
+
+ // Create a new map from an existing map, copying all the key/value pairs.
+ VariantMap(const VariantMap& other) {
+ operator=(other);
+ }
+
+ // Copy the key/value pairs from the other map into this one. Existing key/values are cleared.
+ VariantMap& operator=(const VariantMap& other) {
+ if (this == &other) {
+ return *this;
+ }
+
+ Clear();
+
+ for (auto&& kv_pair : other.storage_map_) {
+ const detail::VariantMapKeyRaw* raw_key_other = kv_pair.first;
+ void* value = kv_pair.second;
+
+ detail::VariantMapKeyRaw* cloned_raw_key = raw_key_other->Clone();
+ void* cloned_value = raw_key_other->ValueClone(value);
+
+ storage_map_.insert({{ cloned_raw_key, cloned_value }});
+ }
+
+ return *this;
+ }
+
+ // Create a new map by moving an existing map into this one. The other map becomes empty.
+ VariantMap(VariantMap&& other) {
+ operator=(std::forward<VariantMap>(other));
+ }
+
+ // Move the existing map's key/value pairs into this one. The other map becomes empty.
+ VariantMap& operator=(VariantMap&& other) {
+ if (this != &other) {
+ Clear();
+ storage_map_.swap(other.storage_map_);
+ other.storage_map_.clear();
+ }
+ return *this;
+ }
+
+ ~VariantMap() {
+ DeleteStoredValues();
+ }
+
+ private:
+ void InitializeParameters() {}
+
+ template <typename TK, typename TValue, typename ... Rest>
+ void InitializeParameters(const TK& key, const TValue& value, const Rest& ... rest) {
+ static_assert(
+ std::is_same<TK, TKey<TValue>>::value, "The 0th/2nd/4th/etc parameters must be a key");
+
+ const TKey<TValue>& key_refined = key;
+
+ Set(key_refined, value);
+ InitializeParameters(rest...);
+ }
+
+ // Custom key comparator for std::map, needed since we are storing raw pointers as the keys.
+ struct KeyComparator {
+ bool operator()(const detail::VariantMapKeyRaw* lhs,
+ const detail::VariantMapKeyRaw* rhs) const {
+ if (lhs == nullptr) {
+ return lhs != rhs;
+ }
+
+ return lhs->Compare(rhs);
+ }
+ };
+
+ // Map of key pointers to value pointers. Pointers are never null.
+ using StorageMap = std::map<const detail::VariantMapKeyRaw*, void*, KeyComparator>;
+
+ template <typename TValue>
+ typename StorageMap::iterator GetKeyValueIterator(const TKey<TValue>& key) {
+ StaticAssertKeyType<TValue>();
+
+ const TKey<TValue>* key_ptr = &key;
+ const detail::VariantMapKeyRaw* raw_ptr = key_ptr;
+ return storage_map_.find(raw_ptr);
+ }
+
+ template <typename TValue>
+ typename StorageMap::const_iterator GetKeyValueIterator(const TKey<TValue>& key) const {
+ StaticAssertKeyType<TValue>();
+
+ const TKey<TValue>* key_ptr = &key;
+ const detail::VariantMapKeyRaw* raw_ptr = key_ptr;
+ return storage_map_.find(raw_ptr);
+ }
+
+ template <typename TValue>
+ TValue* GetValuePtr(const TKey<TValue>& key) {
+ return const_cast<TValue*>(GetValueConstPtr(key));
+ }
+
+ template <typename TValue>
+ const TValue* GetValuePtr(const TKey<TValue>& key) const {
+ return GetValueConstPtr(key);
+ }
+
+ template <typename TValue>
+ const TValue* GetValueConstPtr(const TKey<TValue>& key) const {
+ auto&& it = GetKeyValueIterator(key);
+ if (it == storage_map_.end()) {
+ return nullptr;
+ }
+
+ return reinterpret_cast<const TValue*>(it->second);
+ }
+
+ template <typename TValue>
+ static void StaticAssertKeyType() {
+ static_assert(std::is_base_of<VariantMapKey<TValue>, TKey<TValue>>::value,
+ "The provided key type (TKey) must be a subclass of VariantMapKey");
+ }
+
+ void DeleteStoredValues() {
+ for (auto&& kv_pair : storage_map_) {
+ kv_pair.first->ValueDelete(kv_pair.second);
+ delete kv_pair.first;
+ }
+ }
+
+ StorageMap storage_map_;
+};
+
+} // namespace art
+
+#endif // ART_RUNTIME_BASE_VARIANT_MAP_H_
diff --git a/runtime/base/variant_map_test.cc b/runtime/base/variant_map_test.cc
new file mode 100644
index 0000000..827de46
--- /dev/null
+++ b/runtime/base/variant_map_test.cc
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "variant_map.h"
+#include "gtest/gtest.h"
+
+#define EXPECT_NULL(expected) EXPECT_EQ(reinterpret_cast<const void*>(expected), \
+ reinterpret_cast<void*>(NULL));
+
+namespace art {
+
+namespace {
+ template <typename TValue>
+ struct FruitMapKey : VariantMapKey<TValue> {
+ FruitMapKey() {}
+ };
+
+ struct FruitMap : VariantMap<FruitMap, FruitMapKey> {
+ // This 'using' line is necessary to inherit the variadic constructor.
+ using VariantMap<FruitMap, FruitMapKey>::VariantMap;
+
+ // Make the next '4' usages of Key slightly shorter to type.
+ template <typename TValue>
+ using Key = FruitMapKey<TValue>;
+
+ static const Key<int> Apple;
+ static const Key<double> Orange;
+ };
+
+ const FruitMap::Key<int> FruitMap::Apple;
+ const FruitMap::Key<double> FruitMap::Orange;
+} // namespace
+
+TEST(VariantMaps, BasicReadWrite) {
+ FruitMap fm;
+
+ EXPECT_NULL(fm.Get(FruitMap::Apple));
+ EXPECT_FALSE(fm.Exists(FruitMap::Apple));
+ EXPECT_NULL(fm.Get(FruitMap::Orange));
+ EXPECT_FALSE(fm.Exists(FruitMap::Orange));
+
+ fm.Set(FruitMap::Apple, 1);
+ EXPECT_NULL(fm.Get(FruitMap::Orange));
+ EXPECT_EQ(1, *fm.Get(FruitMap::Apple));
+ EXPECT_TRUE(fm.Exists(FruitMap::Apple));
+
+ fm.Set(FruitMap::Apple, 5);
+ EXPECT_NULL(fm.Get(FruitMap::Orange));
+ EXPECT_EQ(5, *fm.Get(FruitMap::Apple));
+ EXPECT_TRUE(fm.Exists(FruitMap::Apple));
+
+ fm.Set(FruitMap::Orange, 555.0);
+ EXPECT_EQ(5, *fm.Get(FruitMap::Apple));
+ EXPECT_DOUBLE_EQ(555.0, *fm.Get(FruitMap::Orange));
+ EXPECT_EQ(size_t(2), fm.Size());
+
+ fm.Remove(FruitMap::Apple);
+ EXPECT_FALSE(fm.Exists(FruitMap::Apple));
+
+ fm.Clear();
+ EXPECT_EQ(size_t(0), fm.Size());
+ EXPECT_FALSE(fm.Exists(FruitMap::Orange));
+}
+
+TEST(VariantMaps, RuleOfFive) {
+ // Test empty constructor
+ FruitMap fmEmpty;
+ EXPECT_EQ(size_t(0), fmEmpty.Size());
+
+ // Test empty constructor
+ FruitMap fmFilled;
+ fmFilled.Set(FruitMap::Apple, 1);
+ fmFilled.Set(FruitMap::Orange, 555.0);
+ EXPECT_EQ(size_t(2), fmFilled.Size());
+
+ // Test copy constructor
+ FruitMap fmEmptyCopy(fmEmpty);
+ EXPECT_EQ(size_t(0), fmEmptyCopy.Size());
+
+ // Test copy constructor
+ FruitMap fmFilledCopy(fmFilled);
+ EXPECT_EQ(size_t(2), fmFilledCopy.Size());
+ EXPECT_EQ(*fmFilled.Get(FruitMap::Apple), *fmFilledCopy.Get(FruitMap::Apple));
+ EXPECT_DOUBLE_EQ(*fmFilled.Get(FruitMap::Orange), *fmFilledCopy.Get(FruitMap::Orange));
+
+ // Test operator=
+ FruitMap fmFilledCopy2;
+ fmFilledCopy2 = fmFilled;
+ EXPECT_EQ(size_t(2), fmFilledCopy2.Size());
+ EXPECT_EQ(*fmFilled.Get(FruitMap::Apple), *fmFilledCopy2.Get(FruitMap::Apple));
+ EXPECT_DOUBLE_EQ(*fmFilled.Get(FruitMap::Orange), *fmFilledCopy2.Get(FruitMap::Orange));
+
+ // Test move constructor
+ FruitMap fmMoved(std::move(fmFilledCopy));
+ EXPECT_EQ(size_t(0), fmFilledCopy.Size());
+ EXPECT_EQ(size_t(2), fmMoved.Size());
+ EXPECT_EQ(*fmFilled.Get(FruitMap::Apple), *fmMoved.Get(FruitMap::Apple));
+ EXPECT_DOUBLE_EQ(*fmFilled.Get(FruitMap::Orange), *fmMoved.Get(FruitMap::Orange));
+
+ // Test operator= move
+ FruitMap fmMoved2;
+ fmMoved2.Set(FruitMap::Apple, 12345); // This value will be clobbered after the move
+
+ fmMoved2 = std::move(fmFilledCopy2);
+ EXPECT_EQ(size_t(0), fmFilledCopy2.Size());
+ EXPECT_EQ(size_t(2), fmMoved2.Size());
+ EXPECT_EQ(*fmFilled.Get(FruitMap::Apple), *fmMoved2.Get(FruitMap::Apple));
+ EXPECT_DOUBLE_EQ(*fmFilled.Get(FruitMap::Orange), *fmMoved2.Get(FruitMap::Orange));
+}
+
+TEST(VariantMaps, VariadicConstructors) {
+ // Variadic constructor, 1 kv/pair
+ FruitMap fmApple(FruitMap::Apple, 12345);
+ EXPECT_EQ(size_t(1), fmApple.Size());
+ EXPECT_EQ(12345, *fmApple.Get(FruitMap::Apple));
+
+ // Variadic constructor, 2 kv/pair
+ FruitMap fmAppleAndOrange(FruitMap::Apple, 12345,
+ FruitMap::Orange, 100.0);
+ EXPECT_EQ(size_t(2), fmAppleAndOrange.Size());
+ EXPECT_EQ(12345, *fmAppleAndOrange.Get(FruitMap::Apple));
+ EXPECT_DOUBLE_EQ(100.0, *fmAppleAndOrange.Get(FruitMap::Orange));
+}
+
+TEST(VariantMaps, ReleaseOrDefault) {
+ FruitMap fmAppleAndOrange(FruitMap::Apple, 12345,
+ FruitMap::Orange, 100.0);
+
+ int apple = fmAppleAndOrange.ReleaseOrDefault(FruitMap::Apple);
+ EXPECT_EQ(12345, apple);
+
+ // Releasing will also remove the Apple key.
+ EXPECT_EQ(size_t(1), fmAppleAndOrange.Size());
+
+ // Releasing again yields a default value.
+ int apple2 = fmAppleAndOrange.ReleaseOrDefault(FruitMap::Apple);
+ EXPECT_EQ(0, apple2);
+}
+
+TEST(VariantMaps, GetOrDefault) {
+ FruitMap fm(FruitMap::Apple, 12345);
+
+ // Apple gives the expected value we set.
+ int apple = fm.GetOrDefault(FruitMap::Apple);
+ EXPECT_EQ(12345, apple);
+
+ // Map is still 1.
+ EXPECT_EQ(size_t(1), fm.Size());
+
+ // Orange gives back a default value, since it's not in the map.
+ double orange = fm.GetOrDefault(FruitMap::Orange);
+ EXPECT_DOUBLE_EQ(0.0, orange);
+}
+
+} // namespace art
diff --git a/runtime/common_runtime_test.cc b/runtime/common_runtime_test.cc
index d48ac9d..b7ffd60 100644
--- a/runtime/common_runtime_test.cc
+++ b/runtime/common_runtime_test.cc
@@ -224,6 +224,7 @@
options.push_back(std::make_pair(max_heap_string, nullptr));
options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
SetUpRuntimeOptions(&options);
+
if (!Runtime::Create(options, false)) {
LOG(FATAL) << "Failed to create runtime";
return;
diff --git a/runtime/common_runtime_test.h b/runtime/common_runtime_test.h
index 38a9733..9efea84 100644
--- a/runtime/common_runtime_test.h
+++ b/runtime/common_runtime_test.h
@@ -76,6 +76,9 @@
CommonRuntimeTest();
~CommonRuntimeTest();
+ // Gets the path of the libcore dex file.
+ static std::string GetLibCoreDexFileName();
+
protected:
static bool IsHost() {
return !kIsTargetBuild;
@@ -98,11 +101,8 @@
virtual void TearDown();
- // Gets the path of the libcore dex file.
- std::string GetLibCoreDexFileName();
-
// Gets the path of the specified dex file for host or target.
- std::string GetDexFileName(const std::string& jar_prefix);
+ static std::string GetDexFileName(const std::string& jar_prefix);
std::string GetTestAndroidRoot();
diff --git a/runtime/gc/collector_type.h b/runtime/gc/collector_type.h
index ef5d56e..9c62097 100644
--- a/runtime/gc/collector_type.h
+++ b/runtime/gc/collector_type.h
@@ -46,6 +46,19 @@
};
std::ostream& operator<<(std::ostream& os, const CollectorType& collector_type);
+static constexpr CollectorType kCollectorTypeDefault =
+#if ART_DEFAULT_GC_TYPE_IS_CMS
+ kCollectorTypeCMS
+#elif ART_DEFAULT_GC_TYPE_IS_SS
+ kCollectorTypeSS
+#elif ART_DEFAULT_GC_TYPE_IS_GSS
+ kCollectorTypeGSS
+#else
+ gc::kCollectorTypeCMS
+#error "ART default GC type must be set"
+#endif
+ ; // NOLINT [whitespace/semicolon] [5]
+
} // namespace gc
} // namespace art
diff --git a/runtime/gc/heap.cc b/runtime/gc/heap.cc
index 5a60c87..dc42510 100644
--- a/runtime/gc/heap.cc
+++ b/runtime/gc/heap.cc
@@ -364,11 +364,11 @@
CHECK(non_moving_space_ != nullptr);
CHECK(!non_moving_space_->CanMoveObjects());
// Allocate the large object space.
- if (large_object_space_type == space::kLargeObjectSpaceTypeFreeList) {
+ if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
capacity_);
CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
- } else if (large_object_space_type == space::kLargeObjectSpaceTypeMap) {
+ } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
} else {
diff --git a/runtime/gc/heap.h b/runtime/gc/heap.h
index 9aced81..0beb20c 100644
--- a/runtime/gc/heap.h
+++ b/runtime/gc/heap.h
@@ -152,7 +152,7 @@
space::kLargeObjectSpaceTypeFreeList;
#else
static constexpr space::LargeObjectSpaceType kDefaultLargeObjectSpaceType =
- space::kLargeObjectSpaceTypeMap;
+ space::LargeObjectSpaceType::kMap;
#endif
// Used so that we don't overflow the allocation time atomic integer.
static constexpr size_t kTimeAdjust = 1024;
diff --git a/runtime/gc/space/large_object_space.h b/runtime/gc/space/large_object_space.h
index 850a006..847f575 100644
--- a/runtime/gc/space/large_object_space.h
+++ b/runtime/gc/space/large_object_space.h
@@ -31,10 +31,10 @@
class AllocationInfo;
-enum LargeObjectSpaceType {
- kLargeObjectSpaceTypeDisabled,
- kLargeObjectSpaceTypeMap,
- kLargeObjectSpaceTypeFreeList,
+enum class LargeObjectSpaceType {
+ kDisabled,
+ kMap,
+ kFreeList,
};
// Abstraction implemented by all large object spaces.
diff --git a/runtime/globals.h b/runtime/globals.h
index 0756a73..0845475 100644
--- a/runtime/globals.h
+++ b/runtime/globals.h
@@ -110,16 +110,16 @@
#endif
// Kinds of tracing clocks.
-enum TraceClockSource {
- kTraceClockSourceThreadCpu,
- kTraceClockSourceWall,
- kTraceClockSourceDual, // Both wall and thread CPU clocks.
+enum class TraceClockSource {
+ kThreadCpu,
+ kWall,
+ kDual, // Both wall and thread CPU clocks.
};
#if defined(__linux__)
-static constexpr TraceClockSource kDefaultTraceClockSource = kTraceClockSourceDual;
+static constexpr TraceClockSource kDefaultTraceClockSource = TraceClockSource::kDual;
#else
-static constexpr TraceClockSource kDefaultTraceClockSource = kTraceClockSourceWall;
+static constexpr TraceClockSource kDefaultTraceClockSource = TraceClockSource::kWall;
#endif
static constexpr bool kDefaultMustRelocate = true;
diff --git a/runtime/java_vm_ext.cc b/runtime/java_vm_ext.cc
index 40417d8..ea7c192 100644
--- a/runtime/java_vm_ext.cc
+++ b/runtime/java_vm_ext.cc
@@ -32,6 +32,7 @@
#include "java_vm_ext.h"
#include "parsed_options.h"
#include "runtime-inl.h"
+#include "runtime_options.h"
#include "ScopedLocalRef.h"
#include "scoped_thread_state_change.h"
#include "thread-inl.h"
@@ -357,14 +358,15 @@
JII::AttachCurrentThreadAsDaemon
};
-JavaVMExt::JavaVMExt(Runtime* runtime, ParsedOptions* options)
+JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
: runtime_(runtime),
check_jni_abort_hook_(nullptr),
check_jni_abort_hook_data_(nullptr),
check_jni_(false), // Initialized properly in the constructor body below.
- force_copy_(options->force_copy_),
- tracing_enabled_(!options->jni_trace_.empty() || VLOG_IS_ON(third_party_jni)),
- trace_(options->jni_trace_),
+ force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
+ tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
+ || VLOG_IS_ON(third_party_jni)),
+ trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
globals_lock_("JNI global reference table lock"),
globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
libraries_(new Libraries),
@@ -374,9 +376,7 @@
allow_new_weak_globals_(true),
weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
functions = unchecked_functions_;
- if (options->check_jni_) {
- SetCheckJniEnabled(true);
- }
+ SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
}
JavaVMExt::~JavaVMExt() {
diff --git a/runtime/java_vm_ext.h b/runtime/java_vm_ext.h
index c3f0a82..037fbe5 100644
--- a/runtime/java_vm_ext.h
+++ b/runtime/java_vm_ext.h
@@ -34,10 +34,11 @@
class Libraries;
class ParsedOptions;
class Runtime;
+struct RuntimeArgumentMap;
class JavaVMExt : public JavaVM {
public:
- JavaVMExt(Runtime* runtime, ParsedOptions* options);
+ JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options);
~JavaVMExt();
bool ForceCopy() const {
diff --git a/runtime/jdwp/jdwp.h b/runtime/jdwp/jdwp.h
index 9309ab5..6464a62 100644
--- a/runtime/jdwp/jdwp.h
+++ b/runtime/jdwp/jdwp.h
@@ -108,6 +108,8 @@
uint16_t port;
};
+bool operator==(const JdwpOptions& lhs, const JdwpOptions& rhs);
+
struct JdwpEvent;
class JdwpNetStateBase;
struct ModBasket;
diff --git a/runtime/jdwp/jdwp_main.cc b/runtime/jdwp/jdwp_main.cc
index 40211de..b04aa6e 100644
--- a/runtime/jdwp/jdwp_main.cc
+++ b/runtime/jdwp/jdwp_main.cc
@@ -619,6 +619,18 @@
return !(lhs == rhs);
}
+bool operator==(const JdwpOptions& lhs, const JdwpOptions& rhs) {
+ if (&lhs == &rhs) {
+ return true;
+ }
+
+ return lhs.transport == rhs.transport &&
+ lhs.server == rhs.server &&
+ lhs.suspend == rhs.suspend &&
+ lhs.host == rhs.host &&
+ lhs.port == rhs.port;
+}
+
} // namespace JDWP
} // namespace art
diff --git a/runtime/parsed_options.cc b/runtime/parsed_options.cc
index 96430a0..b27bd6b 100644
--- a/runtime/parsed_options.cc
+++ b/runtime/parsed_options.cc
@@ -26,240 +26,327 @@
#include "trace.h"
#include "utils.h"
+#include "cmdline_parser.h"
+#include "runtime_options.h"
+
namespace art {
+using MemoryKiB = Memory<1024>;
+
ParsedOptions::ParsedOptions()
- :
- check_jni_(kIsDebugBuild), // -Xcheck:jni is off by default for regular
- // builds but on by default in debug builds.
- force_copy_(false),
- compiler_callbacks_(nullptr),
- is_zygote_(false),
- must_relocate_(kDefaultMustRelocate),
- dex2oat_enabled_(true),
- image_dex2oat_enabled_(true),
- interpreter_only_(kPoisonHeapReferences), // kPoisonHeapReferences currently works with
- // the interpreter only.
- // TODO: make it work with the compiler.
- is_explicit_gc_disabled_(false),
- use_tlab_(false),
- verify_pre_gc_heap_(false),
- verify_pre_sweeping_heap_(kIsDebugBuild), // Pre sweeping is the one that usually fails
- // if the GC corrupted the heap.
- verify_post_gc_heap_(false),
- verify_pre_gc_rosalloc_(kIsDebugBuild),
- verify_pre_sweeping_rosalloc_(false),
- verify_post_gc_rosalloc_(false),
- long_pause_log_threshold_(gc::Heap::kDefaultLongPauseLogThreshold),
- long_gc_log_threshold_(gc::Heap::kDefaultLongGCLogThreshold),
- dump_gc_performance_on_shutdown_(false),
- ignore_max_footprint_(false),
- heap_initial_size_(gc::Heap::kDefaultInitialSize),
- heap_maximum_size_(gc::Heap::kDefaultMaximumSize),
- heap_growth_limit_(0), // 0 means no growth limit.
- heap_min_free_(gc::Heap::kDefaultMinFree),
- heap_max_free_(gc::Heap::kDefaultMaxFree),
- heap_non_moving_space_capacity_(gc::Heap::kDefaultNonMovingSpaceCapacity),
- large_object_space_type_(gc::Heap::kDefaultLargeObjectSpaceType),
- large_object_threshold_(gc::Heap::kDefaultLargeObjectThreshold),
- heap_target_utilization_(gc::Heap::kDefaultTargetUtilization),
- foreground_heap_growth_multiplier_(gc::Heap::kDefaultHeapGrowthMultiplier),
- parallel_gc_threads_(1),
- conc_gc_threads_(0), // Only the main GC thread, no workers.
- collector_type_( // The default GC type is set in makefiles.
-#if ART_DEFAULT_GC_TYPE_IS_CMS
- gc::kCollectorTypeCMS),
-#elif ART_DEFAULT_GC_TYPE_IS_SS
- gc::kCollectorTypeSS),
-#elif ART_DEFAULT_GC_TYPE_IS_GSS
- gc::kCollectorTypeGSS),
-#else
- gc::kCollectorTypeCMS),
-#error "ART default GC type must be set"
-#endif
- background_collector_type_(gc::kCollectorTypeNone),
- // If background_collector_type_ is
- // kCollectorTypeNone, it defaults to the
- // collector_type_ after parsing options. If
- // you set this to kCollectorTypeHSpaceCompact
- // then we will do an hspace compaction when
- // we transition to background instead of a
- // normal collector transition.
- stack_size_(0), // 0 means default.
- max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
- low_memory_mode_(false),
- lock_profiling_threshold_(0),
- method_trace_(false),
- method_trace_file_("/data/method-trace-file.bin"),
- method_trace_file_size_(10 * MB),
- hook_is_sensitive_thread_(nullptr),
+ : hook_is_sensitive_thread_(nullptr),
hook_vfprintf_(vfprintf),
hook_exit_(exit),
- hook_abort_(nullptr), // We don't call abort(3) by default; see
- // Runtime::Abort.
- profile_clock_source_(kDefaultTraceClockSource),
- verify_(true),
- image_isa_(kRuntimeISA),
- use_homogeneous_space_compaction_for_oom_(true), // Enable hspace compaction on OOM by default.
- min_interval_homogeneous_space_compaction_by_oom_(MsToNs(100 * 1000)) { // 100s.
- if (kUseReadBarrier) {
- // If RB is enabled (currently a build-time decision), use CC as the default GC.
- collector_type_ = gc::kCollectorTypeCC;
- background_collector_type_ = gc::kCollectorTypeCC; // Disable background compaction for CC.
- interpreter_only_ = true; // Disable the compiler for CC (for now).
- // use_tlab_ = true;
- }
+ hook_abort_(nullptr) { // We don't call abort(3) by default; see
+ // Runtime::Abort
}
-ParsedOptions* ParsedOptions::Create(const RuntimeOptions& options, bool ignore_unrecognized) {
+ParsedOptions* ParsedOptions::Create(const RuntimeOptions& options, bool ignore_unrecognized,
+ RuntimeArgumentMap* runtime_options) {
+ CHECK(runtime_options != nullptr);
+
std::unique_ptr<ParsedOptions> parsed(new ParsedOptions());
- if (parsed->Parse(options, ignore_unrecognized)) {
+ if (parsed->Parse(options, ignore_unrecognized, runtime_options)) {
return parsed.release();
}
return nullptr;
}
-// Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
-// memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
-// [gG] gigabytes.
-//
-// "s" should point just past the "-Xm?" part of the string.
-// "div" specifies a divisor, e.g. 1024 if the value must be a multiple
-// of 1024.
-//
-// The spec says the -Xmx and -Xms options must be multiples of 1024. It
-// doesn't say anything about -Xss.
-//
-// Returns 0 (a useless size) if "s" is malformed or specifies a low or
-// non-evenly-divisible value.
-//
-size_t ParseMemoryOption(const char* s, size_t div) {
- // strtoul accepts a leading [+-], which we don't want,
- // so make sure our string starts with a decimal digit.
- if (isdigit(*s)) {
- char* s2;
- size_t val = strtoul(s, &s2, 10);
- if (s2 != s) {
- // s2 should be pointing just after the number.
- // If this is the end of the string, the user
- // has specified a number of bytes. Otherwise,
- // there should be exactly one more character
- // that specifies a multiplier.
- if (*s2 != '\0') {
- // The remainder of the string is either a single multiplier
- // character, or nothing to indicate that the value is in
- // bytes.
- char c = *s2++;
- if (*s2 == '\0') {
- size_t mul;
- if (c == '\0') {
- mul = 1;
- } else if (c == 'k' || c == 'K') {
- mul = KB;
- } else if (c == 'm' || c == 'M') {
- mul = MB;
- } else if (c == 'g' || c == 'G') {
- mul = GB;
- } else {
- // Unknown multiplier character.
- return 0;
- }
+using RuntimeParser = CmdlineParser<RuntimeArgumentMap, RuntimeArgumentMap::Key>;
- if (val <= std::numeric_limits<size_t>::max() / mul) {
- val *= mul;
- } else {
- // Clamp to a multiple of 1024.
- val = std::numeric_limits<size_t>::max() & ~(1024-1);
- }
- } else {
- // There's more than one character after the numeric part.
- return 0;
- }
- }
- // The man page says that a -Xm value must be a multiple of 1024.
- if (val % div == 0) {
- return val;
- }
- }
- }
- return 0;
+// Yes, the stack frame is huge. But we get called super early on (and just once)
+// to pass the command line arguments, so we'll probably be ok.
+// Ideas to avoid suppressing this diagnostic are welcome!
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wframe-larger-than="
+
+std::unique_ptr<RuntimeParser> ParsedOptions::MakeParser(bool ignore_unrecognized) {
+ using M = RuntimeArgumentMap;
+
+ std::unique_ptr<RuntimeParser::Builder> parser_builder =
+ std::unique_ptr<RuntimeParser::Builder>(new RuntimeParser::Builder());
+
+ parser_builder->
+ Define("-Xzygote")
+ .IntoKey(M::Zygote)
+ .Define("-help")
+ .IntoKey(M::Help)
+ .Define("-showversion")
+ .IntoKey(M::ShowVersion)
+ .Define("-Xbootclasspath:_")
+ .WithType<std::string>()
+ .IntoKey(M::BootClassPath)
+ .Define("-Xbootclasspath-locations:_")
+ .WithType<ParseStringList<':'>>() // std::vector<std::string>, split by :
+ .IntoKey(M::BootClassPathLocations)
+ .Define({"-classpath _", "-cp _"})
+ .WithType<std::string>()
+ .IntoKey(M::ClassPath)
+ .Define("-Ximage:_")
+ .WithType<std::string>()
+ .IntoKey(M::Image)
+ .Define("-Xcheck:jni")
+ .IntoKey(M::CheckJni)
+ .Define("-Xjniopts:forcecopy")
+ .IntoKey(M::JniOptsForceCopy)
+ .Define({"-Xrunjdwp:_", "-agentlib:jdwp=_"})
+ .WithType<JDWP::JdwpOptions>()
+ .IntoKey(M::JdwpOptions)
+ .Define("-Xms_")
+ .WithType<MemoryKiB>()
+ .IntoKey(M::MemoryInitialSize)
+ .Define("-Xmx_")
+ .WithType<MemoryKiB>()
+ .IntoKey(M::MemoryMaximumSize)
+ .Define("-XX:HeapGrowthLimit=_")
+ .WithType<MemoryKiB>()
+ .IntoKey(M::HeapGrowthLimit)
+ .Define("-XX:HeapMinFree=_")
+ .WithType<MemoryKiB>()
+ .IntoKey(M::HeapMinFree)
+ .Define("-XX:HeapMaxFree=_")
+ .WithType<MemoryKiB>()
+ .IntoKey(M::HeapMaxFree)
+ .Define("-XX:NonMovingSpaceCapacity=_")
+ .WithType<MemoryKiB>()
+ .IntoKey(M::NonMovingSpaceCapacity)
+ .Define("-XX:HeapTargetUtilization=_")
+ .WithType<double>().WithRange(0.1, 0.9)
+ .IntoKey(M::HeapTargetUtilization)
+ .Define("-XX:ForegroundHeapGrowthMultiplier=_")
+ .WithType<double>().WithRange(0.1, 1.0)
+ .IntoKey(M::ForegroundHeapGrowthMultiplier)
+ .Define("-XX:ParallelGCThreads=_")
+ .WithType<unsigned int>()
+ .IntoKey(M::ParallelGCThreads)
+ .Define("-XX:ConcGCThreads=_")
+ .WithType<unsigned int>()
+ .IntoKey(M::ConcGCThreads)
+ .Define("-Xss_")
+ .WithType<Memory<1>>()
+ .IntoKey(M::StackSize)
+ .Define("-XX:MaxSpinsBeforeThinLockInflation=_")
+ .WithType<unsigned int>()
+ .IntoKey(M::MaxSpinsBeforeThinLockInflation)
+ .Define("-XX:LongPauseLogThreshold=_") // in ms
+ .WithType<MillisecondsToNanoseconds>() // store as ns
+ .IntoKey(M::LongPauseLogThreshold)
+ .Define("-XX:LongGCLogThreshold=_") // in ms
+ .WithType<MillisecondsToNanoseconds>() // store as ns
+ .IntoKey(M::LongGCLogThreshold)
+ .Define("-XX:DumpGCPerformanceOnShutdown")
+ .IntoKey(M::DumpGCPerformanceOnShutdown)
+ .Define("-XX:IgnoreMaxFootprint")
+ .IntoKey(M::IgnoreMaxFootprint)
+ .Define("-XX:LowMemoryMode")
+ .IntoKey(M::LowMemoryMode)
+ .Define("-XX:UseTLAB")
+ .IntoKey(M::UseTLAB)
+ .Define({"-XX:EnableHSpaceCompactForOOM", "-XX:DisableHSpaceCompactForOOM"})
+ .WithValues({true, false})
+ .IntoKey(M::EnableHSpaceCompactForOOM)
+ .Define("-XX:HspaceCompactForOOMMinIntervalMs=_") // in ms
+ .WithType<MillisecondsToNanoseconds>() // store as ns
+ .IntoKey(M::HSpaceCompactForOOMMinIntervalsMs)
+ .Define("-D_")
+ .WithType<std::vector<std::string>>().AppendValues()
+ .IntoKey(M::PropertiesList)
+ .Define("-Xjnitrace:_")
+ .WithType<std::string>()
+ .IntoKey(M::JniTrace)
+ .Define("-Xpatchoat:_")
+ .WithType<std::string>()
+ .IntoKey(M::PatchOat)
+ .Define({"-Xrelocate", "-Xnorelocate"})
+ .WithValues({true, false})
+ .IntoKey(M::Relocate)
+ .Define({"-Xdex2oat", "-Xnodex2oat"})
+ .WithValues({true, false})
+ .IntoKey(M::Dex2Oat)
+ .Define({"-Ximage-dex2oat", "-Xnoimage-dex2oat"})
+ .WithValues({true, false})
+ .IntoKey(M::ImageDex2Oat)
+ .Define("-Xint")
+ .WithValue(true)
+ .IntoKey(M::Interpret)
+ .Define("-Xgc:_")
+ .WithType<XGcOption>()
+ .IntoKey(M::GcOption)
+ .Define("-XX:LargeObjectSpace=_")
+ .WithType<gc::space::LargeObjectSpaceType>()
+ .WithValueMap({{"disabled", gc::space::LargeObjectSpaceType::kDisabled},
+ {"freelist", gc::space::LargeObjectSpaceType::kFreeList},
+ {"map", gc::space::LargeObjectSpaceType::kMap}})
+ .IntoKey(M::LargeObjectSpace)
+ .Define("-XX:LargeObjectThreshold=_")
+ .WithType<Memory<1>>()
+ .IntoKey(M::LargeObjectThreshold)
+ .Define("-XX:BackgroundGC=_")
+ .WithType<BackgroundGcOption>()
+ .IntoKey(M::BackgroundGc)
+ .Define("-XX:+DisableExplicitGC")
+ .IntoKey(M::DisableExplicitGC)
+ .Define("-verbose:_")
+ .WithType<LogVerbosity>()
+ .IntoKey(M::Verbose)
+ .Define("-Xlockprofthreshold:_")
+ .WithType<unsigned int>()
+ .IntoKey(M::LockProfThreshold)
+ .Define("-Xstacktracefile:_")
+ .WithType<std::string>()
+ .IntoKey(M::StackTraceFile)
+ .Define("-Xmethod-trace")
+ .IntoKey(M::MethodTrace)
+ .Define("-Xmethod-trace-file:_")
+ .WithType<std::string>()
+ .IntoKey(M::MethodTraceFile)
+ .Define("-Xmethod-trace-file-size:_")
+ .WithType<unsigned int>()
+ .IntoKey(M::MethodTraceFileSize)
+ .Define("-Xprofile:_")
+ .WithType<TraceClockSource>()
+ .WithValueMap({{"threadcpuclock", TraceClockSource::kThreadCpu},
+ {"wallclock", TraceClockSource::kWall},
+ {"dualclock", TraceClockSource::kDual}})
+ .IntoKey(M::ProfileClock)
+ .Define("-Xenable-profiler")
+ .WithType<TestProfilerOptions>()
+ .AppendValues()
+ .IntoKey(M::ProfilerOpts) // NOTE: Appends into same key as -Xprofile-*
+ .Define("-Xprofile-_") // -Xprofile-<key>:<value>
+ .WithType<TestProfilerOptions>()
+ .AppendValues()
+ .IntoKey(M::ProfilerOpts) // NOTE: Appends into same key as -Xenable-profiler
+ .Define("-Xcompiler:_")
+ .WithType<std::string>()
+ .IntoKey(M::Compiler)
+ .Define("-Xcompiler-option _")
+ .WithType<std::vector<std::string>>()
+ .AppendValues()
+ .IntoKey(M::CompilerOptions)
+ .Define("-Ximage-compiler-option _")
+ .WithType<std::vector<std::string>>()
+ .AppendValues()
+ .IntoKey(M::ImageCompilerOptions)
+ .Define("-Xverify:_")
+ .WithType<bool>()
+ .WithValueMap({{"none", false},
+ {"remote", true},
+ {"all", true}})
+ .IntoKey(M::Verify)
+ .Define("-XX:NativeBridge=_")
+ .WithType<std::string>()
+ .IntoKey(M::NativeBridge)
+ .Ignore({
+ "-ea", "-da", "-enableassertions", "-disableassertions", "--runtime-arg", "-esa",
+ "-dsa", "-enablesystemassertions", "-disablesystemassertions", "-Xrs", "-Xint:_",
+ "-Xdexopt:_", "-Xnoquithandler", "-Xjnigreflimit:_", "-Xgenregmap", "-Xnogenregmap",
+ "-Xverifyopt:_", "-Xcheckdexsum", "-Xincludeselectedop", "-Xjitop:_",
+ "-Xincludeselectedmethod", "-Xjitthreshold:_", "-Xjitcodecachesize:_",
+ "-Xjitblocking", "-Xjitmethod:_", "-Xjitclass:_", "-Xjitoffset:_",
+ "-Xjitconfig:_", "-Xjitcheckcg", "-Xjitverbose", "-Xjitprofile",
+ "-Xjitdisableopt", "-Xjitsuspendpoll", "-XX:mainThreadStackSize=_"})
+ .IgnoreUnrecognized(ignore_unrecognized);
+
+ // TODO: Move Usage information into this DSL.
+
+ return std::unique_ptr<RuntimeParser>(new RuntimeParser(parser_builder->Build()));
}
-static gc::CollectorType ParseCollectorType(const std::string& option) {
- if (option == "MS" || option == "nonconcurrent") {
- return gc::kCollectorTypeMS;
- } else if (option == "CMS" || option == "concurrent") {
- return gc::kCollectorTypeCMS;
- } else if (option == "SS") {
- return gc::kCollectorTypeSS;
- } else if (option == "GSS") {
- return gc::kCollectorTypeGSS;
- } else if (option == "CC") {
- return gc::kCollectorTypeCC;
- } else if (option == "MC") {
- return gc::kCollectorTypeMC;
- } else {
- return gc::kCollectorTypeNone;
- }
-}
+#pragma GCC diagnostic pop
-bool ParsedOptions::ParseXGcOption(const std::string& option) {
- std::vector<std::string> gc_options;
- Split(option.substr(strlen("-Xgc:")), ',', &gc_options);
- for (const std::string& gc_option : gc_options) {
- gc::CollectorType collector_type = ParseCollectorType(gc_option);
- if (collector_type != gc::kCollectorTypeNone) {
- collector_type_ = collector_type;
- } else if (gc_option == "preverify") {
- verify_pre_gc_heap_ = true;
- } else if (gc_option == "nopreverify") {
- verify_pre_gc_heap_ = false;
- } else if (gc_option == "presweepingverify") {
- verify_pre_sweeping_heap_ = true;
- } else if (gc_option == "nopresweepingverify") {
- verify_pre_sweeping_heap_ = false;
- } else if (gc_option == "postverify") {
- verify_post_gc_heap_ = true;
- } else if (gc_option == "nopostverify") {
- verify_post_gc_heap_ = false;
- } else if (gc_option == "preverify_rosalloc") {
- verify_pre_gc_rosalloc_ = true;
- } else if (gc_option == "nopreverify_rosalloc") {
- verify_pre_gc_rosalloc_ = false;
- } else if (gc_option == "presweepingverify_rosalloc") {
- verify_pre_sweeping_rosalloc_ = true;
- } else if (gc_option == "nopresweepingverify_rosalloc") {
- verify_pre_sweeping_rosalloc_ = false;
- } else if (gc_option == "postverify_rosalloc") {
- verify_post_gc_rosalloc_ = true;
- } else if (gc_option == "nopostverify_rosalloc") {
- verify_post_gc_rosalloc_ = false;
- } else if ((gc_option == "precise") ||
- (gc_option == "noprecise") ||
- (gc_option == "verifycardtable") ||
- (gc_option == "noverifycardtable")) {
- // Ignored for backwards compatibility.
+// Remove all the special options that have something in the void* part of the option.
+// If runtime_options is not null, put the options in there.
+// As a side-effect, populate the hooks from options.
+bool ParsedOptions::ProcessSpecialOptions(const RuntimeOptions& options,
+ RuntimeArgumentMap* runtime_options,
+ std::vector<std::string>* out_options) {
+ using M = RuntimeArgumentMap;
+
+ // TODO: Move the below loop into JNI
+ // Handle special options that set up hooks
+ for (size_t i = 0; i < options.size(); ++i) {
+ const std::string option(options[i].first);
+ // TODO: support -Djava.class.path
+ if (option == "bootclasspath") {
+ auto boot_class_path
+ = reinterpret_cast<const std::vector<const DexFile*>*>(options[i].second);
+
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::BootClassPathDexList, boot_class_path);
+ }
+ } else if (option == "compilercallbacks") {
+ CompilerCallbacks* compiler_callbacks =
+ reinterpret_cast<CompilerCallbacks*>(const_cast<void*>(options[i].second));
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::CompilerCallbacksPtr, compiler_callbacks);
+ }
+ } else if (option == "imageinstructionset") {
+ const char* isa_str = reinterpret_cast<const char*>(options[i].second);
+ auto&& image_isa = GetInstructionSetFromString(isa_str);
+ if (image_isa == kNone) {
+ Usage("%s is not a valid instruction set.", isa_str);
+ return false;
+ }
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::ImageInstructionSet, image_isa);
+ }
+ } else if (option == "sensitiveThread") {
+ const void* hook = options[i].second;
+ bool (*hook_is_sensitive_thread)() = reinterpret_cast<bool (*)()>(const_cast<void*>(hook));
+
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::HookIsSensitiveThread, hook_is_sensitive_thread);
+ }
+ } else if (option == "vfprintf") {
+ const void* hook = options[i].second;
+ if (hook == nullptr) {
+ Usage("vfprintf argument was NULL");
+ return false;
+ }
+ int (*hook_vfprintf)(FILE *, const char*, va_list) =
+ reinterpret_cast<int (*)(FILE *, const char*, va_list)>(const_cast<void*>(hook));
+
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::HookVfprintf, hook_vfprintf);
+ }
+ hook_vfprintf_ = hook_vfprintf;
+ } else if (option == "exit") {
+ const void* hook = options[i].second;
+ if (hook == nullptr) {
+ Usage("exit argument was NULL");
+ return false;
+ }
+ void(*hook_exit)(jint) = reinterpret_cast<void(*)(jint)>(const_cast<void*>(hook));
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::HookExit, hook_exit);
+ }
+ hook_exit_ = hook_exit;
+ } else if (option == "abort") {
+ const void* hook = options[i].second;
+ if (hook == nullptr) {
+ Usage("abort was NULL\n");
+ return false;
+ }
+ void(*hook_abort)() = reinterpret_cast<void(*)()>(const_cast<void*>(hook));
+ if (runtime_options != nullptr) {
+ runtime_options->Set(M::HookAbort, hook_abort);
+ }
+ hook_abort_ = hook_abort;
} else {
- Usage("Unknown -Xgc option %s\n", gc_option.c_str());
- return false;
+ // It is a regular option, that doesn't have a known 'second' value.
+ // Push it on to the regular options which will be parsed by our parser.
+ if (out_options != nullptr) {
+ out_options->push_back(option);
+ }
}
}
+
return true;
}
-bool ParsedOptions::Parse(const RuntimeOptions& options, bool ignore_unrecognized) {
- const char* boot_class_path_string = getenv("BOOTCLASSPATH");
- if (boot_class_path_string != NULL) {
- boot_class_path_string_ = boot_class_path_string;
- }
- const char* class_path_string = getenv("CLASSPATH");
- if (class_path_string != NULL) {
- class_path_string_ = class_path_string;
- }
-
- // Default to number of processors minus one since the main GC thread also does work.
- parallel_gc_threads_ = sysconf(_SC_NPROCESSORS_CONF) - 1;
-
+bool ParsedOptions::Parse(const RuntimeOptions& options, bool ignore_unrecognized,
+ RuntimeArgumentMap* runtime_options) {
// gLogVerbosity.class_linker = true; // TODO: don't check this in!
// gLogVerbosity.compiler = true; // TODO: don't check this in!
// gLogVerbosity.gc = true; // TODO: don't check this in!
@@ -279,435 +366,110 @@
LOG(INFO) << "option[" << i << "]=" << options[i].first;
}
}
- for (size_t i = 0; i < options.size(); ++i) {
- const std::string option(options[i].first);
- if (StartsWith(option, "-help")) {
- Usage(nullptr);
- return false;
- } else if (StartsWith(option, "-showversion")) {
- UsageMessage(stdout, "ART version %s\n", Runtime::GetVersion());
+
+ auto parser = MakeParser(ignore_unrecognized);
+
+ // Convert to a simple string list (without the magic pointer options)
+ std::vector<std::string> argv_list;
+ if (!ProcessSpecialOptions(options, nullptr, &argv_list)) {
+ return false;
+ }
+
+ CmdlineResult parse_result = parser->Parse(argv_list);
+
+ // Handle parse errors by displaying the usage and potentially exiting.
+ if (parse_result.IsError()) {
+ if (parse_result.GetStatus() == CmdlineResult::kUsage) {
+ UsageMessage(stdout, "%s\n", parse_result.GetMessage().c_str());
Exit(0);
- } else if (StartsWith(option, "-Xbootclasspath:")) {
- boot_class_path_string_ = option.substr(strlen("-Xbootclasspath:")).data();
- LOG(INFO) << "setting boot class path to " << boot_class_path_string_;
- } else if (StartsWith(option, "-Xbootclasspath-locations:")) {
- boot_class_path_locations_string_ = option.substr(
- strlen("-Xbootclasspath-locations:")).data();
- } else if (option == "-classpath" || option == "-cp") {
- // TODO: support -Djava.class.path
- i++;
- if (i == options.size()) {
- Usage("Missing required class path value for %s\n", option.c_str());
- return false;
- }
- const StringPiece& value = options[i].first;
- class_path_string_ = value.data();
- } else if (StartsWith(option, "-Ximage:")) {
- if (!ParseStringAfterChar(option, ':', &image_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xcheck:jni")) {
- check_jni_ = true;
- } else if (StartsWith(option, "-Xjniopts:forcecopy")) {
- force_copy_ = true;
- } else if (StartsWith(option, "-Xrunjdwp:") || StartsWith(option, "-agentlib:jdwp=")) {
- std::string tail(option.substr(option[1] == 'X' ? 10 : 15));
- // TODO: move parsing logic out of Dbg
- if (tail == "help" || !Dbg::ParseJdwpOptions(tail)) {
- if (tail != "help") {
- UsageMessage(stderr, "Failed to parse JDWP option %s\n", tail.c_str());
- }
- Usage("Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
- "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
- return false;
- }
- } else if (StartsWith(option, "-Xms")) {
- size_t size = ParseMemoryOption(option.substr(strlen("-Xms")).c_str(), 1024);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- heap_initial_size_ = size;
- } else if (StartsWith(option, "-Xmx")) {
- size_t size = ParseMemoryOption(option.substr(strlen("-Xmx")).c_str(), 1024);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- heap_maximum_size_ = size;
- } else if (StartsWith(option, "-XX:HeapGrowthLimit=")) {
- size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapGrowthLimit=")).c_str(), 1024);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- heap_growth_limit_ = size;
- } else if (StartsWith(option, "-XX:HeapMinFree=")) {
- size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMinFree=")).c_str(), 1024);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- heap_min_free_ = size;
- } else if (StartsWith(option, "-XX:HeapMaxFree=")) {
- size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMaxFree=")).c_str(), 1024);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- heap_max_free_ = size;
- } else if (StartsWith(option, "-XX:NonMovingSpaceCapacity=")) {
- size_t size = ParseMemoryOption(
- option.substr(strlen("-XX:NonMovingSpaceCapacity=")).c_str(), 1024);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- heap_non_moving_space_capacity_ = size;
- } else if (StartsWith(option, "-XX:HeapTargetUtilization=")) {
- if (!ParseDouble(option, '=', 0.1, 0.9, &heap_target_utilization_)) {
- return false;
- }
- } else if (StartsWith(option, "-XX:ForegroundHeapGrowthMultiplier=")) {
- if (!ParseDouble(option, '=', 0.1, 10.0, &foreground_heap_growth_multiplier_)) {
- return false;
- }
- } else if (StartsWith(option, "-XX:ParallelGCThreads=")) {
- if (!ParseUnsignedInteger(option, '=', ¶llel_gc_threads_)) {
- return false;
- }
- } else if (StartsWith(option, "-XX:ConcGCThreads=")) {
- if (!ParseUnsignedInteger(option, '=', &conc_gc_threads_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xss")) {
- size_t size = ParseMemoryOption(option.substr(strlen("-Xss")).c_str(), 1);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- stack_size_ = size;
- } else if (StartsWith(option, "-XX:MaxSpinsBeforeThinLockInflation=")) {
- if (!ParseUnsignedInteger(option, '=', &max_spins_before_thin_lock_inflation_)) {
- return false;
- }
- } else if (StartsWith(option, "-XX:LongPauseLogThreshold=")) {
- unsigned int value;
- if (!ParseUnsignedInteger(option, '=', &value)) {
- return false;
- }
- long_pause_log_threshold_ = MsToNs(value);
- } else if (StartsWith(option, "-XX:LongGCLogThreshold=")) {
- unsigned int value;
- if (!ParseUnsignedInteger(option, '=', &value)) {
- return false;
- }
- long_gc_log_threshold_ = MsToNs(value);
- } else if (option == "-XX:DumpGCPerformanceOnShutdown") {
- dump_gc_performance_on_shutdown_ = true;
- } else if (option == "-XX:IgnoreMaxFootprint") {
- ignore_max_footprint_ = true;
- } else if (option == "-XX:LowMemoryMode") {
- low_memory_mode_ = true;
- // TODO Might want to turn off must_relocate here.
- } else if (option == "-XX:UseTLAB") {
- use_tlab_ = true;
- } else if (option == "-XX:EnableHSpaceCompactForOOM") {
- use_homogeneous_space_compaction_for_oom_ = true;
- } else if (option == "-XX:DisableHSpaceCompactForOOM") {
- use_homogeneous_space_compaction_for_oom_ = false;
- } else if (StartsWith(option, "-XX:HspaceCompactForOOMMinIntervalMs=")) {
- unsigned int value;
- if (!ParseUnsignedInteger(option, '=', &value)) {
- return false;
- }
- min_interval_homogeneous_space_compaction_by_oom_ = MsToNs(value);
- } else if (StartsWith(option, "-D")) {
- properties_.push_back(option.substr(strlen("-D")));
- } else if (StartsWith(option, "-Xjnitrace:")) {
- jni_trace_ = option.substr(strlen("-Xjnitrace:"));
- } else if (option == "compilercallbacks") {
- compiler_callbacks_ =
- reinterpret_cast<CompilerCallbacks*>(const_cast<void*>(options[i].second));
- } else if (option == "imageinstructionset") {
- const char* isa_str = reinterpret_cast<const char*>(options[i].second);
- image_isa_ = GetInstructionSetFromString(isa_str);
- if (image_isa_ == kNone) {
- Usage("%s is not a valid instruction set.", isa_str);
- return false;
- }
- } else if (option == "-Xzygote") {
- is_zygote_ = true;
- } else if (StartsWith(option, "-Xpatchoat:")) {
- if (!ParseStringAfterChar(option, ':', &patchoat_executable_)) {
- return false;
- }
- } else if (option == "-Xrelocate") {
- must_relocate_ = true;
- } else if (option == "-Xnorelocate") {
- must_relocate_ = false;
- } else if (option == "-Xnodex2oat") {
- dex2oat_enabled_ = false;
- } else if (option == "-Xdex2oat") {
- dex2oat_enabled_ = true;
- } else if (option == "-Xnoimage-dex2oat") {
- image_dex2oat_enabled_ = false;
- } else if (option == "-Ximage-dex2oat") {
- image_dex2oat_enabled_ = true;
- } else if (option == "-Xint") {
- interpreter_only_ = true;
- } else if (StartsWith(option, "-Xgc:")) {
- if (!ParseXGcOption(option)) {
- return false;
- }
- } else if (StartsWith(option, "-XX:LargeObjectSpace=")) {
- std::string substring;
- if (!ParseStringAfterChar(option, '=', &substring)) {
- return false;
- }
- if (substring == "disabled") {
- large_object_space_type_ = gc::space::kLargeObjectSpaceTypeDisabled;
- } else if (substring == "freelist") {
- large_object_space_type_ = gc::space::kLargeObjectSpaceTypeFreeList;
- } else if (substring == "map") {
- large_object_space_type_ = gc::space::kLargeObjectSpaceTypeMap;
- } else {
- Usage("Unknown -XX:LargeObjectSpace= option %s\n", substring.c_str());
- return false;
- }
- } else if (StartsWith(option, "-XX:LargeObjectThreshold=")) {
- std::string substring;
- if (!ParseStringAfterChar(option, '=', &substring)) {
- return false;
- }
- size_t size = ParseMemoryOption(substring.c_str(), 1);
- if (size == 0) {
- Usage("Failed to parse memory option %s\n", option.c_str());
- return false;
- }
- large_object_threshold_ = size;
- } else if (StartsWith(option, "-XX:BackgroundGC=")) {
- std::string substring;
- if (!ParseStringAfterChar(option, '=', &substring)) {
- return false;
- }
- // Special handling for HSpaceCompact since this is only valid as a background GC type.
- if (substring == "HSpaceCompact") {
- background_collector_type_ = gc::kCollectorTypeHomogeneousSpaceCompact;
- } else {
- gc::CollectorType collector_type = ParseCollectorType(substring);
- if (collector_type != gc::kCollectorTypeNone) {
- background_collector_type_ = collector_type;
- } else {
- Usage("Unknown -XX:BackgroundGC option %s\n", substring.c_str());
- return false;
- }
- }
- } else if (option == "-XX:+DisableExplicitGC") {
- is_explicit_gc_disabled_ = true;
- } else if (StartsWith(option, "-verbose:")) {
- std::vector<std::string> verbose_options;
- Split(option.substr(strlen("-verbose:")), ',', &verbose_options);
- for (size_t j = 0; j < verbose_options.size(); ++j) {
- if (verbose_options[j] == "class") {
- gLogVerbosity.class_linker = true;
- } else if (verbose_options[j] == "compiler") {
- gLogVerbosity.compiler = true;
- } else if (verbose_options[j] == "gc") {
- gLogVerbosity.gc = true;
- } else if (verbose_options[j] == "heap") {
- gLogVerbosity.heap = true;
- } else if (verbose_options[j] == "jdwp") {
- gLogVerbosity.jdwp = true;
- } else if (verbose_options[j] == "jni") {
- gLogVerbosity.jni = true;
- } else if (verbose_options[j] == "monitor") {
- gLogVerbosity.monitor = true;
- } else if (verbose_options[j] == "profiler") {
- gLogVerbosity.profiler = true;
- } else if (verbose_options[j] == "signals") {
- gLogVerbosity.signals = true;
- } else if (verbose_options[j] == "startup") {
- gLogVerbosity.startup = true;
- } else if (verbose_options[j] == "third-party-jni") {
- gLogVerbosity.third_party_jni = true;
- } else if (verbose_options[j] == "threads") {
- gLogVerbosity.threads = true;
- } else if (verbose_options[j] == "verifier") {
- gLogVerbosity.verifier = true;
- } else {
- Usage("Unknown -verbose option %s\n", verbose_options[j].c_str());
- return false;
- }
- }
- } else if (StartsWith(option, "-Xlockprofthreshold:")) {
- if (!ParseUnsignedInteger(option, ':', &lock_profiling_threshold_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xstacktracefile:")) {
- if (!ParseStringAfterChar(option, ':', &stack_trace_file_)) {
- return false;
- }
- } else if (option == "sensitiveThread") {
- const void* hook = options[i].second;
- hook_is_sensitive_thread_ = reinterpret_cast<bool (*)()>(const_cast<void*>(hook));
- } else if (option == "vfprintf") {
- const void* hook = options[i].second;
- if (hook == nullptr) {
- Usage("vfprintf argument was NULL");
- return false;
- }
- hook_vfprintf_ =
- reinterpret_cast<int (*)(FILE *, const char*, va_list)>(const_cast<void*>(hook));
- } else if (option == "exit") {
- const void* hook = options[i].second;
- if (hook == nullptr) {
- Usage("exit argument was NULL");
- return false;
- }
- hook_exit_ = reinterpret_cast<void(*)(jint)>(const_cast<void*>(hook));
- } else if (option == "abort") {
- const void* hook = options[i].second;
- if (hook == nullptr) {
- Usage("abort was NULL\n");
- return false;
- }
- hook_abort_ = reinterpret_cast<void(*)()>(const_cast<void*>(hook));
- } else if (option == "-Xmethod-trace") {
- method_trace_ = true;
- } else if (StartsWith(option, "-Xmethod-trace-file:")) {
- method_trace_file_ = option.substr(strlen("-Xmethod-trace-file:"));
- } else if (StartsWith(option, "-Xmethod-trace-file-size:")) {
- if (!ParseUnsignedInteger(option, ':', &method_trace_file_size_)) {
- return false;
- }
- } else if (option == "-Xprofile:threadcpuclock") {
- Trace::SetDefaultClockSource(kTraceClockSourceThreadCpu);
- } else if (option == "-Xprofile:wallclock") {
- Trace::SetDefaultClockSource(kTraceClockSourceWall);
- } else if (option == "-Xprofile:dualclock") {
- Trace::SetDefaultClockSource(kTraceClockSourceDual);
- } else if (option == "-Xenable-profiler") {
- profiler_options_.enabled_ = true;
- } else if (StartsWith(option, "-Xprofile-filename:")) {
- if (!ParseStringAfterChar(option, ':', &profile_output_filename_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xprofile-period:")) {
- if (!ParseUnsignedInteger(option, ':', &profiler_options_.period_s_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xprofile-duration:")) {
- if (!ParseUnsignedInteger(option, ':', &profiler_options_.duration_s_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xprofile-interval:")) {
- if (!ParseUnsignedInteger(option, ':', &profiler_options_.interval_us_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xprofile-backoff:")) {
- if (!ParseDouble(option, ':', 1.0, 10.0, &profiler_options_.backoff_coefficient_)) {
- return false;
- }
- } else if (option == "-Xprofile-start-immediately") {
- profiler_options_.start_immediately_ = true;
- } else if (StartsWith(option, "-Xprofile-top-k-threshold:")) {
- if (!ParseDouble(option, ':', 0.0, 100.0, &profiler_options_.top_k_threshold_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xprofile-top-k-change-threshold:")) {
- if (!ParseDouble(option, ':', 0.0, 100.0, &profiler_options_.top_k_change_threshold_)) {
- return false;
- }
- } else if (option == "-Xprofile-type:method") {
- profiler_options_.profile_type_ = kProfilerMethod;
- } else if (option == "-Xprofile-type:stack") {
- profiler_options_.profile_type_ = kProfilerBoundedStack;
- } else if (StartsWith(option, "-Xprofile-max-stack-depth:")) {
- if (!ParseUnsignedInteger(option, ':', &profiler_options_.max_stack_depth_)) {
- return false;
- }
- } else if (StartsWith(option, "-Xcompiler:")) {
- if (!ParseStringAfterChar(option, ':', &compiler_executable_)) {
- return false;
- }
- } else if (option == "-Xcompiler-option") {
- i++;
- if (i == options.size()) {
- Usage("Missing required compiler option for %s\n", option.c_str());
- return false;
- }
- compiler_options_.push_back(options[i].first);
- } else if (option == "-Ximage-compiler-option") {
- i++;
- if (i == options.size()) {
- Usage("Missing required compiler option for %s\n", option.c_str());
- return false;
- }
- image_compiler_options_.push_back(options[i].first);
- } else if (StartsWith(option, "-Xverify:")) {
- std::string verify_mode = option.substr(strlen("-Xverify:"));
- if (verify_mode == "none") {
- verify_ = false;
- } else if (verify_mode == "remote" || verify_mode == "all") {
- verify_ = true;
- } else {
- Usage("Unknown -Xverify option %s\n", verify_mode.c_str());
- return false;
- }
- } else if (StartsWith(option, "-XX:NativeBridge=")) {
- if (!ParseStringAfterChar(option, '=', &native_bridge_library_filename_)) {
- return false;
- }
- } else if (StartsWith(option, "-ea") ||
- StartsWith(option, "-da") ||
- StartsWith(option, "-enableassertions") ||
- StartsWith(option, "-disableassertions") ||
- (option == "--runtime-arg") ||
- (option == "-esa") ||
- (option == "-dsa") ||
- (option == "-enablesystemassertions") ||
- (option == "-disablesystemassertions") ||
- (option == "-Xrs") ||
- StartsWith(option, "-Xint:") ||
- StartsWith(option, "-Xdexopt:") ||
- (option == "-Xnoquithandler") ||
- StartsWith(option, "-Xjnigreflimit:") ||
- (option == "-Xgenregmap") ||
- (option == "-Xnogenregmap") ||
- StartsWith(option, "-Xverifyopt:") ||
- (option == "-Xcheckdexsum") ||
- (option == "-Xincludeselectedop") ||
- StartsWith(option, "-Xjitop:") ||
- (option == "-Xincludeselectedmethod") ||
- StartsWith(option, "-Xjitthreshold:") ||
- StartsWith(option, "-Xjitcodecachesize:") ||
- (option == "-Xjitblocking") ||
- StartsWith(option, "-Xjitmethod:") ||
- StartsWith(option, "-Xjitclass:") ||
- StartsWith(option, "-Xjitoffset:") ||
- StartsWith(option, "-Xjitconfig:") ||
- (option == "-Xjitcheckcg") ||
- (option == "-Xjitverbose") ||
- (option == "-Xjitprofile") ||
- (option == "-Xjitdisableopt") ||
- (option == "-Xjitsuspendpoll") ||
- StartsWith(option, "-XX:mainThreadStackSize=")) {
- // Ignored for backwards compatibility.
- } else if (!ignore_unrecognized) {
- Usage("Unrecognized option %s\n", option.c_str());
+ } else if (parse_result.GetStatus() == CmdlineResult::kUnknown && !ignore_unrecognized) {
+ Usage("%s\n", parse_result.GetMessage().c_str());
return false;
+ } else {
+ Usage("%s\n", parse_result.GetMessage().c_str());
+ Exit(0);
+ }
+
+ UNREACHABLE();
+ return false;
+ }
+
+ using M = RuntimeArgumentMap;
+ RuntimeArgumentMap args = parser->ReleaseArgumentsMap();
+
+ // -help, -showversion, etc.
+ if (args.Exists(M::Help)) {
+ Usage(nullptr);
+ return false;
+ } else if (args.Exists(M::ShowVersion)) {
+ UsageMessage(stdout, "ART version %s\n", Runtime::GetVersion());
+ Exit(0);
+ } else if (args.Exists(M::BootClassPath)) {
+ LOG(INFO) << "setting boot class path to " << *args.Get(M::BootClassPath);
+ }
+
+ // Set a default boot class path if we didn't get an explicit one via command line.
+ if (getenv("BOOTCLASSPATH") != nullptr) {
+ args.SetIfMissing(M::BootClassPath, std::string(getenv("BOOTCLASSPATH")));
+ }
+
+ // Set a default class path if we didn't get an explicit one via command line.
+ if (getenv("CLASSPATH") != nullptr) {
+ args.SetIfMissing(M::ClassPath, std::string(getenv("CLASSPATH")));
+ }
+
+ // Default to number of processors minus one since the main GC thread also does work.
+ args.SetIfMissing(M::ParallelGCThreads,
+ static_cast<unsigned int>(sysconf(_SC_NPROCESSORS_CONF) - 1u));
+
+ // -Xverbose:
+ {
+ LogVerbosity *log_verbosity = args.Get(M::Verbose);
+ if (log_verbosity != nullptr) {
+ gLogVerbosity = *log_verbosity;
}
}
- // If not set, background collector type defaults to homogeneous compaction.
- // If foreground is GSS, use GSS as background collector.
- // If not low memory mode, semispace otherwise.
- if (background_collector_type_ == gc::kCollectorTypeNone) {
- if (collector_type_ != gc::kCollectorTypeGSS) {
- background_collector_type_ = low_memory_mode_ ?
- gc::kCollectorTypeSS : gc::kCollectorTypeHomogeneousSpaceCompact;
- } else {
- background_collector_type_ = collector_type_;
+
+ // -Xprofile:
+ Trace::SetDefaultClockSource(args.GetOrDefault(M::ProfileClock));
+
+ if (!ProcessSpecialOptions(options, &args, nullptr)) {
+ return false;
+ }
+
+ {
+ // If not set, background collector type defaults to homogeneous compaction.
+ // If foreground is GSS, use GSS as background collector.
+ // If not low memory mode, semispace otherwise.
+
+ gc::CollectorType background_collector_type_;
+ gc::CollectorType collector_type_ = (XGcOption{}).collector_type_; // NOLINT [whitespace/braces] [5]
+ bool low_memory_mode_ = args.Exists(M::LowMemoryMode);
+
+ background_collector_type_ = args.GetOrDefault(M::BackgroundGc);
+ {
+ XGcOption* xgc = args.Get(M::GcOption);
+ if (xgc != nullptr && xgc->collector_type_ != gc::kCollectorTypeNone) {
+ collector_type_ = xgc->collector_type_;
+ }
+ }
+
+ if (background_collector_type_ == gc::kCollectorTypeNone) {
+ if (collector_type_ != gc::kCollectorTypeGSS) {
+ background_collector_type_ = low_memory_mode_ ?
+ gc::kCollectorTypeSS : gc::kCollectorTypeHomogeneousSpaceCompact;
+ } else {
+ background_collector_type_ = collector_type_;
+ }
+ }
+
+ args.Set(M::BackgroundGc, BackgroundGcOption { background_collector_type_ });
+ {
+ XGcOption* xgc = args.Get(M::GcOption);
+ if (xgc != nullptr) {
+ xgc->collector_type_ = collector_type_;
+ args.Set(M::GcOption, *xgc);
+ }
}
}
@@ -723,38 +485,45 @@
std::string core_jar("/core-hostdex.jar");
std::string core_libart_jar("/core-libart-hostdex.jar");
#endif
- size_t core_jar_pos = boot_class_path_string_.find(core_jar);
+ auto boot_class_path_string = args.GetOrDefault(M::BootClassPath);
+
+ size_t core_jar_pos = boot_class_path_string.find(core_jar);
if (core_jar_pos != std::string::npos) {
- boot_class_path_string_.replace(core_jar_pos, core_jar.size(), core_libart_jar);
+ boot_class_path_string.replace(core_jar_pos, core_jar.size(), core_libart_jar);
+ args.Set(M::BootClassPath, boot_class_path_string);
}
- if (!boot_class_path_locations_string_.empty()) {
- std::vector<std::string> files;
- Split(boot_class_path_string_, ':', &files);
+ {
+ auto&& boot_class_path = args.GetOrDefault(M::BootClassPath);
+ auto&& boot_class_path_locations = args.GetOrDefault(M::BootClassPathLocations);
+ if (args.Exists(M::BootClassPathLocations)) {
+ size_t boot_class_path_count = ParseStringList<':'>::Split(boot_class_path).Size();
- std::vector<std::string> locations;
- Split(boot_class_path_locations_string_, ':', &locations);
-
- if (files.size() != locations.size()) {
- Usage("The number of boot class path files does not match"
- " the number of boot class path locations given\n"
- " boot class path files (%zu): %s\n"
- " boot class path locations (%zu): %s\n",
- files.size(), boot_class_path_string_.c_str(),
- locations.size(), boot_class_path_locations_string_.c_str());
- return false;
+ if (boot_class_path_count != boot_class_path_locations.Size()) {
+ Usage("The number of boot class path files does not match"
+ " the number of boot class path locations given\n"
+ " boot class path files (%zu): %s\n"
+ " boot class path locations (%zu): %s\n",
+ boot_class_path.size(), boot_class_path_string.c_str(),
+ boot_class_path_locations.Size(), boot_class_path_locations.Join().c_str());
+ return false;
+ }
}
}
- if (compiler_callbacks_ == nullptr && image_.empty()) {
- image_ += GetAndroidRoot();
- image_ += "/framework/boot.art";
+ if (!args.Exists(M::CompilerCallbacksPtr) && !args.Exists(M::Image)) {
+ std::string image = GetAndroidRoot();
+ image += "/framework/boot.art";
+ args.Set(M::Image, image);
}
- if (heap_growth_limit_ == 0) {
- heap_growth_limit_ = heap_maximum_size_;
+
+ if (args.GetOrDefault(M::HeapGrowthLimit) == 0u) { // 0 means no growth limit
+ args.Set(M::HeapGrowthLimit, args.GetOrDefault(M::MemoryMaximumSize));
}
+
+ *runtime_options = std::move(args);
return true;
-} // NOLINT(readability/fn_size)
+}
void ParsedOptions::Exit(int status) {
hook_exit_(status);
@@ -831,7 +600,7 @@
UsageMessage(stream, " -Xgc:[no]presweepingverify\n");
UsageMessage(stream, " -Ximage:filename\n");
UsageMessage(stream, " -Xbootclasspath-locations:bootclasspath\n"
- " (override the dex locations of the -Xbootclasspath files)\n");
+ " (override the dex locations of the -Xbootclasspath files)\n");
UsageMessage(stream, " -XX:+DisableExplicitGC\n");
UsageMessage(stream, " -XX:ParallelGCThreads=integervalue\n");
UsageMessage(stream, " -XX:ConcGCThreads=integervalue\n");
@@ -907,73 +676,4 @@
Exit((error) ? 1 : 0);
}
-bool ParsedOptions::ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
- std::string::size_type colon = s.find(c);
- if (colon == std::string::npos) {
- Usage("Missing char %c in option %s\n", c, s.c_str());
- return false;
- }
- // Add one to remove the char we were trimming until.
- *parsed_value = s.substr(colon + 1);
- return true;
-}
-
-bool ParsedOptions::ParseInteger(const std::string& s, char after_char, int* parsed_value) {
- std::string::size_type colon = s.find(after_char);
- if (colon == std::string::npos) {
- Usage("Missing char %c in option %s\n", after_char, s.c_str());
- return false;
- }
- const char* begin = &s[colon + 1];
- char* end;
- size_t result = strtoul(begin, &end, 10);
- if (begin == end || *end != '\0') {
- Usage("Failed to parse integer from %s\n", s.c_str());
- return false;
- }
- *parsed_value = result;
- return true;
-}
-
-bool ParsedOptions::ParseUnsignedInteger(const std::string& s, char after_char,
- unsigned int* parsed_value) {
- int i;
- if (!ParseInteger(s, after_char, &i)) {
- return false;
- }
- if (i < 0) {
- Usage("Negative value %d passed for unsigned option %s\n", i, s.c_str());
- return false;
- }
- *parsed_value = i;
- return true;
-}
-
-bool ParsedOptions::ParseDouble(const std::string& option, char after_char,
- double min, double max, double* parsed_value) {
- std::string substring;
- if (!ParseStringAfterChar(option, after_char, &substring)) {
- return false;
- }
- bool sane_val = true;
- double value;
- if ((false)) {
- // TODO: this doesn't seem to work on the emulator. b/15114595
- std::stringstream iss(substring);
- iss >> value;
- // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
- sane_val = iss.eof() && (value >= min) && (value <= max);
- } else {
- char* end = nullptr;
- value = strtod(substring.c_str(), &end);
- sane_val = *end == '\0' && value >= min && value <= max;
- }
- if (!sane_val) {
- Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
- return false;
- }
- *parsed_value = value;
- return true;
-}
-
} // namespace art
diff --git a/runtime/parsed_options.h b/runtime/parsed_options.h
index c7162b8..529dd5c 100644
--- a/runtime/parsed_options.h
+++ b/runtime/parsed_options.h
@@ -27,92 +27,44 @@
#include "gc/space/large_object_space.h"
#include "arch/instruction_set.h"
#include "profiler_options.h"
+#include "runtime_options.h"
namespace art {
class CompilerCallbacks;
class DexFile;
+struct RuntimeArgumentMap;
typedef std::vector<std::pair<std::string, const void*>> RuntimeOptions;
+template <typename TVariantMap,
+ template <typename TKeyValue> class TVariantMapKey>
+struct CmdlineParser;
+
class ParsedOptions {
public:
- // returns null if problem parsing and ignore_unrecognized is false
- static ParsedOptions* Create(const RuntimeOptions& options, bool ignore_unrecognized);
+ using RuntimeParser = CmdlineParser<RuntimeArgumentMap, RuntimeArgumentMap::Key>;
+ // Create a parser that can turn user-defined input into a RuntimeArgumentMap.
+ // This visibility is effectively for testing-only, and normal code does not
+ // need to create its own parser.
+ static std::unique_ptr<RuntimeParser> MakeParser(bool ignore_unrecognized);
- std::string boot_class_path_string_;
- std::string boot_class_path_locations_string_;
- std::string class_path_string_;
- std::string image_;
- bool check_jni_;
- bool force_copy_;
- std::string jni_trace_;
- std::string native_bridge_library_filename_;
- CompilerCallbacks* compiler_callbacks_;
- bool is_zygote_;
- bool must_relocate_;
- bool dex2oat_enabled_;
- bool image_dex2oat_enabled_;
- std::string patchoat_executable_;
- bool interpreter_only_;
- bool is_explicit_gc_disabled_;
- bool use_tlab_;
- bool verify_pre_gc_heap_;
- bool verify_pre_sweeping_heap_;
- bool verify_post_gc_heap_;
- bool verify_pre_gc_rosalloc_;
- bool verify_pre_sweeping_rosalloc_;
- bool verify_post_gc_rosalloc_;
- unsigned int long_pause_log_threshold_;
- unsigned int long_gc_log_threshold_;
- bool dump_gc_performance_on_shutdown_;
- bool ignore_max_footprint_;
- size_t heap_initial_size_;
- size_t heap_maximum_size_;
- size_t heap_growth_limit_;
- size_t heap_min_free_;
- size_t heap_max_free_;
- size_t heap_non_moving_space_capacity_;
- gc::space::LargeObjectSpaceType large_object_space_type_;
- size_t large_object_threshold_;
- double heap_target_utilization_;
- double foreground_heap_growth_multiplier_;
- unsigned int parallel_gc_threads_;
- unsigned int conc_gc_threads_;
- gc::CollectorType collector_type_;
- gc::CollectorType background_collector_type_;
- size_t stack_size_;
- unsigned int max_spins_before_thin_lock_inflation_;
- bool low_memory_mode_;
- unsigned int lock_profiling_threshold_;
- std::string stack_trace_file_;
- bool method_trace_;
- std::string method_trace_file_;
- unsigned int method_trace_file_size_;
+ // returns true if parsing succeeds, and stores the resulting options into runtime_options
+ static ParsedOptions* Create(const RuntimeOptions& options, bool ignore_unrecognized,
+ RuntimeArgumentMap* runtime_options);
+
bool (*hook_is_sensitive_thread_)();
jint (*hook_vfprintf_)(FILE* stream, const char* format, va_list ap);
void (*hook_exit_)(jint status);
void (*hook_abort_)();
- std::vector<std::string> properties_;
- std::string compiler_executable_;
- std::vector<std::string> compiler_options_;
- std::vector<std::string> image_compiler_options_;
- ProfilerOptions profiler_options_;
- std::string profile_output_filename_;
- TraceClockSource profile_clock_source_;
- bool verify_;
- InstructionSet image_isa_;
-
- // Whether or not we use homogeneous space compaction to avoid OOM errors. If enabled,
- // the heap will attempt to create an extra space which enables compacting from a malloc space to
- // another malloc space when we are about to throw OOM.
- bool use_homogeneous_space_compaction_for_oom_;
- // Minimal interval allowed between two homogeneous space compactions caused by OOM.
- uint64_t min_interval_homogeneous_space_compaction_by_oom_;
private:
ParsedOptions();
+ bool ProcessSpecialOptions(const RuntimeOptions& options,
+ RuntimeArgumentMap* runtime_options,
+ std::vector<std::string>* out_options);
+
void Usage(const char* fmt, ...);
void UsageMessage(FILE* stream, const char* fmt, ...);
void UsageMessageV(FILE* stream, const char* fmt, va_list ap);
@@ -120,13 +72,8 @@
void Exit(int status);
void Abort();
- bool Parse(const RuntimeOptions& options, bool ignore_unrecognized);
- bool ParseXGcOption(const std::string& option);
- bool ParseStringAfterChar(const std::string& option, char after_char, std::string* parsed_value);
- bool ParseInteger(const std::string& option, char after_char, int* parsed_value);
- bool ParseUnsignedInteger(const std::string& option, char after_char, unsigned int* parsed_value);
- bool ParseDouble(const std::string& option, char after_char, double min, double max,
- double* parsed_value);
+ bool Parse(const RuntimeOptions& options, bool ignore_unrecognized,
+ RuntimeArgumentMap* runtime_options);
};
} // namespace art
diff --git a/runtime/parsed_options_test.cc b/runtime/parsed_options_test.cc
index 61481b1..f68b632 100644
--- a/runtime/parsed_options_test.cc
+++ b/runtime/parsed_options_test.cc
@@ -22,7 +22,7 @@
namespace art {
-class ParsedOptionsTest : public CommonRuntimeTest {};
+class ParsedOptionsTest : public ::testing::Test {};
TEST_F(ParsedOptionsTest, ParsedOptions) {
void* test_vfprintf = reinterpret_cast<void*>(0xa);
@@ -30,7 +30,7 @@
void* test_exit = reinterpret_cast<void*>(0xc);
void* null = reinterpret_cast<void*>(NULL);
- std::string lib_core(GetLibCoreDexFileName());
+ std::string lib_core(CommonRuntimeTest::GetLibCoreDexFileName());
std::string boot_class_path;
boot_class_path += "-Xbootclasspath:";
@@ -54,20 +54,28 @@
options.push_back(std::make_pair("vfprintf", test_vfprintf));
options.push_back(std::make_pair("abort", test_abort));
options.push_back(std::make_pair("exit", test_exit));
- std::unique_ptr<ParsedOptions> parsed(ParsedOptions::Create(options, false));
- ASSERT_TRUE(parsed.get() != NULL);
- EXPECT_EQ(lib_core, parsed->boot_class_path_string_);
- EXPECT_EQ(lib_core, parsed->class_path_string_);
- EXPECT_EQ(std::string("boot_image"), parsed->image_);
- EXPECT_EQ(true, parsed->check_jni_);
- EXPECT_EQ(2048U, parsed->heap_initial_size_);
- EXPECT_EQ(4 * KB, parsed->heap_maximum_size_);
- EXPECT_EQ(1 * MB, parsed->stack_size_);
- EXPECT_DOUBLE_EQ(0.75, parsed->heap_target_utilization_);
- EXPECT_TRUE(test_vfprintf == parsed->hook_vfprintf_);
- EXPECT_TRUE(test_exit == parsed->hook_exit_);
- EXPECT_TRUE(test_abort == parsed->hook_abort_);
+ RuntimeArgumentMap map;
+ std::unique_ptr<ParsedOptions> parsed(ParsedOptions::Create(options, false, &map));
+ ASSERT_TRUE(parsed.get() != NULL);
+ ASSERT_NE(0u, map.Size());
+
+ using Opt = RuntimeArgumentMap;
+
+#define EXPECT_PARSED_EQ(expected, actual_key) EXPECT_EQ(expected, map.GetOrDefault(actual_key))
+#define EXPECT_PARSED_EXISTS(actual_key) EXPECT_TRUE(map.Exists(actual_key))
+
+ EXPECT_PARSED_EQ(lib_core, Opt::BootClassPath);
+ EXPECT_PARSED_EQ(lib_core, Opt::ClassPath);
+ EXPECT_PARSED_EQ(std::string("boot_image"), Opt::Image);
+ EXPECT_PARSED_EXISTS(Opt::CheckJni);
+ EXPECT_PARSED_EQ(2048U, Opt::MemoryInitialSize);
+ EXPECT_PARSED_EQ(4 * KB, Opt::MemoryMaximumSize);
+ EXPECT_PARSED_EQ(1 * MB, Opt::StackSize);
+ EXPECT_DOUBLE_EQ(0.75, map.GetOrDefault(Opt::HeapTargetUtilization));
+ EXPECT_TRUE(test_vfprintf == map.GetOrDefault(Opt::HookVfprintf));
+ EXPECT_TRUE(test_exit == map.GetOrDefault(Opt::HookExit));
+ EXPECT_TRUE(test_abort == map.GetOrDefault(Opt::HookAbort));
EXPECT_TRUE(VLOG_IS_ON(class_linker));
EXPECT_FALSE(VLOG_IS_ON(compiler));
EXPECT_FALSE(VLOG_IS_ON(heap));
@@ -78,9 +86,11 @@
EXPECT_FALSE(VLOG_IS_ON(startup));
EXPECT_FALSE(VLOG_IS_ON(third_party_jni));
EXPECT_FALSE(VLOG_IS_ON(threads));
- ASSERT_EQ(2U, parsed->properties_.size());
- EXPECT_EQ("foo=bar", parsed->properties_[0]);
- EXPECT_EQ("baz=qux", parsed->properties_[1]);
+
+ auto&& properties_list = map.GetOrDefault(Opt::PropertiesList);
+ ASSERT_EQ(2U, properties_list.size());
+ EXPECT_EQ("foo=bar", properties_list[0]);
+ EXPECT_EQ("baz=qux", properties_list[1]);
}
} // namespace art
diff --git a/runtime/runtime.cc b/runtime/runtime.cc
index 3acac3a..4bb1741 100644
--- a/runtime/runtime.cc
+++ b/runtime/runtime.cc
@@ -29,7 +29,7 @@
#include <cstdio>
#include <cstdlib>
#include <limits>
-#include <memory>
+#include <memory_representation.h>
#include <vector>
#include <fcntl.h>
@@ -106,6 +106,8 @@
#include "profiler.h"
#include "quick/quick_method_frame_info.h"
#include "reflection.h"
+#include "runtime_options.h"
+#include "ScopedLocalRef.h"
#include "scoped_thread_state_change.h"
#include "sigchain.h"
#include "signal_catcher.h"
@@ -711,8 +713,11 @@
MemMap::Init();
- std::unique_ptr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized));
- if (options.get() == nullptr) {
+ using Opt = RuntimeArgumentMap;
+ RuntimeArgumentMap runtime_options;
+ std::unique_ptr<ParsedOptions> parsed_options(
+ ParsedOptions::Create(raw_options, ignore_unrecognized, &runtime_options));
+ if (parsed_options.get() == nullptr) {
LOG(ERROR) << "Failed to parse options";
return false;
}
@@ -720,76 +725,79 @@
QuasiAtomic::Startup();
- Monitor::Init(options->lock_profiling_threshold_, options->hook_is_sensitive_thread_);
+ Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold),
+ runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
- boot_class_path_string_ = options->boot_class_path_string_;
- class_path_string_ = options->class_path_string_;
- properties_ = options->properties_;
+ boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
+ class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
+ properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
- compiler_callbacks_ = options->compiler_callbacks_;
- patchoat_executable_ = options->patchoat_executable_;
- must_relocate_ = options->must_relocate_;
- is_zygote_ = options->is_zygote_;
- is_explicit_gc_disabled_ = options->is_explicit_gc_disabled_;
- dex2oat_enabled_ = options->dex2oat_enabled_;
- image_dex2oat_enabled_ = options->image_dex2oat_enabled_;
+ compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
+ patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat);
+ must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
+ is_zygote_ = runtime_options.Exists(Opt::Zygote);
+ is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
+ dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat);
+ image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
- vfprintf_ = options->hook_vfprintf_;
- exit_ = options->hook_exit_;
- abort_ = options->hook_abort_;
+ vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
+ exit_ = runtime_options.GetOrDefault(Opt::HookExit);
+ abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
- default_stack_size_ = options->stack_size_;
- stack_trace_file_ = options->stack_trace_file_;
+ default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
+ stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile);
- compiler_executable_ = options->compiler_executable_;
- compiler_options_ = options->compiler_options_;
- image_compiler_options_ = options->image_compiler_options_;
- image_location_ = options->image_;
+ compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
+ compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
+ image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
+ image_location_ = runtime_options.GetOrDefault(Opt::Image);
- max_spins_before_thin_lock_inflation_ = options->max_spins_before_thin_lock_inflation_;
+ max_spins_before_thin_lock_inflation_ =
+ runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
monitor_list_ = new MonitorList;
monitor_pool_ = MonitorPool::Create();
thread_list_ = new ThreadList;
intern_table_ = new InternTable;
- verify_ = options->verify_;
+ verify_ = runtime_options.GetOrDefault(Opt::Verify);
- if (options->interpreter_only_) {
+ if (runtime_options.Exists(Opt::Interpret)) {
GetInstrumentation()->ForceInterpretOnly();
}
- heap_ = new gc::Heap(options->heap_initial_size_,
- options->heap_growth_limit_,
- options->heap_min_free_,
- options->heap_max_free_,
- options->heap_target_utilization_,
- options->foreground_heap_growth_multiplier_,
- options->heap_maximum_size_,
- options->heap_non_moving_space_capacity_,
- options->image_,
- options->image_isa_,
- options->collector_type_,
- options->background_collector_type_,
- options->large_object_space_type_,
- options->large_object_threshold_,
- options->parallel_gc_threads_,
- options->conc_gc_threads_,
- options->low_memory_mode_,
- options->long_pause_log_threshold_,
- options->long_gc_log_threshold_,
- options->ignore_max_footprint_,
- options->use_tlab_,
- options->verify_pre_gc_heap_,
- options->verify_pre_sweeping_heap_,
- options->verify_post_gc_heap_,
- options->verify_pre_gc_rosalloc_,
- options->verify_pre_sweeping_rosalloc_,
- options->verify_post_gc_rosalloc_,
- options->use_homogeneous_space_compaction_for_oom_,
- options->min_interval_homogeneous_space_compaction_by_oom_);
+ XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
+ heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
+ runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
+ runtime_options.GetOrDefault(Opt::HeapMinFree),
+ runtime_options.GetOrDefault(Opt::HeapMaxFree),
+ runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
+ runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier),
+ runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
+ runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
+ runtime_options.GetOrDefault(Opt::Image),
+ runtime_options.GetOrDefault(Opt::ImageInstructionSet),
+ xgc_option.collector_type_,
+ runtime_options.GetOrDefault(Opt::BackgroundGc),
+ runtime_options.GetOrDefault(Opt::LargeObjectSpace),
+ runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
+ runtime_options.GetOrDefault(Opt::ParallelGCThreads),
+ runtime_options.GetOrDefault(Opt::ConcGCThreads),
+ runtime_options.Exists(Opt::LowMemoryMode),
+ runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
+ runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
+ runtime_options.Exists(Opt::IgnoreMaxFootprint),
+ runtime_options.Exists(Opt::UseTLAB),
+ xgc_option.verify_pre_gc_heap_,
+ xgc_option.verify_pre_sweeping_heap_,
+ xgc_option.verify_post_gc_heap_,
+ xgc_option.verify_pre_gc_rosalloc_,
+ xgc_option.verify_pre_sweeping_rosalloc_,
+ xgc_option.verify_post_gc_rosalloc_,
+ runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
+ runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs));
- dump_gc_performance_on_shutdown_ = options->dump_gc_performance_on_shutdown_;
+ dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
BlockSignals();
InitPlatformSignalHandlers();
@@ -840,7 +848,7 @@
}
}
- java_vm_ = new JavaVMExt(this, options.get());
+ java_vm_ = new JavaVMExt(this, runtime_options);
Thread::Startup();
@@ -879,16 +887,20 @@
Split(boot_class_path_string_, ':', &dex_filenames);
std::vector<std::string> dex_locations;
- if (options->boot_class_path_locations_string_.empty()) {
+ if (!runtime_options.Exists(Opt::BootClassPathLocations)) {
dex_locations = dex_filenames;
} else {
- Split(options->boot_class_path_locations_string_, ':', &dex_locations);
+ dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations);
CHECK_EQ(dex_filenames.size(), dex_locations.size());
}
std::vector<std::unique_ptr<const DexFile>> boot_class_path;
- OpenDexFiles(dex_filenames, dex_locations, options->image_, &boot_class_path);
+ OpenDexFiles(dex_filenames,
+ dex_locations,
+ runtime_options.GetOrDefault(Opt::Image),
+ &boot_class_path);
class_linker_->InitWithoutImage(std::move(boot_class_path));
+
// TODO: Should we move the following to InitWithoutImage?
SetInstructionSet(kRuntimeISA);
for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
@@ -907,20 +919,42 @@
verifier::MethodVerifier::Init();
- method_trace_ = options->method_trace_;
- method_trace_file_ = options->method_trace_file_;
- method_trace_file_size_ = options->method_trace_file_size_;
+ method_trace_ = runtime_options.Exists(Opt::MethodTrace);
+ method_trace_file_ = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
+ method_trace_file_size_ = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
- profile_output_filename_ = options->profile_output_filename_;
- profiler_options_ = options->profiler_options_;
+ {
+ auto&& profiler_options = runtime_options.ReleaseOrDefault(Opt::ProfilerOpts);
+ profile_output_filename_ = profiler_options.output_file_name_;
+
+ // TODO: Don't do this, just change ProfilerOptions to include the output file name?
+ ProfilerOptions other_options(
+ profiler_options.enabled_,
+ profiler_options.period_s_,
+ profiler_options.duration_s_,
+ profiler_options.interval_us_,
+ profiler_options.backoff_coefficient_,
+ profiler_options.start_immediately_,
+ profiler_options.top_k_threshold_,
+ profiler_options.top_k_change_threshold_,
+ profiler_options.profile_type_,
+ profiler_options.max_stack_depth_);
+
+ profiler_options_ = other_options;
+ }
// TODO: move this to just be an Trace::Start argument
- Trace::SetDefaultClockSource(options->profile_clock_source_);
+ Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
- if (options->method_trace_) {
+ if (method_trace_) {
ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
- Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0,
- false, false, 0);
+ Trace::Start(method_trace_file_.c_str(),
+ -1,
+ static_cast<int>(method_trace_file_size_),
+ 0,
+ false,
+ false,
+ 0);
}
// Pre-allocate an OutOfMemoryError for the double-OOME case.
@@ -964,7 +998,10 @@
// Runtime::Start():
// DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
// No-op wrt native bridge.
- is_native_bridge_loaded_ = LoadNativeBridge(options->native_bridge_library_filename_);
+ {
+ std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
+ is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
+ }
VLOG(startup) << "Runtime::Init exiting";
return true;
diff --git a/runtime/runtime_options.cc b/runtime/runtime_options.cc
new file mode 100644
index 0000000..c54461e
--- /dev/null
+++ b/runtime/runtime_options.cc
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "runtime_options.h"
+
+#include "gc/heap.h"
+#include "monitor.h"
+#include "runtime.h"
+#include "trace.h"
+#include "utils.h"
+#include "debugger.h"
+
+namespace art {
+
+// Specify storage for the RuntimeOptions keys.
+
+#define RUNTIME_OPTIONS_KEY(Type, Name, ...) const RuntimeArgumentMap::Key<Type> RuntimeArgumentMap::Name {__VA_ARGS__}; // NOLINT [readability/braces] [4]
+#include "runtime_options.def"
+
+} // namespace art
diff --git a/runtime/runtime_options.def b/runtime/runtime_options.def
new file mode 100644
index 0000000..022a2a5
--- /dev/null
+++ b/runtime/runtime_options.def
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RUNTIME_OPTIONS_KEY
+#error "Please #define RUNTIME_OPTIONS_KEY before #including this file"
+#define RUNTIME_OPTIONS_KEY(...) // Don't display errors in this file in IDEs.
+#endif
+
+// This file defines the list of keys for RuntimeOptions.
+// These can be used with RuntimeOptions.Get/Set/etc, for example:
+// RuntimeOptions opt; bool* dex2oat_enabled = opt.Get(RuntimeOptions::Dex2Oat);
+//
+// Column Descriptions:
+// <<Type>> <<Key Name>> <<Default Value>>
+//
+// Default values are only used by Map::GetOrDefault(K<T>).
+// If a default value is omitted here, T{} is used as the default value, which is
+// almost-always the value of the type as if it was memset to all 0.
+//
+
+// Parse-able keys from the command line.
+RUNTIME_OPTIONS_KEY (Unit, Zygote)
+RUNTIME_OPTIONS_KEY (Unit, Help)
+RUNTIME_OPTIONS_KEY (Unit, ShowVersion)
+RUNTIME_OPTIONS_KEY (std::string, BootClassPath)
+RUNTIME_OPTIONS_KEY (ParseStringList<':'>,BootClassPathLocations) // std::vector<std::string>
+RUNTIME_OPTIONS_KEY (std::string, ClassPath)
+RUNTIME_OPTIONS_KEY (std::string, Image)
+RUNTIME_OPTIONS_KEY (Unit, CheckJni)
+RUNTIME_OPTIONS_KEY (Unit, JniOptsForceCopy)
+RUNTIME_OPTIONS_KEY (JDWP::JdwpOptions, JdwpOptions)
+RUNTIME_OPTIONS_KEY (MemoryKiB, MemoryMaximumSize, gc::Heap::kDefaultMaximumSize) // -Xmx
+RUNTIME_OPTIONS_KEY (MemoryKiB, MemoryInitialSize, gc::Heap::kDefaultInitialSize) // -Xms
+RUNTIME_OPTIONS_KEY (MemoryKiB, HeapGrowthLimit) // Default is 0 for unlimited
+RUNTIME_OPTIONS_KEY (MemoryKiB, HeapMinFree, gc::Heap::kDefaultMinFree)
+RUNTIME_OPTIONS_KEY (MemoryKiB, HeapMaxFree, gc::Heap::kDefaultMaxFree)
+RUNTIME_OPTIONS_KEY (MemoryKiB, NonMovingSpaceCapacity, gc::Heap::kDefaultNonMovingSpaceCapacity)
+RUNTIME_OPTIONS_KEY (double, HeapTargetUtilization, gc::Heap::kDefaultTargetUtilization)
+RUNTIME_OPTIONS_KEY (double, ForegroundHeapGrowthMultiplier, gc::Heap::kDefaultHeapGrowthMultiplier)
+RUNTIME_OPTIONS_KEY (unsigned int, ParallelGCThreads, 1u)
+RUNTIME_OPTIONS_KEY (unsigned int, ConcGCThreads)
+RUNTIME_OPTIONS_KEY (Memory<1>, StackSize) // -Xss
+RUNTIME_OPTIONS_KEY (unsigned int, MaxSpinsBeforeThinLockInflation,Monitor::kDefaultMaxSpinsBeforeThinLockInflation)
+RUNTIME_OPTIONS_KEY (MillisecondsToNanoseconds, \
+ LongPauseLogThreshold, gc::Heap::kDefaultLongPauseLogThreshold)
+RUNTIME_OPTIONS_KEY (MillisecondsToNanoseconds, \
+ LongGCLogThreshold, gc::Heap::kDefaultLongGCLogThreshold)
+RUNTIME_OPTIONS_KEY (Unit, DumpGCPerformanceOnShutdown)
+RUNTIME_OPTIONS_KEY (Unit, IgnoreMaxFootprint)
+RUNTIME_OPTIONS_KEY (Unit, LowMemoryMode)
+RUNTIME_OPTIONS_KEY (Unit, UseTLAB)
+RUNTIME_OPTIONS_KEY (bool, EnableHSpaceCompactForOOM, true)
+RUNTIME_OPTIONS_KEY (MillisecondsToNanoseconds, \
+ HSpaceCompactForOOMMinIntervalsMs,\
+ MsToNs(100 * 1000)) // 100s
+RUNTIME_OPTIONS_KEY (std::vector<std::string>, \
+ PropertiesList) // -D<whatever> -D<whatever> ...
+RUNTIME_OPTIONS_KEY (std::string, JniTrace)
+RUNTIME_OPTIONS_KEY (std::string, PatchOat)
+RUNTIME_OPTIONS_KEY (bool, Relocate, kDefaultMustRelocate)
+RUNTIME_OPTIONS_KEY (bool, Dex2Oat, true)
+RUNTIME_OPTIONS_KEY (bool, ImageDex2Oat, true)
+ // kPoisonHeapReferences currently works with
+ // the interpreter only.
+ // TODO: make it work with the compiler.
+RUNTIME_OPTIONS_KEY (bool, Interpret, (kPoisonHeapReferences || kUseReadBarrier)) // -Xint
+ // Disable the compiler for CC (for now).
+RUNTIME_OPTIONS_KEY (XGcOption, GcOption) // -Xgc:
+RUNTIME_OPTIONS_KEY (gc::space::LargeObjectSpaceType, \
+ LargeObjectSpace, gc::Heap::kDefaultLargeObjectSpaceType)
+RUNTIME_OPTIONS_KEY (Memory<1>, LargeObjectThreshold, gc::Heap::kDefaultLargeObjectThreshold)
+RUNTIME_OPTIONS_KEY (BackgroundGcOption, BackgroundGc)
+
+RUNTIME_OPTIONS_KEY (Unit, DisableExplicitGC)
+RUNTIME_OPTIONS_KEY (LogVerbosity, Verbose)
+RUNTIME_OPTIONS_KEY (unsigned int, LockProfThreshold)
+RUNTIME_OPTIONS_KEY (std::string, StackTraceFile)
+RUNTIME_OPTIONS_KEY (Unit, MethodTrace)
+RUNTIME_OPTIONS_KEY (std::string, MethodTraceFile, "/data/method-trace-file.bin")
+RUNTIME_OPTIONS_KEY (unsigned int, MethodTraceFileSize, 10 * MB)
+RUNTIME_OPTIONS_KEY (TraceClockSource, ProfileClock, kDefaultTraceClockSource) // -Xprofile:
+RUNTIME_OPTIONS_KEY (TestProfilerOptions, ProfilerOpts) // -Xenable-profiler, -Xprofile-*
+RUNTIME_OPTIONS_KEY (std::string, Compiler)
+RUNTIME_OPTIONS_KEY (std::vector<std::string>, \
+ CompilerOptions) // -Xcompiler-option ...
+RUNTIME_OPTIONS_KEY (std::vector<std::string>, \
+ ImageCompilerOptions) // -Ximage-compiler-option ...
+RUNTIME_OPTIONS_KEY (bool, Verify, true)
+RUNTIME_OPTIONS_KEY (std::string, NativeBridge)
+
+// Not parse-able from command line, but can be provided explicitly.
+RUNTIME_OPTIONS_KEY (const std::vector<const DexFile*>*, \
+ BootClassPathDexList) // TODO: make unique_ptr
+RUNTIME_OPTIONS_KEY (InstructionSet, ImageInstructionSet, kRuntimeISA)
+RUNTIME_OPTIONS_KEY (CompilerCallbacks*, CompilerCallbacksPtr) // TDOO: make unique_ptr
+RUNTIME_OPTIONS_KEY (bool (*)(), HookIsSensitiveThread)
+RUNTIME_OPTIONS_KEY (int32_t (*)(FILE* stream, const char* format, va_list ap), \
+ HookVfprintf, vfprintf)
+RUNTIME_OPTIONS_KEY (void (*)(int32_t status), \
+ HookExit, exit)
+ // We don't call abort(3) by default; see
+ // Runtime::Abort.
+RUNTIME_OPTIONS_KEY (void (*)(), HookAbort, nullptr)
+
+
+#undef RUNTIME_OPTIONS_KEY
diff --git a/runtime/runtime_options.h b/runtime/runtime_options.h
new file mode 100644
index 0000000..ebd52d7
--- /dev/null
+++ b/runtime/runtime_options.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ART_RUNTIME_RUNTIME_OPTIONS_H_
+#define ART_RUNTIME_RUNTIME_OPTIONS_H_
+
+#include "runtime/base/variant_map.h"
+#include "cmdline/cmdline_types.h" // TODO: don't need to include this file here
+
+// Map keys
+#include <vector>
+#include <string>
+#include "runtime/base/logging.h"
+#include "cmdline/unit.h"
+#include "jdwp/jdwp.h"
+#include "gc/collector_type.h"
+#include "gc/space/large_object_space.h"
+#include "profiler_options.h"
+#include "arch/instruction_set.h"
+#include <stdio.h>
+#include <stdarg.h>
+
+namespace art {
+
+class CompilerCallbacks;
+class DexFile;
+struct XGcOption;
+struct BackgroundGcOption;
+struct TestProfilerOptions;
+
+#define DECLARE_KEY(Type, Name) static const Key<Type> Name
+
+ // Define a key that is usable with a RuntimeArgumentMap.
+ // This key will *not* work with other subtypes of VariantMap.
+ template <typename TValue>
+ struct RuntimeArgumentMapKey : VariantMapKey<TValue> {
+ RuntimeArgumentMapKey() {}
+ explicit RuntimeArgumentMapKey(TValue default_value)
+ : VariantMapKey<TValue>(std::move(default_value)) {}
+ // Don't ODR-use constexpr default values, which means that Struct::Fields
+ // that are declared 'static constexpr T Name = Value' don't need to have a matching definition.
+ };
+
+ // Defines a type-safe heterogeneous key->value map.
+ // Use the VariantMap interface to look up or to store a RuntimeArgumentMapKey,Value pair.
+ //
+ // Example:
+ // auto map = RuntimeArgumentMap();
+ // map.Set(RuntimeArgumentMap::HeapTargetUtilization, 5.0);
+ // double *target_utilization = map.Get(RuntimeArgumentMap);
+ //
+ struct RuntimeArgumentMap : VariantMap<RuntimeArgumentMap, RuntimeArgumentMapKey> {
+ // This 'using' line is necessary to inherit the variadic constructor.
+ using VariantMap<RuntimeArgumentMap, RuntimeArgumentMapKey>::VariantMap;
+
+ // Make the next many usages of Key slightly shorter to type.
+ template <typename TValue>
+ using Key = RuntimeArgumentMapKey<TValue>;
+
+ // List of key declarations, shorthand for 'static const Key<T> Name'
+#define RUNTIME_OPTIONS_KEY(Type, Name, ...) static const Key<Type> Name;
+#include "runtime_options.def"
+ };
+
+#undef DECLARE_KEY
+
+ // using RuntimeOptions = RuntimeArgumentMap;
+} // namespace art
+
+#endif // ART_RUNTIME_RUNTIME_OPTIONS_H_
diff --git a/runtime/trace.cc b/runtime/trace.cc
index 5066e03..0950abeb 100644
--- a/runtime/trace.cc
+++ b/runtime/trace.cc
@@ -153,30 +153,30 @@
#if defined(__linux__)
default_clock_source_ = clock_source;
#else
- if (clock_source != kTraceClockSourceWall) {
+ if (clock_source != TraceClockSource::kWall) {
LOG(WARNING) << "Ignoring tracing request to use CPU time.";
}
#endif
}
static uint16_t GetTraceVersion(TraceClockSource clock_source) {
- return (clock_source == kTraceClockSourceDual) ? kTraceVersionDualClock
+ return (clock_source == TraceClockSource::kDual) ? kTraceVersionDualClock
: kTraceVersionSingleClock;
}
static uint16_t GetRecordSize(TraceClockSource clock_source) {
- return (clock_source == kTraceClockSourceDual) ? kTraceRecordSizeDualClock
+ return (clock_source == TraceClockSource::kDual) ? kTraceRecordSizeDualClock
: kTraceRecordSizeSingleClock;
}
bool Trace::UseThreadCpuClock() {
- return (clock_source_ == kTraceClockSourceThreadCpu) ||
- (clock_source_ == kTraceClockSourceDual);
+ return (clock_source_ == TraceClockSource::kThreadCpu) ||
+ (clock_source_ == TraceClockSource::kDual);
}
bool Trace::UseWallClock() {
- return (clock_source_ == kTraceClockSourceWall) ||
- (clock_source_ == kTraceClockSourceDual);
+ return (clock_source_ == TraceClockSource::kWall) ||
+ (clock_source_ == TraceClockSource::kDual);
}
void Trace::MeasureClockOverhead() {
diff --git a/runtime/utils.h b/runtime/utils.h
index b5413e7..1c2576c 100644
--- a/runtime/utils.h
+++ b/runtime/utils.h
@@ -549,6 +549,13 @@
template <typename T>
using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
+// C++14 from-the-future import (std::make_unique)
+// Invoke the constructor of 'T' with the provided args, and wrap the result in a unique ptr.
+template <typename T, typename ... Args>
+std::unique_ptr<T> MakeUnique(Args&& ... args) {
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
} // namespace art
#endif // ART_RUNTIME_UTILS_H_