2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "cmdline_parser.h"
18 #include "runtime/runtime_options.h"
19 #include "runtime/parsed_options.h"
23 #include "gtest/gtest.h"
24 #include "runtime/experimental_flags.h"
26 #define EXPECT_NULL(expected) EXPECT_EQ(reinterpret_cast<const void*>(expected), \
27 reinterpret_cast<void*>(nullptr));
30 bool UsuallyEquals(double expected, double actual);
32 // This has a gtest dependency, which is why it's in the gtest only.
33 bool operator==(const ProfileSaverOptions& lhs, const ProfileSaverOptions& rhs) {
34 return lhs.enabled_ == rhs.enabled_ &&
35 lhs.min_save_period_ms_ == rhs.min_save_period_ms_ &&
36 lhs.save_resolved_classes_delay_ms_ == rhs.save_resolved_classes_delay_ms_ &&
37 lhs.startup_method_samples_ == rhs.startup_method_samples_ &&
38 lhs.min_methods_to_save_ == rhs.min_methods_to_save_ &&
39 lhs.min_classes_to_save_ == rhs.min_classes_to_save_ &&
40 lhs.min_notification_before_wake_ == rhs.min_notification_before_wake_ &&
41 lhs.max_notification_before_wake_ == rhs.max_notification_before_wake_;
44 bool UsuallyEquals(double expected, double actual) {
45 using FloatingPoint = ::testing::internal::FloatingPoint<double>;
47 FloatingPoint exp(expected);
48 FloatingPoint act(actual);
50 // Compare with ULPs instead of comparing with ==
51 return exp.AlmostEquals(act);
55 bool UsuallyEquals(const T& expected, const T& actual,
56 typename std::enable_if<
57 detail::SupportsEqualityOperator<T>::value>::type* = 0) {
58 return expected == actual;
61 // Try to use memcmp to compare simple plain-old-data structs.
63 // This should *not* generate false positives, but it can generate false negatives.
64 // This will mostly work except for fields like float which can have different bit patterns
65 // that are nevertheless equal.
66 // If a test is failing because the structs aren't "equal" when they really are
67 // then it's recommended to implement operator== for it instead.
68 template <typename T, typename ... Ignore>
69 bool UsuallyEquals(const T& expected, const T& actual,
70 const Ignore& ... more ATTRIBUTE_UNUSED,
71 typename std::enable_if<std::is_pod<T>::value>::type* = 0,
72 typename std::enable_if<!detail::SupportsEqualityOperator<T>::value>::type* = 0
74 return memcmp(std::addressof(expected), std::addressof(actual), sizeof(T)) == 0;
77 bool UsuallyEquals(const XGcOption& expected, const XGcOption& actual) {
78 return memcmp(std::addressof(expected), std::addressof(actual), sizeof(expected)) == 0;
81 bool UsuallyEquals(const char* expected, const std::string& actual) {
82 return std::string(expected) == actual;
85 template <typename TMap, typename TKey, typename T>
86 ::testing::AssertionResult IsExpectedKeyValue(const T& expected,
89 auto* actual = map.Get(key);
90 if (actual != nullptr) {
91 if (!UsuallyEquals(expected, *actual)) {
92 return ::testing::AssertionFailure()
93 << "expected " << detail::ToStringAny(expected) << " but got "
94 << detail::ToStringAny(*actual);
96 return ::testing::AssertionSuccess();
99 return ::testing::AssertionFailure() << "key was not in the map";
102 template <typename TMap, typename TKey, typename T>
103 ::testing::AssertionResult IsExpectedDefaultKeyValue(const T& expected,
106 const T& actual = map.GetOrDefault(key);
107 if (!UsuallyEquals(expected, actual)) {
108 return ::testing::AssertionFailure()
109 << "expected " << detail::ToStringAny(expected) << " but got "
110 << detail::ToStringAny(actual);
112 return ::testing::AssertionSuccess();
115 class CmdlineParserTest : public ::testing::Test {
117 CmdlineParserTest() = default;
118 ~CmdlineParserTest() = default;
121 using M = RuntimeArgumentMap;
122 using RuntimeParser = ParsedOptions::RuntimeParser;
124 static void SetUpTestCase() {
125 art::InitLogging(nullptr, art::Runtime::Aborter); // argv = null
128 virtual void SetUp() {
129 parser_ = ParsedOptions::MakeParser(false); // do not ignore unrecognized options
132 static ::testing::AssertionResult IsResultSuccessful(const CmdlineResult& result) {
133 if (result.IsSuccess()) {
134 return ::testing::AssertionSuccess();
136 return ::testing::AssertionFailure()
137 << result.GetStatus() << " with: " << result.GetMessage();
141 static ::testing::AssertionResult IsResultFailure(const CmdlineResult& result,
142 CmdlineResult::Status failure_status) {
143 if (result.IsSuccess()) {
144 return ::testing::AssertionFailure() << " got success but expected failure: "
146 } else if (result.GetStatus() == failure_status) {
147 return ::testing::AssertionSuccess();
150 return ::testing::AssertionFailure() << " expected failure " << failure_status
151 << " but got " << result.GetStatus();
154 std::unique_ptr<RuntimeParser> parser_;
157 #define EXPECT_KEY_EXISTS(map, key) EXPECT_TRUE((map).Exists(key))
158 #define EXPECT_KEY_VALUE(map, key, expected) EXPECT_TRUE(IsExpectedKeyValue(expected, map, key))
159 #define EXPECT_DEFAULT_KEY_VALUE(map, key, expected) EXPECT_TRUE(IsExpectedDefaultKeyValue(expected, map, key))
161 #define _EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv) \
163 EXPECT_TRUE(IsResultSuccessful(parser_->Parse(argv))); \
164 EXPECT_EQ(0u, parser_->GetArgumentsMap().Size()); \
166 #define EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv) \
167 _EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv); \
170 #define EXPECT_SINGLE_PARSE_DEFAULT_VALUE(expected, argv, key)\
171 _EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv); \
172 RuntimeArgumentMap args = parser_->ReleaseArgumentsMap(); \
173 EXPECT_DEFAULT_KEY_VALUE(args, key, expected); \
174 } while (false) // NOLINT [readability/namespace] [5]
176 #define _EXPECT_SINGLE_PARSE_EXISTS(argv, key) \
178 EXPECT_TRUE(IsResultSuccessful(parser_->Parse(argv))); \
179 RuntimeArgumentMap args = parser_->ReleaseArgumentsMap(); \
180 EXPECT_EQ(1u, args.Size()); \
181 EXPECT_KEY_EXISTS(args, key); \
183 #define EXPECT_SINGLE_PARSE_EXISTS(argv, key) \
184 _EXPECT_SINGLE_PARSE_EXISTS(argv, key); \
187 #define EXPECT_SINGLE_PARSE_VALUE(expected, argv, key) \
188 _EXPECT_SINGLE_PARSE_EXISTS(argv, key); \
189 EXPECT_KEY_VALUE(args, key, expected); \
190 } while (false) // NOLINT [readability/namespace] [5]
192 #define EXPECT_SINGLE_PARSE_VALUE_STR(expected, argv, key) \
193 EXPECT_SINGLE_PARSE_VALUE(std::string(expected), argv, key)
195 #define EXPECT_SINGLE_PARSE_FAIL(argv, failure_status) \
197 EXPECT_TRUE(IsResultFailure(parser_->Parse(argv), failure_status));\
198 RuntimeArgumentMap args = parser_->ReleaseArgumentsMap();\
199 EXPECT_EQ(0u, args.Size()); \
202 TEST_F(CmdlineParserTest, TestSimpleSuccesses) {
203 auto& parser = *parser_;
205 EXPECT_LT(0u, parser.CountDefinedArguments());
208 // Test case 1: No command line arguments
209 EXPECT_TRUE(IsResultSuccessful(parser.Parse("")));
210 RuntimeArgumentMap args = parser.ReleaseArgumentsMap();
211 EXPECT_EQ(0u, args.Size());
214 EXPECT_SINGLE_PARSE_EXISTS("-Xzygote", M::Zygote);
215 EXPECT_SINGLE_PARSE_VALUE_STR("/hello/world", "-Xbootclasspath:/hello/world", M::BootClassPath);
216 EXPECT_SINGLE_PARSE_VALUE("/hello/world", "-Xbootclasspath:/hello/world", M::BootClassPath);
217 EXPECT_SINGLE_PARSE_VALUE(Memory<1>(234), "-Xss234", M::StackSize);
218 EXPECT_SINGLE_PARSE_VALUE(MemoryKiB(1234*MB), "-Xms1234m", M::MemoryInitialSize);
219 EXPECT_SINGLE_PARSE_VALUE(true, "-XX:EnableHSpaceCompactForOOM", M::EnableHSpaceCompactForOOM);
220 EXPECT_SINGLE_PARSE_VALUE(false, "-XX:DisableHSpaceCompactForOOM", M::EnableHSpaceCompactForOOM);
221 EXPECT_SINGLE_PARSE_VALUE(0.5, "-XX:HeapTargetUtilization=0.5", M::HeapTargetUtilization);
222 EXPECT_SINGLE_PARSE_VALUE(5u, "-XX:ParallelGCThreads=5", M::ParallelGCThreads);
223 EXPECT_SINGLE_PARSE_EXISTS("-Xno-dex-file-fallback", M::NoDexFileFallback);
226 TEST_F(CmdlineParserTest, TestSimpleFailures) {
227 // Test argument is unknown to the parser
228 EXPECT_SINGLE_PARSE_FAIL("abcdefg^%@#*(@#", CmdlineResult::kUnknown);
229 // Test value map substitution fails
230 EXPECT_SINGLE_PARSE_FAIL("-Xverify:whatever", CmdlineResult::kFailure);
231 // Test value type parsing failures
232 EXPECT_SINGLE_PARSE_FAIL("-Xsswhatever", CmdlineResult::kFailure); // invalid memory value
233 EXPECT_SINGLE_PARSE_FAIL("-Xms123", CmdlineResult::kFailure); // memory value too small
234 EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=0.0", CmdlineResult::kOutOfRange); // toosmal
235 EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=2.0", CmdlineResult::kOutOfRange); // toolarg
236 EXPECT_SINGLE_PARSE_FAIL("-XX:ParallelGCThreads=-5", CmdlineResult::kOutOfRange); // too small
237 EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage); // not a valid suboption
240 TEST_F(CmdlineParserTest, TestLogVerbosity) {
242 const char* log_args = "-verbose:"
243 "class,compiler,gc,heap,jdwp,jni,monitor,profiler,signals,simulator,startup,"
244 "third-party-jni,threads,verifier";
246 LogVerbosity log_verbosity = LogVerbosity();
247 log_verbosity.class_linker = true;
248 log_verbosity.compiler = true;
249 log_verbosity.gc = true;
250 log_verbosity.heap = true;
251 log_verbosity.jdwp = true;
252 log_verbosity.jni = true;
253 log_verbosity.monitor = true;
254 log_verbosity.profiler = true;
255 log_verbosity.signals = true;
256 log_verbosity.simulator = true;
257 log_verbosity.startup = true;
258 log_verbosity.third_party_jni = true;
259 log_verbosity.threads = true;
260 log_verbosity.verifier = true;
262 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
266 const char* log_args = "-verbose:"
267 "class,compiler,gc,heap,jdwp,jni,monitor";
269 LogVerbosity log_verbosity = LogVerbosity();
270 log_verbosity.class_linker = true;
271 log_verbosity.compiler = true;
272 log_verbosity.gc = true;
273 log_verbosity.heap = true;
274 log_verbosity.jdwp = true;
275 log_verbosity.jni = true;
276 log_verbosity.monitor = true;
278 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
281 EXPECT_SINGLE_PARSE_FAIL("-verbose:blablabla", CmdlineResult::kUsage); // invalid verbose opt
284 const char* log_args = "-verbose:deopt";
285 LogVerbosity log_verbosity = LogVerbosity();
286 log_verbosity.deopt = true;
287 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
291 const char* log_args = "-verbose:collector";
292 LogVerbosity log_verbosity = LogVerbosity();
293 log_verbosity.collector = true;
294 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
298 const char* log_args = "-verbose:oat";
299 LogVerbosity log_verbosity = LogVerbosity();
300 log_verbosity.oat = true;
301 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
305 // TODO: Enable this b/19274810
306 TEST_F(CmdlineParserTest, DISABLED_TestXGcOption) {
311 XGcOption option_all_true{}; // NOLINT [readability/braces] [4]
312 option_all_true.collector_type_ = gc::CollectorType::kCollectorTypeCMS;
313 option_all_true.verify_pre_gc_heap_ = true;
314 option_all_true.verify_pre_sweeping_heap_ = true;
315 option_all_true.verify_post_gc_heap_ = true;
316 option_all_true.verify_pre_gc_rosalloc_ = true;
317 option_all_true.verify_pre_sweeping_rosalloc_ = true;
318 option_all_true.verify_post_gc_rosalloc_ = true;
320 const char * xgc_args_all_true = "-Xgc:concurrent,"
321 "preverify,presweepingverify,postverify,"
322 "preverify_rosalloc,presweepingverify_rosalloc,"
323 "postverify_rosalloc,precise,"
326 EXPECT_SINGLE_PARSE_VALUE(option_all_true, xgc_args_all_true, M::GcOption);
328 XGcOption option_all_false{}; // NOLINT [readability/braces] [4]
329 option_all_false.collector_type_ = gc::CollectorType::kCollectorTypeMS;
330 option_all_false.verify_pre_gc_heap_ = false;
331 option_all_false.verify_pre_sweeping_heap_ = false;
332 option_all_false.verify_post_gc_heap_ = false;
333 option_all_false.verify_pre_gc_rosalloc_ = false;
334 option_all_false.verify_pre_sweeping_rosalloc_ = false;
335 option_all_false.verify_post_gc_rosalloc_ = false;
337 const char* xgc_args_all_false = "-Xgc:nonconcurrent,"
338 "nopreverify,nopresweepingverify,nopostverify,nopreverify_rosalloc,"
339 "nopresweepingverify_rosalloc,nopostverify_rosalloc,noprecise,noverifycardtable";
341 EXPECT_SINGLE_PARSE_VALUE(option_all_false, xgc_args_all_false, M::GcOption);
343 XGcOption option_all_default{}; // NOLINT [readability/braces] [4]
345 const char* xgc_args_blank = "-Xgc:";
346 EXPECT_SINGLE_PARSE_VALUE(option_all_default, xgc_args_blank, M::GcOption);
352 EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage); // invalid Xgc opt
356 * {"-Xrunjdwp:_", "-agentlib:jdwp=_"}
358 TEST_F(CmdlineParserTest, TestJdwpOptions) {
364 * "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
366 JDWP::JdwpOptions opt = JDWP::JdwpOptions();
367 opt.transport = JDWP::JdwpTransportType::kJdwpTransportSocket;
371 const char *opt_args = "-Xrunjdwp:transport=dt_socket,address=8000,server=y";
373 EXPECT_SINGLE_PARSE_VALUE(opt, opt_args, M::JdwpOptions);
378 * "Example: -agentlib:jdwp=transport=dt_socket,address=localhost:6500,server=n\n");
380 JDWP::JdwpOptions opt = JDWP::JdwpOptions();
381 opt.transport = JDWP::JdwpTransportType::kJdwpTransportSocket;
382 opt.host = "localhost";
386 const char *opt_args = "-agentlib:jdwp=transport=dt_socket,address=localhost:6500,server=n";
388 EXPECT_SINGLE_PARSE_VALUE(opt, opt_args, M::JdwpOptions);
394 EXPECT_SINGLE_PARSE_FAIL("-Xrunjdwp:help", CmdlineResult::kUsage); // usage for help only
395 EXPECT_SINGLE_PARSE_FAIL("-Xrunjdwp:blabla", CmdlineResult::kFailure); // invalid subarg
396 EXPECT_SINGLE_PARSE_FAIL("-agentlib:jdwp=help", CmdlineResult::kUsage); // usage for help only
397 EXPECT_SINGLE_PARSE_FAIL("-agentlib:jdwp=blabla", CmdlineResult::kFailure); // invalid subarg
403 TEST_F(CmdlineParserTest, TestPropertiesList) {
408 std::vector<std::string> opt = {"hello"};
410 EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello", M::PropertiesList);
414 std::vector<std::string> opt = {"hello", "world"};
416 EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello -Dworld", M::PropertiesList);
420 std::vector<std::string> opt = {"one", "two", "three"};
422 EXPECT_SINGLE_PARSE_VALUE(opt, "-Done -Dtwo -Dthree", M::PropertiesList);
427 * -Xcompiler-option foo -Xcompiler-option bar ...
429 TEST_F(CmdlineParserTest, TestCompilerOption) {
434 std::vector<std::string> opt = {"hello"};
435 EXPECT_SINGLE_PARSE_VALUE(opt, "-Xcompiler-option hello", M::CompilerOptions);
439 std::vector<std::string> opt = {"hello", "world"};
440 EXPECT_SINGLE_PARSE_VALUE(opt,
441 "-Xcompiler-option hello -Xcompiler-option world",
446 std::vector<std::string> opt = {"one", "two", "three"};
447 EXPECT_SINGLE_PARSE_VALUE(opt,
448 "-Xcompiler-option one -Xcompiler-option two -Xcompiler-option three",
454 * -Xjit, -Xnojit, -Xjitcodecachesize, Xjitcompilethreshold
456 TEST_F(CmdlineParserTest, TestJitOptions) {
461 EXPECT_SINGLE_PARSE_VALUE(true, "-Xusejit:true", M::UseJitCompilation);
462 EXPECT_SINGLE_PARSE_VALUE(false, "-Xusejit:false", M::UseJitCompilation);
465 EXPECT_SINGLE_PARSE_VALUE(
466 MemoryKiB(16 * KB), "-Xjitinitialsize:16K", M::JITCodeCacheInitialCapacity);
467 EXPECT_SINGLE_PARSE_VALUE(
468 MemoryKiB(16 * MB), "-Xjitmaxsize:16M", M::JITCodeCacheMaxCapacity);
471 EXPECT_SINGLE_PARSE_VALUE(12345u, "-Xjitthreshold:12345", M::JITCompileThreshold);
478 TEST_F(CmdlineParserTest, ProfileSaverOptions) {
479 ProfileSaverOptions opt = ProfileSaverOptions(true, 1, 2, 3, 4, 5, 6, 7, "abc");
481 EXPECT_SINGLE_PARSE_VALUE(opt,
482 "-Xjitsaveprofilinginfo "
483 "-Xps-min-save-period-ms:1 "
484 "-Xps-save-resolved-classes-delay-ms:2 "
485 "-Xps-startup-method-samples:3 "
486 "-Xps-min-methods-to-save:4 "
487 "-Xps-min-classes-to-save:5 "
488 "-Xps-min-notification-before-wake:6 "
489 "-Xps-max-notification-before-wake:7 "
490 "-Xps-profile-path:abc",
491 M::ProfileSaverOpts);
494 /* -Xexperimental:_ */
495 TEST_F(CmdlineParserTest, TestExperimentalFlags) {
497 EXPECT_SINGLE_PARSE_DEFAULT_VALUE(ExperimentalFlags::kNone,
501 // Disabled explicitly
502 EXPECT_SINGLE_PARSE_VALUE(ExperimentalFlags::kNone,
503 "-Xexperimental:none",
508 TEST_F(CmdlineParserTest, TestVerify) {
509 EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kNone, "-Xverify:none", M::Verify);
510 EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kEnable, "-Xverify:remote", M::Verify);
511 EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kEnable, "-Xverify:all", M::Verify);
512 EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kSoftFail, "-Xverify:softfail", M::Verify);
515 TEST_F(CmdlineParserTest, TestIgnoreUnrecognized) {
516 RuntimeParser::Builder parserBuilder;
521 .IgnoreUnrecognized(true);
523 parser_.reset(new RuntimeParser(parserBuilder.Build()));
525 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option");
526 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option1 --non-existent-option-2");
529 TEST_F(CmdlineParserTest, TestIgnoredArguments) {
530 std::initializer_list<const char*> ignored_args = {
531 "-ea", "-da", "-enableassertions", "-disableassertions", "--runtime-arg", "-esa",
532 "-dsa", "-enablesystemassertions", "-disablesystemassertions", "-Xrs", "-Xint:abdef",
533 "-Xdexopt:foobar", "-Xnoquithandler", "-Xjnigreflimit:ixnay", "-Xgenregmap", "-Xnogenregmap",
534 "-Xverifyopt:never", "-Xcheckdexsum", "-Xincludeselectedop", "-Xjitop:noop",
535 "-Xincludeselectedmethod", "-Xjitblocking", "-Xjitmethod:_", "-Xjitclass:nosuchluck",
536 "-Xjitoffset:none", "-Xjitconfig:yes", "-Xjitcheckcg", "-Xjitverbose", "-Xjitprofile",
537 "-Xjitdisableopt", "-Xjitsuspendpoll", "-XX:mainThreadStackSize=1337"
540 // Check they are ignored when parsed one at a time
541 for (auto&& arg : ignored_args) {
543 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(arg);
546 // Check they are ignored when we pass it all together at once
547 std::vector<const char*> argv = ignored_args;
548 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv);
551 TEST_F(CmdlineParserTest, MultipleArguments) {
552 EXPECT_TRUE(IsResultSuccessful(parser_->Parse(
553 "-help -XX:ForegroundHeapGrowthMultiplier=0.5 "
554 "-Xnodex2oat -Xmethod-trace -XX:LargeObjectSpace=map")));
556 auto&& map = parser_->ReleaseArgumentsMap();
557 EXPECT_EQ(5u, map.Size());
558 EXPECT_KEY_VALUE(map, M::Help, Unit{}); // NOLINT [whitespace/braces] [5]
559 EXPECT_KEY_VALUE(map, M::ForegroundHeapGrowthMultiplier, 0.5);
560 EXPECT_KEY_VALUE(map, M::Dex2Oat, false);
561 EXPECT_KEY_VALUE(map, M::MethodTrace, Unit{}); // NOLINT [whitespace/braces] [5]
562 EXPECT_KEY_VALUE(map, M::LargeObjectSpace, gc::space::LargeObjectSpaceType::kMap);