blob: 288f7ac0134c4824d7842742014aabaf23ca06c0 [file] [log] [blame]
Igor Murashkinaaebaa02015-01-26 10:55:53 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "cmdline_parser.h"
18#include "runtime/runtime_options.h"
19#include "runtime/parsed_options.h"
20
21#include "utils.h"
22#include <numeric>
23#include "gtest/gtest.h"
24
25#define EXPECT_NULL(expected) EXPECT_EQ(reinterpret_cast<const void*>(expected), \
26 reinterpret_cast<void*>(NULL));
27
28namespace art {
29 bool UsuallyEquals(double expected, double actual);
30
31 // This has a gtest dependency, which is why it's in the gtest only.
32 bool operator==(const TestProfilerOptions& lhs, const TestProfilerOptions& rhs) {
33 return lhs.enabled_ == rhs.enabled_ &&
34 lhs.output_file_name_ == rhs.output_file_name_ &&
35 lhs.period_s_ == rhs.period_s_ &&
36 lhs.duration_s_ == rhs.duration_s_ &&
37 lhs.interval_us_ == rhs.interval_us_ &&
38 UsuallyEquals(lhs.backoff_coefficient_, rhs.backoff_coefficient_) &&
39 UsuallyEquals(lhs.start_immediately_, rhs.start_immediately_) &&
40 UsuallyEquals(lhs.top_k_threshold_, rhs.top_k_threshold_) &&
41 UsuallyEquals(lhs.top_k_change_threshold_, rhs.top_k_change_threshold_) &&
42 lhs.profile_type_ == rhs.profile_type_ &&
43 lhs.max_stack_depth_ == rhs.max_stack_depth_;
44 }
45
46 bool UsuallyEquals(double expected, double actual) {
47 using FloatingPoint = ::testing::internal::FloatingPoint<double>;
48
49 FloatingPoint exp(expected);
50 FloatingPoint act(actual);
51
52 // Compare with ULPs instead of comparing with ==
53 return exp.AlmostEquals(act);
54 }
55
56 template <typename T>
57 bool UsuallyEquals(const T& expected, const T& actual,
58 typename std::enable_if<
59 detail::SupportsEqualityOperator<T>::value>::type* = 0) {
60 return expected == actual;
61 }
62
63 // Try to use memcmp to compare simple plain-old-data structs.
64 //
65 // This should *not* generate false positives, but it can generate false negatives.
66 // This will mostly work except for fields like float which can have different bit patterns
67 // that are nevertheless equal.
68 // If a test is failing because the structs aren't "equal" when they really are
69 // then it's recommended to implement operator== for it instead.
70 template <typename T, typename ... Ignore>
71 bool UsuallyEquals(const T& expected, const T& actual,
72 const Ignore& ... more ATTRIBUTE_UNUSED,
73 typename std::enable_if<std::is_pod<T>::value>::type* = 0,
74 typename std::enable_if<!detail::SupportsEqualityOperator<T>::value>::type* = 0
75 ) {
76 return memcmp(std::addressof(expected), std::addressof(actual), sizeof(T)) == 0;
77 }
78
79 bool UsuallyEquals(const XGcOption& expected, const XGcOption& actual) {
80 return memcmp(std::addressof(expected), std::addressof(actual), sizeof(expected)) == 0;
81 }
82
83 bool UsuallyEquals(const char* expected, std::string actual) {
84 return std::string(expected) == actual;
85 }
86
87 template <typename TMap, typename TKey, typename T>
88 ::testing::AssertionResult IsExpectedKeyValue(const T& expected,
89 const TMap& map,
90 const TKey& key) {
91 auto* actual = map.Get(key);
92 if (actual != nullptr) {
93 if (!UsuallyEquals(expected, *actual)) {
94 return ::testing::AssertionFailure()
95 << "expected " << detail::ToStringAny(expected) << " but got "
96 << detail::ToStringAny(*actual);
97 }
98 return ::testing::AssertionSuccess();
99 }
100
101 return ::testing::AssertionFailure() << "key was not in the map";
102 }
103
104class CmdlineParserTest : public ::testing::Test {
105 public:
106 CmdlineParserTest() = default;
107 ~CmdlineParserTest() = default;
108
109 protected:
110 using M = RuntimeArgumentMap;
111 using RuntimeParser = ParsedOptions::RuntimeParser;
112
113 static void SetUpTestCase() {
114 art::InitLogging(nullptr); // argv = null
115 }
116
117 virtual void SetUp() {
118 parser_ = ParsedOptions::MakeParser(false); // do not ignore unrecognized options
119 }
120
121 static ::testing::AssertionResult IsResultSuccessful(CmdlineResult result) {
122 if (result.IsSuccess()) {
123 return ::testing::AssertionSuccess();
124 } else {
125 return ::testing::AssertionFailure()
126 << result.GetStatus() << " with: " << result.GetMessage();
127 }
128 }
129
130 static ::testing::AssertionResult IsResultFailure(CmdlineResult result,
131 CmdlineResult::Status failure_status) {
132 if (result.IsSuccess()) {
133 return ::testing::AssertionFailure() << " got success but expected failure: "
134 << failure_status;
135 } else if (result.GetStatus() == failure_status) {
136 return ::testing::AssertionSuccess();
137 }
138
139 return ::testing::AssertionFailure() << " expected failure " << failure_status
140 << " but got " << result.GetStatus();
141 }
142
143 std::unique_ptr<RuntimeParser> parser_;
144};
145
146#define EXPECT_KEY_EXISTS(map, key) EXPECT_TRUE((map).Exists(key))
147#define EXPECT_KEY_VALUE(map, key, expected) EXPECT_TRUE(IsExpectedKeyValue(expected, map, key))
148
149#define EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv) \
150 do { \
151 EXPECT_TRUE(IsResultSuccessful(parser_->Parse(argv))); \
152 EXPECT_EQ(0u, parser_->GetArgumentsMap().Size()); \
153 } while (false)
154
155#define _EXPECT_SINGLE_PARSE_EXISTS(argv, key) \
156 do { \
157 EXPECT_TRUE(IsResultSuccessful(parser_->Parse(argv))); \
158 RuntimeArgumentMap args = parser_->ReleaseArgumentsMap(); \
159 EXPECT_EQ(1u, args.Size()); \
160 EXPECT_KEY_EXISTS(args, key); \
161
162#define EXPECT_SINGLE_PARSE_EXISTS(argv, key) \
163 _EXPECT_SINGLE_PARSE_EXISTS(argv, key); \
164 } while (false)
165
166#define EXPECT_SINGLE_PARSE_VALUE(expected, argv, key) \
167 _EXPECT_SINGLE_PARSE_EXISTS(argv, key); \
168 EXPECT_KEY_VALUE(args, key, expected); \
169 } while (false) // NOLINT [readability/namespace] [5]
170
171#define EXPECT_SINGLE_PARSE_VALUE_STR(expected, argv, key) \
172 EXPECT_SINGLE_PARSE_VALUE(std::string(expected), argv, key)
173
174#define EXPECT_SINGLE_PARSE_FAIL(argv, failure_status) \
175 do { \
176 EXPECT_TRUE(IsResultFailure(parser_->Parse(argv), failure_status));\
177 RuntimeArgumentMap args = parser_->ReleaseArgumentsMap();\
178 EXPECT_EQ(0u, args.Size()); \
179 } while (false)
180
181TEST_F(CmdlineParserTest, TestSimpleSuccesses) {
182 auto& parser = *parser_;
183
184 EXPECT_LT(0u, parser.CountDefinedArguments());
185
186 {
187 // Test case 1: No command line arguments
188 EXPECT_TRUE(IsResultSuccessful(parser.Parse("")));
189 RuntimeArgumentMap args = parser.ReleaseArgumentsMap();
190 EXPECT_EQ(0u, args.Size());
191 }
192
193 EXPECT_SINGLE_PARSE_EXISTS("-Xzygote", M::Zygote);
194 EXPECT_SINGLE_PARSE_VALUE_STR("/hello/world", "-Xbootclasspath:/hello/world", M::BootClassPath);
195 EXPECT_SINGLE_PARSE_VALUE("/hello/world", "-Xbootclasspath:/hello/world", M::BootClassPath);
196 EXPECT_SINGLE_PARSE_VALUE(false, "-Xverify:none", M::Verify);
197 EXPECT_SINGLE_PARSE_VALUE(true, "-Xverify:remote", M::Verify);
198 EXPECT_SINGLE_PARSE_VALUE(true, "-Xverify:all", M::Verify);
199 EXPECT_SINGLE_PARSE_VALUE(Memory<1>(234), "-Xss234", M::StackSize);
200 EXPECT_SINGLE_PARSE_VALUE(MemoryKiB(1234*MB), "-Xms1234m", M::MemoryInitialSize);
201 EXPECT_SINGLE_PARSE_VALUE(true, "-XX:EnableHSpaceCompactForOOM", M::EnableHSpaceCompactForOOM);
202 EXPECT_SINGLE_PARSE_VALUE(false, "-XX:DisableHSpaceCompactForOOM", M::EnableHSpaceCompactForOOM);
203 EXPECT_SINGLE_PARSE_VALUE(0.5, "-XX:HeapTargetUtilization=0.5", M::HeapTargetUtilization);
204 EXPECT_SINGLE_PARSE_VALUE(5u, "-XX:ParallelGCThreads=5", M::ParallelGCThreads);
205} // TEST_F
206
207TEST_F(CmdlineParserTest, TestSimpleFailures) {
208 // Test argument is unknown to the parser
209 EXPECT_SINGLE_PARSE_FAIL("abcdefg^%@#*(@#", CmdlineResult::kUnknown);
210 // Test value map substitution fails
211 EXPECT_SINGLE_PARSE_FAIL("-Xverify:whatever", CmdlineResult::kFailure);
212 // Test value type parsing failures
213 EXPECT_SINGLE_PARSE_FAIL("-Xsswhatever", CmdlineResult::kFailure); // invalid memory value
214 EXPECT_SINGLE_PARSE_FAIL("-Xms123", CmdlineResult::kFailure); // memory value too small
215 EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=0.0", CmdlineResult::kOutOfRange); // toosmal
216 EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=2.0", CmdlineResult::kOutOfRange); // toolarg
217 EXPECT_SINGLE_PARSE_FAIL("-XX:ParallelGCThreads=-5", CmdlineResult::kOutOfRange); // too small
218 EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage); // not a valid suboption
219} // TEST_F
220
221TEST_F(CmdlineParserTest, TestLogVerbosity) {
222 {
223 const char* log_args = "-verbose:"
224 "class,compiler,gc,heap,jdwp,jni,monitor,profiler,signals,startup,third-party-jni,"
225 "threads,verifier";
226
227 LogVerbosity log_verbosity = LogVerbosity();
228 log_verbosity.class_linker = true;
229 log_verbosity.compiler = true;
230 log_verbosity.gc = true;
231 log_verbosity.heap = true;
232 log_verbosity.jdwp = true;
233 log_verbosity.jni = true;
234 log_verbosity.monitor = true;
235 log_verbosity.profiler = true;
236 log_verbosity.signals = true;
237 log_verbosity.startup = true;
238 log_verbosity.third_party_jni = true;
239 log_verbosity.threads = true;
240 log_verbosity.verifier = true;
241
242 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
243 }
244
245 {
246 const char* log_args = "-verbose:"
247 "class,compiler,gc,heap,jdwp,jni,monitor";
248
249 LogVerbosity log_verbosity = LogVerbosity();
250 log_verbosity.class_linker = true;
251 log_verbosity.compiler = true;
252 log_verbosity.gc = true;
253 log_verbosity.heap = true;
254 log_verbosity.jdwp = true;
255 log_verbosity.jni = true;
256 log_verbosity.monitor = true;
257
258 EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
259 }
260
261 EXPECT_SINGLE_PARSE_FAIL("-verbose:blablabla", CmdlineResult::kUsage); // invalid verbose opt
262} // TEST_F
263
Nicolas Geoffray8f4ee5c2015-02-05 10:14:10 +0000264// TODO: Enable this b/19274810
265TEST_F(CmdlineParserTest, DISABLED_TestXGcOption) {
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800266 /*
267 * Test success
268 */
269 {
270 XGcOption option_all_true{}; // NOLINT [readability/braces] [4]
271 option_all_true.collector_type_ = gc::CollectorType::kCollectorTypeCMS;
272 option_all_true.verify_pre_gc_heap_ = true;
273 option_all_true.verify_pre_sweeping_heap_ = true;
274 option_all_true.verify_post_gc_heap_ = true;
275 option_all_true.verify_pre_gc_rosalloc_ = true;
276 option_all_true.verify_pre_sweeping_rosalloc_ = true;
277 option_all_true.verify_post_gc_rosalloc_ = true;
278
279 const char * xgc_args_all_true = "-Xgc:concurrent,"
280 "preverify,presweepingverify,postverify,"
281 "preverify_rosalloc,presweepingverify_rosalloc,"
282 "postverify_rosalloc,precise,"
283 "verifycardtable";
284
285 EXPECT_SINGLE_PARSE_VALUE(option_all_true, xgc_args_all_true, M::GcOption);
286
287 XGcOption option_all_false{}; // NOLINT [readability/braces] [4]
288 option_all_false.collector_type_ = gc::CollectorType::kCollectorTypeMS;
289 option_all_false.verify_pre_gc_heap_ = false;
290 option_all_false.verify_pre_sweeping_heap_ = false;
291 option_all_false.verify_post_gc_heap_ = false;
292 option_all_false.verify_pre_gc_rosalloc_ = false;
293 option_all_false.verify_pre_sweeping_rosalloc_ = false;
294 option_all_false.verify_post_gc_rosalloc_ = false;
295
296 const char* xgc_args_all_false = "-Xgc:nonconcurrent,"
297 "nopreverify,nopresweepingverify,nopostverify,nopreverify_rosalloc,"
298 "nopresweepingverify_rosalloc,nopostverify_rosalloc,noprecise,noverifycardtable";
299
300 EXPECT_SINGLE_PARSE_VALUE(option_all_false, xgc_args_all_false, M::GcOption);
301
302 XGcOption option_all_default{}; // NOLINT [readability/braces] [4]
303
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800304 const char* xgc_args_blank = "-Xgc:";
305 EXPECT_SINGLE_PARSE_VALUE(option_all_default, xgc_args_blank, M::GcOption);
306 }
307
308 /*
309 * Test failures
310 */
311 EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage); // invalid Xgc opt
312} // TEST_F
313
314/*
315 * {"-Xrunjdwp:_", "-agentlib:jdwp=_"}
316 */
317TEST_F(CmdlineParserTest, TestJdwpOptions) {
318 /*
319 * Test success
320 */
321 {
322 /*
323 * "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
324 */
325 JDWP::JdwpOptions opt = JDWP::JdwpOptions();
326 opt.transport = JDWP::JdwpTransportType::kJdwpTransportSocket;
327 opt.port = 8000;
328 opt.server = true;
329
330 const char *opt_args = "-Xrunjdwp:transport=dt_socket,address=8000,server=y";
331
332 EXPECT_SINGLE_PARSE_VALUE(opt, opt_args, M::JdwpOptions);
333 }
334
335 {
336 /*
337 * "Example: -agentlib:jdwp=transport=dt_socket,address=localhost:6500,server=n\n");
338 */
339 JDWP::JdwpOptions opt = JDWP::JdwpOptions();
340 opt.transport = JDWP::JdwpTransportType::kJdwpTransportSocket;
341 opt.host = "localhost";
342 opt.port = 6500;
343 opt.server = false;
344
345 const char *opt_args = "-agentlib:jdwp=transport=dt_socket,address=localhost:6500,server=n";
346
347 EXPECT_SINGLE_PARSE_VALUE(opt, opt_args, M::JdwpOptions);
348 }
349
350 /*
351 * Test failures
352 */
353 EXPECT_SINGLE_PARSE_FAIL("-Xrunjdwp:help", CmdlineResult::kUsage); // usage for help only
354 EXPECT_SINGLE_PARSE_FAIL("-Xrunjdwp:blabla", CmdlineResult::kFailure); // invalid subarg
355 EXPECT_SINGLE_PARSE_FAIL("-agentlib:jdwp=help", CmdlineResult::kUsage); // usage for help only
356 EXPECT_SINGLE_PARSE_FAIL("-agentlib:jdwp=blabla", CmdlineResult::kFailure); // invalid subarg
357} // TEST_F
358
359/*
360 * -D_ -D_ -D_ ...
361 */
362TEST_F(CmdlineParserTest, TestPropertiesList) {
363 /*
364 * Test successes
365 */
366 {
367 std::vector<std::string> opt = {"hello"};
368
369 EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello", M::PropertiesList);
370 }
371
372 {
373 std::vector<std::string> opt = {"hello", "world"};
374
375 EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello -Dworld", M::PropertiesList);
376 }
377
378 {
379 std::vector<std::string> opt = {"one", "two", "three"};
380
381 EXPECT_SINGLE_PARSE_VALUE(opt, "-Done -Dtwo -Dthree", M::PropertiesList);
382 }
383} // TEST_F
384
385/*
386* -Xcompiler-option foo -Xcompiler-option bar ...
387*/
388TEST_F(CmdlineParserTest, TestCompilerOption) {
389 /*
390 * Test successes
391 */
392 {
393 std::vector<std::string> opt = {"hello"};
394 EXPECT_SINGLE_PARSE_VALUE(opt, "-Xcompiler-option hello", M::CompilerOptions);
395 }
396
397 {
398 std::vector<std::string> opt = {"hello", "world"};
399 EXPECT_SINGLE_PARSE_VALUE(opt,
400 "-Xcompiler-option hello -Xcompiler-option world",
401 M::CompilerOptions);
402 }
403
404 {
405 std::vector<std::string> opt = {"one", "two", "three"};
406 EXPECT_SINGLE_PARSE_VALUE(opt,
407 "-Xcompiler-option one -Xcompiler-option two -Xcompiler-option three",
408 M::CompilerOptions);
409 }
410} // TEST_F
411
412/*
413* -X-profile-*
414*/
415TEST_F(CmdlineParserTest, TestProfilerOptions) {
416 /*
417 * Test successes
418 */
419
420 {
421 TestProfilerOptions opt;
422 opt.enabled_ = true;
423
424 EXPECT_SINGLE_PARSE_VALUE(opt,
425 "-Xenable-profiler",
426 M::ProfilerOpts);
427 }
428
429 {
430 TestProfilerOptions opt;
431 // also need to test 'enabled'
432 opt.output_file_name_ = "hello_world.txt";
433
434 EXPECT_SINGLE_PARSE_VALUE(opt,
435 "-Xprofile-filename:hello_world.txt ",
436 M::ProfilerOpts);
437 }
438
439 {
440 TestProfilerOptions opt = TestProfilerOptions();
441 // also need to test 'enabled'
442 opt.output_file_name_ = "output.txt";
443 opt.period_s_ = 123u;
444 opt.duration_s_ = 456u;
445 opt.interval_us_ = 789u;
446 opt.backoff_coefficient_ = 2.0;
447 opt.start_immediately_ = true;
448 opt.top_k_threshold_ = 50.0;
449 opt.top_k_change_threshold_ = 60.0;
450 opt.profile_type_ = kProfilerMethod;
451 opt.max_stack_depth_ = 1337u;
452
453 EXPECT_SINGLE_PARSE_VALUE(opt,
454 "-Xprofile-filename:output.txt "
455 "-Xprofile-period:123 "
456 "-Xprofile-duration:456 "
457 "-Xprofile-interval:789 "
458 "-Xprofile-backoff:2.0 "
459 "-Xprofile-start-immediately "
460 "-Xprofile-top-k-threshold:50.0 "
461 "-Xprofile-top-k-change-threshold:60.0 "
462 "-Xprofile-type:method "
463 "-Xprofile-max-stack-depth:1337",
464 M::ProfilerOpts);
465 }
466
467 {
468 TestProfilerOptions opt = TestProfilerOptions();
469 opt.profile_type_ = kProfilerBoundedStack;
470
471 EXPECT_SINGLE_PARSE_VALUE(opt,
472 "-Xprofile-type:stack",
473 M::ProfilerOpts);
474 }
475} // TEST_F
476
477TEST_F(CmdlineParserTest, TestIgnoreUnrecognized) {
478 RuntimeParser::Builder parserBuilder;
479
480 parserBuilder
481 .Define("-help")
482 .IntoKey(M::Help)
483 .IgnoreUnrecognized(true);
484
485 parser_.reset(new RuntimeParser(parserBuilder.Build()));
486
487 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option");
488 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option1 --non-existent-option-2");
489} // TEST_F
490
491TEST_F(CmdlineParserTest, TestIgnoredArguments) {
492 std::initializer_list<const char*> ignored_args = {
493 "-ea", "-da", "-enableassertions", "-disableassertions", "--runtime-arg", "-esa",
494 "-dsa", "-enablesystemassertions", "-disablesystemassertions", "-Xrs", "-Xint:abdef",
495 "-Xdexopt:foobar", "-Xnoquithandler", "-Xjnigreflimit:ixnay", "-Xgenregmap", "-Xnogenregmap",
496 "-Xverifyopt:never", "-Xcheckdexsum", "-Xincludeselectedop", "-Xjitop:noop",
497 "-Xincludeselectedmethod", "-Xjitthreshold:123", "-Xjitcodecachesize:12345",
498 "-Xjitblocking", "-Xjitmethod:_", "-Xjitclass:nosuchluck", "-Xjitoffset:none",
499 "-Xjitconfig:yes", "-Xjitcheckcg", "-Xjitverbose", "-Xjitprofile",
500 "-Xjitdisableopt", "-Xjitsuspendpoll", "-XX:mainThreadStackSize=1337"
501 };
502
503 // Check they are ignored when parsed one at a time
504 for (auto&& arg : ignored_args) {
505 SCOPED_TRACE(arg);
506 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(arg);
507 }
508
509 // Check they are ignored when we pass it all together at once
510 std::vector<const char*> argv = ignored_args;
511 EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv);
512} // TEST_F
513
514TEST_F(CmdlineParserTest, MultipleArguments) {
515 EXPECT_TRUE(IsResultSuccessful(parser_->Parse(
516 "-help -XX:ForegroundHeapGrowthMultiplier=0.5 "
517 "-Xnodex2oat -Xmethod-trace -XX:LargeObjectSpace=map")));
518
519 auto&& map = parser_->ReleaseArgumentsMap();
520 EXPECT_EQ(5u, map.Size());
521 EXPECT_KEY_VALUE(map, M::Help, Unit{}); // NOLINT [whitespace/braces] [5]
522 EXPECT_KEY_VALUE(map, M::ForegroundHeapGrowthMultiplier, 0.5);
523 EXPECT_KEY_VALUE(map, M::Dex2Oat, false);
524 EXPECT_KEY_VALUE(map, M::MethodTrace, Unit{}); // NOLINT [whitespace/braces] [5]
525 EXPECT_KEY_VALUE(map, M::LargeObjectSpace, gc::space::LargeObjectSpaceType::kMap);
526} // TEST_F
527} // namespace art