1 /*
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 
19 #include <numeric>
20 
21 #include "gtest/gtest.h"
22 
23 #include "base/utils.h"
24 #include "jdwp_provider.h"
25 #include "experimental_flags.h"
26 #include "parsed_options.h"
27 #include "runtime.h"
28 #include "runtime_options.h"
29 
30 #define EXPECT_NULL(expected) EXPECT_EQ(reinterpret_cast<const void*>(expected), \
31                                         reinterpret_cast<void*>(nullptr));
32 
33 namespace art {
34   bool UsuallyEquals(double expected, double actual);
35 
36   // This has a gtest dependency, which is why it's in the gtest only.
operator ==(const ProfileSaverOptions & lhs,const ProfileSaverOptions & rhs)37   bool operator==(const ProfileSaverOptions& lhs, const ProfileSaverOptions& rhs) {
38     return lhs.enabled_ == rhs.enabled_ &&
39         lhs.min_save_period_ms_ == rhs.min_save_period_ms_ &&
40         lhs.save_resolved_classes_delay_ms_ == rhs.save_resolved_classes_delay_ms_ &&
41         lhs.hot_startup_method_samples_ == rhs.hot_startup_method_samples_ &&
42         lhs.min_methods_to_save_ == rhs.min_methods_to_save_ &&
43         lhs.min_classes_to_save_ == rhs.min_classes_to_save_ &&
44         lhs.min_notification_before_wake_ == rhs.min_notification_before_wake_ &&
45         lhs.max_notification_before_wake_ == rhs.max_notification_before_wake_;
46   }
47 
UsuallyEquals(double expected,double actual)48   bool UsuallyEquals(double expected, double actual) {
49     using FloatingPoint = ::testing::internal::FloatingPoint<double>;
50 
51     FloatingPoint exp(expected);
52     FloatingPoint act(actual);
53 
54     // Compare with ULPs instead of comparing with ==
55     return exp.AlmostEquals(act);
56   }
57 
58   template <typename T>
UsuallyEquals(const T & expected,const T & actual,typename std::enable_if<detail::SupportsEqualityOperator<T>::value>::type * =nullptr)59   bool UsuallyEquals(const T& expected, const T& actual,
60                      typename std::enable_if<
61                          detail::SupportsEqualityOperator<T>::value>::type* = nullptr) {
62     return expected == actual;
63   }
64 
65   template <char Separator>
UsuallyEquals(const std::vector<std::string> & expected,const ParseStringList<Separator> & actual)66   bool UsuallyEquals(const std::vector<std::string>& expected,
67                      const ParseStringList<Separator>& actual) {
68     return expected == static_cast<std::vector<std::string>>(actual);
69   }
70 
71   // Try to use memcmp to compare simple plain-old-data structs.
72   //
73   // This should *not* generate false positives, but it can generate false negatives.
74   // This will mostly work except for fields like float which can have different bit patterns
75   // that are nevertheless equal.
76   // If a test is failing because the structs aren't "equal" when they really are
77   // then it's recommended to implement operator== for it instead.
78   template <typename T, typename ... Ignore>
UsuallyEquals(const T & expected,const T & actual,const Ignore &...more ATTRIBUTE_UNUSED,typename std::enable_if<std::is_pod<T>::value>::type * =nullptr,typename std::enable_if<!detail::SupportsEqualityOperator<T>::value>::type * =nullptr)79   bool UsuallyEquals(const T& expected, const T& actual,
80                      const Ignore& ... more ATTRIBUTE_UNUSED,
81                      typename std::enable_if<std::is_pod<T>::value>::type* = nullptr,
82                      typename std::enable_if<!detail::SupportsEqualityOperator<T>::value>::type* = nullptr
83                      ) {
84     return memcmp(std::addressof(expected), std::addressof(actual), sizeof(T)) == 0;
85   }
86 
UsuallyEquals(const XGcOption & expected,const XGcOption & actual)87   bool UsuallyEquals(const XGcOption& expected, const XGcOption& actual) {
88     return memcmp(std::addressof(expected), std::addressof(actual), sizeof(expected)) == 0;
89   }
90 
UsuallyEquals(const char * expected,const std::string & actual)91   bool UsuallyEquals(const char* expected, const std::string& actual) {
92     return std::string(expected) == actual;
93   }
94 
95   template <typename TMap, typename TKey, typename T>
IsExpectedKeyValue(const T & expected,const TMap & map,const TKey & key)96   ::testing::AssertionResult IsExpectedKeyValue(const T& expected,
97                                                 const TMap& map,
98                                                 const TKey& key) {
99     auto* actual = map.Get(key);
100     if (actual != nullptr) {
101       if (!UsuallyEquals(expected, *actual)) {
102         return ::testing::AssertionFailure()
103           << "expected " << detail::ToStringAny(expected) << " but got "
104           << detail::ToStringAny(*actual);
105       }
106       return ::testing::AssertionSuccess();
107     }
108 
109     return ::testing::AssertionFailure() << "key was not in the map";
110   }
111 
112   template <typename TMap, typename TKey, typename T>
IsExpectedDefaultKeyValue(const T & expected,const TMap & map,const TKey & key)113   ::testing::AssertionResult IsExpectedDefaultKeyValue(const T& expected,
114                                                        const TMap& map,
115                                                        const TKey& key) {
116     const T& actual = map.GetOrDefault(key);
117     if (!UsuallyEquals(expected, actual)) {
118       return ::testing::AssertionFailure()
119           << "expected " << detail::ToStringAny(expected) << " but got "
120           << detail::ToStringAny(actual);
121      }
122     return ::testing::AssertionSuccess();
123   }
124 
125 class CmdlineParserTest : public ::testing::Test {
126  public:
127   CmdlineParserTest() = default;
128   ~CmdlineParserTest() = default;
129 
130  protected:
131   using M = RuntimeArgumentMap;
132   using RuntimeParser = ParsedOptions::RuntimeParser;
133 
SetUpTestCase()134   static void SetUpTestCase() {
135     art::Locks::Init();
136     art::InitLogging(nullptr, art::Runtime::Abort);  // argv = null
137   }
138 
SetUp()139   void SetUp() override {
140     parser_ = ParsedOptions::MakeParser(false);  // do not ignore unrecognized options
141   }
142 
IsResultSuccessful(const CmdlineResult & result)143   static ::testing::AssertionResult IsResultSuccessful(const CmdlineResult& result) {
144     if (result.IsSuccess()) {
145       return ::testing::AssertionSuccess();
146     } else {
147       return ::testing::AssertionFailure()
148         << result.GetStatus() << " with: " << result.GetMessage();
149     }
150   }
151 
IsResultFailure(const CmdlineResult & result,CmdlineResult::Status failure_status)152   static ::testing::AssertionResult IsResultFailure(const CmdlineResult& result,
153                                                     CmdlineResult::Status failure_status) {
154     if (result.IsSuccess()) {
155       return ::testing::AssertionFailure() << " got success but expected failure: "
156           << failure_status;
157     } else if (result.GetStatus() == failure_status) {
158       return ::testing::AssertionSuccess();
159     }
160 
161     return ::testing::AssertionFailure() << " expected failure " << failure_status
162         << " but got " << result.GetStatus();
163   }
164 
165   std::unique_ptr<RuntimeParser> parser_;
166 };
167 
168 #define EXPECT_KEY_EXISTS(map, key) EXPECT_TRUE((map).Exists(key))
169 #define EXPECT_KEY_VALUE(map, key, expected) EXPECT_TRUE(IsExpectedKeyValue(expected, map, key))
170 #define EXPECT_DEFAULT_KEY_VALUE(map, key, expected) EXPECT_TRUE(IsExpectedDefaultKeyValue(expected, map, key))
171 
172 #define _EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv)              \
173   do {                                                        \
174     EXPECT_TRUE(IsResultSuccessful(parser_->Parse(argv)));    \
175     EXPECT_EQ(0u, parser_->GetArgumentsMap().Size());         \
176 
177 #define EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv)               \
178   _EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv);                   \
179   } while (false)
180 
181 #define EXPECT_SINGLE_PARSE_DEFAULT_VALUE(expected, argv, key)\
182   _EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv);                   \
183     RuntimeArgumentMap args = parser_->ReleaseArgumentsMap(); \
184     EXPECT_DEFAULT_KEY_VALUE(args, key, expected);            \
185   } while (false)                                             // NOLINT [readability/namespace] [5]
186 
187 #define _EXPECT_SINGLE_PARSE_EXISTS(argv, key)                \
188   do {                                                        \
189     EXPECT_TRUE(IsResultSuccessful(parser_->Parse(argv)));    \
190     RuntimeArgumentMap args = parser_->ReleaseArgumentsMap(); \
191     EXPECT_EQ(1u, args.Size());                               \
192     EXPECT_KEY_EXISTS(args, key);                             \
193 
194 #define EXPECT_SINGLE_PARSE_EXISTS(argv, key)                 \
195     _EXPECT_SINGLE_PARSE_EXISTS(argv, key);                   \
196   } while (false)
197 
198 #define EXPECT_SINGLE_PARSE_VALUE(expected, argv, key)        \
199     _EXPECT_SINGLE_PARSE_EXISTS(argv, key);                   \
200     EXPECT_KEY_VALUE(args, key, expected);                    \
201   } while (false)
202 
203 #define EXPECT_SINGLE_PARSE_VALUE_STR(expected, argv, key)    \
204   EXPECT_SINGLE_PARSE_VALUE(std::string(expected), argv, key)
205 
206 #define EXPECT_SINGLE_PARSE_FAIL(argv, failure_status)         \
207     do {                                                       \
208       EXPECT_TRUE(IsResultFailure(parser_->Parse(argv), failure_status));\
209       RuntimeArgumentMap args = parser_->ReleaseArgumentsMap();\
210       EXPECT_EQ(0u, args.Size());                              \
211     } while (false)
212 
TEST_F(CmdlineParserTest,TestSimpleSuccesses)213 TEST_F(CmdlineParserTest, TestSimpleSuccesses) {
214   auto& parser = *parser_;
215 
216   EXPECT_LT(0u, parser.CountDefinedArguments());
217 
218   {
219     // Test case 1: No command line arguments
220     EXPECT_TRUE(IsResultSuccessful(parser.Parse("")));
221     RuntimeArgumentMap args = parser.ReleaseArgumentsMap();
222     EXPECT_EQ(0u, args.Size());
223   }
224 
225   EXPECT_SINGLE_PARSE_EXISTS("-Xzygote", M::Zygote);
226   EXPECT_SINGLE_PARSE_VALUE(std::vector<std::string>({"/hello/world"}),
227                             "-Xbootclasspath:/hello/world",
228                             M::BootClassPath);
229   EXPECT_SINGLE_PARSE_VALUE(std::vector<std::string>({"/hello", "/world"}),
230                             "-Xbootclasspath:/hello:/world",
231                             M::BootClassPath);
232   EXPECT_SINGLE_PARSE_VALUE_STR("/hello/world", "-classpath /hello/world", M::ClassPath);
233   EXPECT_SINGLE_PARSE_VALUE(Memory<1>(234), "-Xss234", M::StackSize);
234   EXPECT_SINGLE_PARSE_VALUE(MemoryKiB(1234*MB), "-Xms1234m", M::MemoryInitialSize);
235   EXPECT_SINGLE_PARSE_VALUE(true, "-XX:EnableHSpaceCompactForOOM", M::EnableHSpaceCompactForOOM);
236   EXPECT_SINGLE_PARSE_VALUE(false, "-XX:DisableHSpaceCompactForOOM", M::EnableHSpaceCompactForOOM);
237   EXPECT_SINGLE_PARSE_VALUE(0.5, "-XX:HeapTargetUtilization=0.5", M::HeapTargetUtilization);
238   EXPECT_SINGLE_PARSE_VALUE(5u, "-XX:ParallelGCThreads=5", M::ParallelGCThreads);
239 }  // TEST_F
240 
TEST_F(CmdlineParserTest,TestSimpleFailures)241 TEST_F(CmdlineParserTest, TestSimpleFailures) {
242   // Test argument is unknown to the parser
243   EXPECT_SINGLE_PARSE_FAIL("abcdefg^%@#*(@#", CmdlineResult::kUnknown);
244   // Test value map substitution fails
245   EXPECT_SINGLE_PARSE_FAIL("-Xverify:whatever", CmdlineResult::kFailure);
246   // Test value type parsing failures
247   EXPECT_SINGLE_PARSE_FAIL("-Xsswhatever", CmdlineResult::kFailure);  // invalid memory value
248   EXPECT_SINGLE_PARSE_FAIL("-Xms123", CmdlineResult::kFailure);       // memory value too small
249   EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=0.0", CmdlineResult::kOutOfRange);  // toosmal
250   EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=2.0", CmdlineResult::kOutOfRange);  // toolarg
251   EXPECT_SINGLE_PARSE_FAIL("-XX:ParallelGCThreads=-5", CmdlineResult::kOutOfRange);  // too small
252   EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage);  // not a valid suboption
253 }  // TEST_F
254 
TEST_F(CmdlineParserTest,TestLogVerbosity)255 TEST_F(CmdlineParserTest, TestLogVerbosity) {
256   {
257     const char* log_args = "-verbose:"
258         "class,compiler,gc,heap,interpreter,jdwp,jni,monitor,profiler,signals,simulator,startup,"
259         "third-party-jni,threads,verifier,verifier-debug";
260 
261     LogVerbosity log_verbosity = LogVerbosity();
262     log_verbosity.class_linker = true;
263     log_verbosity.compiler = true;
264     log_verbosity.gc = true;
265     log_verbosity.heap = true;
266     log_verbosity.interpreter = true;
267     log_verbosity.jdwp = true;
268     log_verbosity.jni = true;
269     log_verbosity.monitor = true;
270     log_verbosity.profiler = true;
271     log_verbosity.signals = true;
272     log_verbosity.simulator = true;
273     log_verbosity.startup = true;
274     log_verbosity.third_party_jni = true;
275     log_verbosity.threads = true;
276     log_verbosity.verifier = true;
277     log_verbosity.verifier_debug = true;
278 
279     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
280   }
281 
282   {
283     const char* log_args = "-verbose:"
284         "class,compiler,gc,heap,jdwp,jni,monitor";
285 
286     LogVerbosity log_verbosity = LogVerbosity();
287     log_verbosity.class_linker = true;
288     log_verbosity.compiler = true;
289     log_verbosity.gc = true;
290     log_verbosity.heap = true;
291     log_verbosity.jdwp = true;
292     log_verbosity.jni = true;
293     log_verbosity.monitor = true;
294 
295     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
296   }
297 
298   EXPECT_SINGLE_PARSE_FAIL("-verbose:blablabla", CmdlineResult::kUsage);  // invalid verbose opt
299 
300   {
301     const char* log_args = "-verbose:deopt";
302     LogVerbosity log_verbosity = LogVerbosity();
303     log_verbosity.deopt = true;
304     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
305   }
306 
307   {
308     const char* log_args = "-verbose:collector";
309     LogVerbosity log_verbosity = LogVerbosity();
310     log_verbosity.collector = true;
311     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
312   }
313 
314   {
315     const char* log_args = "-verbose:oat";
316     LogVerbosity log_verbosity = LogVerbosity();
317     log_verbosity.oat = true;
318     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
319   }
320 
321   {
322     const char* log_args = "-verbose:dex";
323     LogVerbosity log_verbosity = LogVerbosity();
324     log_verbosity.dex = true;
325     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
326   }
327 }  // TEST_F
328 
329 // TODO: Enable this b/19274810
TEST_F(CmdlineParserTest,DISABLED_TestXGcOption)330 TEST_F(CmdlineParserTest, DISABLED_TestXGcOption) {
331   /*
332    * Test success
333    */
334   {
335     XGcOption option_all_true{};
336     option_all_true.collector_type_ = gc::CollectorType::kCollectorTypeCMS;
337     option_all_true.verify_pre_gc_heap_ = true;
338     option_all_true.verify_pre_sweeping_heap_ = true;
339     option_all_true.verify_post_gc_heap_ = true;
340     option_all_true.verify_pre_gc_rosalloc_ = true;
341     option_all_true.verify_pre_sweeping_rosalloc_ = true;
342     option_all_true.verify_post_gc_rosalloc_ = true;
343 
344     const char * xgc_args_all_true = "-Xgc:concurrent,"
345         "preverify,presweepingverify,postverify,"
346         "preverify_rosalloc,presweepingverify_rosalloc,"
347         "postverify_rosalloc,precise,"
348         "verifycardtable";
349 
350     EXPECT_SINGLE_PARSE_VALUE(option_all_true, xgc_args_all_true, M::GcOption);
351 
352     XGcOption option_all_false{};
353     option_all_false.collector_type_ = gc::CollectorType::kCollectorTypeMS;
354     option_all_false.verify_pre_gc_heap_ = false;
355     option_all_false.verify_pre_sweeping_heap_ = false;
356     option_all_false.verify_post_gc_heap_ = false;
357     option_all_false.verify_pre_gc_rosalloc_ = false;
358     option_all_false.verify_pre_sweeping_rosalloc_ = false;
359     option_all_false.verify_post_gc_rosalloc_ = false;
360 
361     const char* xgc_args_all_false = "-Xgc:nonconcurrent,"
362         "nopreverify,nopresweepingverify,nopostverify,nopreverify_rosalloc,"
363         "nopresweepingverify_rosalloc,nopostverify_rosalloc,noprecise,noverifycardtable";
364 
365     EXPECT_SINGLE_PARSE_VALUE(option_all_false, xgc_args_all_false, M::GcOption);
366 
367     XGcOption option_all_default{};
368 
369     const char* xgc_args_blank = "-Xgc:";
370     EXPECT_SINGLE_PARSE_VALUE(option_all_default, xgc_args_blank, M::GcOption);
371   }
372 
373   /*
374    * Test failures
375    */
376   EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage);  // invalid Xgc opt
377 }  // TEST_F
378 
379 /*
380  * { "-XjdwpProvider:_" }
381  */
TEST_F(CmdlineParserTest,TestJdwpProviderEmpty)382 TEST_F(CmdlineParserTest, TestJdwpProviderEmpty) {
383   {
384     EXPECT_SINGLE_PARSE_DEFAULT_VALUE(JdwpProvider::kUnset, "", M::JdwpProvider);
385   }
386 }  // TEST_F
387 
TEST_F(CmdlineParserTest,TestJdwpProviderDefault)388 TEST_F(CmdlineParserTest, TestJdwpProviderDefault) {
389   const char* opt_args = "-XjdwpProvider:default";
390   EXPECT_SINGLE_PARSE_VALUE(JdwpProvider::kDefaultJdwpProvider, opt_args, M::JdwpProvider);
391 }  // TEST_F
392 
TEST_F(CmdlineParserTest,TestJdwpProviderNone)393 TEST_F(CmdlineParserTest, TestJdwpProviderNone) {
394   const char* opt_args = "-XjdwpProvider:none";
395   EXPECT_SINGLE_PARSE_VALUE(JdwpProvider::kNone, opt_args, M::JdwpProvider);
396 }  // TEST_F
397 
TEST_F(CmdlineParserTest,TestJdwpProviderAdbconnection)398 TEST_F(CmdlineParserTest, TestJdwpProviderAdbconnection) {
399   const char* opt_args = "-XjdwpProvider:adbconnection";
400   EXPECT_SINGLE_PARSE_VALUE(JdwpProvider::kAdbConnection, opt_args, M::JdwpProvider);
401 }  // TEST_F
402 
TEST_F(CmdlineParserTest,TestJdwpProviderHelp)403 TEST_F(CmdlineParserTest, TestJdwpProviderHelp) {
404   EXPECT_SINGLE_PARSE_FAIL("-XjdwpProvider:help", CmdlineResult::kUsage);
405 }  // TEST_F
406 
TEST_F(CmdlineParserTest,TestJdwpProviderFail)407 TEST_F(CmdlineParserTest, TestJdwpProviderFail) {
408   EXPECT_SINGLE_PARSE_FAIL("-XjdwpProvider:blablabla", CmdlineResult::kFailure);
409 }  // TEST_F
410 
411 /*
412  * -D_ -D_ -D_ ...
413  */
TEST_F(CmdlineParserTest,TestPropertiesList)414 TEST_F(CmdlineParserTest, TestPropertiesList) {
415   /*
416    * Test successes
417    */
418   {
419     std::vector<std::string> opt = {"hello"};
420 
421     EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello", M::PropertiesList);
422   }
423 
424   {
425     std::vector<std::string> opt = {"hello", "world"};
426 
427     EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello -Dworld", M::PropertiesList);
428   }
429 
430   {
431     std::vector<std::string> opt = {"one", "two", "three"};
432 
433     EXPECT_SINGLE_PARSE_VALUE(opt, "-Done -Dtwo -Dthree", M::PropertiesList);
434   }
435 }  // TEST_F
436 
437 /*
438 * -Xcompiler-option foo -Xcompiler-option bar ...
439 */
TEST_F(CmdlineParserTest,TestCompilerOption)440 TEST_F(CmdlineParserTest, TestCompilerOption) {
441  /*
442   * Test successes
443   */
444   {
445     std::vector<std::string> opt = {"hello"};
446     EXPECT_SINGLE_PARSE_VALUE(opt, "-Xcompiler-option hello", M::CompilerOptions);
447   }
448 
449   {
450     std::vector<std::string> opt = {"hello", "world"};
451     EXPECT_SINGLE_PARSE_VALUE(opt,
452                               "-Xcompiler-option hello -Xcompiler-option world",
453                               M::CompilerOptions);
454   }
455 
456   {
457     std::vector<std::string> opt = {"one", "two", "three"};
458     EXPECT_SINGLE_PARSE_VALUE(opt,
459                               "-Xcompiler-option one -Xcompiler-option two -Xcompiler-option three",
460                               M::CompilerOptions);
461   }
462 }  // TEST_F
463 
464 /*
465 * -Xjit, -Xnojit, -Xjitcodecachesize, Xjitcompilethreshold
466 */
TEST_F(CmdlineParserTest,TestJitOptions)467 TEST_F(CmdlineParserTest, TestJitOptions) {
468  /*
469   * Test successes
470   */
471   {
472     EXPECT_SINGLE_PARSE_VALUE(true, "-Xusejit:true", M::UseJitCompilation);
473     EXPECT_SINGLE_PARSE_VALUE(false, "-Xusejit:false", M::UseJitCompilation);
474   }
475   {
476     EXPECT_SINGLE_PARSE_VALUE(
477         MemoryKiB(16 * KB), "-Xjitinitialsize:16K", M::JITCodeCacheInitialCapacity);
478     EXPECT_SINGLE_PARSE_VALUE(
479         MemoryKiB(16 * MB), "-Xjitmaxsize:16M", M::JITCodeCacheMaxCapacity);
480   }
481   {
482     EXPECT_SINGLE_PARSE_VALUE(12345u, "-Xjitthreshold:12345", M::JITCompileThreshold);
483   }
484 }  // TEST_F
485 
486 /*
487 * -Xps-*
488 */
TEST_F(CmdlineParserTest,ProfileSaverOptions)489 TEST_F(CmdlineParserTest, ProfileSaverOptions) {
490   ProfileSaverOptions opt = ProfileSaverOptions(true, 1, 2, 3, 4, 5, 6, 7, 8, "abc", true);
491 
492   EXPECT_SINGLE_PARSE_VALUE(opt,
493                             "-Xjitsaveprofilinginfo "
494                             "-Xps-min-save-period-ms:1 "
495                             "-Xps-min-first-save-ms:2 "
496                             "-Xps-save-resolved-classes-delay-ms:3 "
497                             "-Xps-hot-startup-method-samples:4 "
498                             "-Xps-min-methods-to-save:5 "
499                             "-Xps-min-classes-to-save:6 "
500                             "-Xps-min-notification-before-wake:7 "
501                             "-Xps-max-notification-before-wake:8 "
502                             "-Xps-profile-path:abc "
503                             "-Xps-profile-boot-class-path",
504                             M::ProfileSaverOpts);
505 }  // TEST_F
506 
507 /* -Xexperimental:_ */
TEST_F(CmdlineParserTest,TestExperimentalFlags)508 TEST_F(CmdlineParserTest, TestExperimentalFlags) {
509   // Default
510   EXPECT_SINGLE_PARSE_DEFAULT_VALUE(ExperimentalFlags::kNone,
511                                     "",
512                                     M::Experimental);
513 
514   // Disabled explicitly
515   EXPECT_SINGLE_PARSE_VALUE(ExperimentalFlags::kNone,
516                             "-Xexperimental:none",
517                             M::Experimental);
518 }
519 
520 // -Xverify:_
TEST_F(CmdlineParserTest,TestVerify)521 TEST_F(CmdlineParserTest, TestVerify) {
522   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kNone,     "-Xverify:none",     M::Verify);
523   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kEnable,   "-Xverify:remote",   M::Verify);
524   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kEnable,   "-Xverify:all",      M::Verify);
525   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kSoftFail, "-Xverify:softfail", M::Verify);
526 }
527 
TEST_F(CmdlineParserTest,TestIgnoreUnrecognized)528 TEST_F(CmdlineParserTest, TestIgnoreUnrecognized) {
529   RuntimeParser::Builder parserBuilder;
530 
531   parserBuilder
532       .Define("-help")
533           .IntoKey(M::Help)
534       .IgnoreUnrecognized(true);
535 
536   parser_.reset(new RuntimeParser(parserBuilder.Build()));
537 
538   EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option");
539   EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option1 --non-existent-option-2");
540 }  //  TEST_F
541 
TEST_F(CmdlineParserTest,TestIgnoredArguments)542 TEST_F(CmdlineParserTest, TestIgnoredArguments) {
543   std::initializer_list<const char*> ignored_args = {
544       "-ea", "-da", "-enableassertions", "-disableassertions", "--runtime-arg", "-esa",
545       "-dsa", "-enablesystemassertions", "-disablesystemassertions", "-Xrs", "-Xint:abdef",
546       "-Xdexopt:foobar", "-Xnoquithandler", "-Xjnigreflimit:ixnay", "-Xgenregmap", "-Xnogenregmap",
547       "-Xverifyopt:never", "-Xcheckdexsum", "-Xincludeselectedop", "-Xjitop:noop",
548       "-Xincludeselectedmethod", "-Xjitblocking", "-Xjitmethod:_", "-Xjitclass:nosuchluck",
549       "-Xjitoffset:none", "-Xjitconfig:yes", "-Xjitcheckcg", "-Xjitverbose", "-Xjitprofile",
550       "-Xjitdisableopt", "-Xjitsuspendpoll", "-XX:mainThreadStackSize=1337"
551   };
552 
553   // Check they are ignored when parsed one at a time
554   for (auto&& arg : ignored_args) {
555     SCOPED_TRACE(arg);
556     EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(arg);
557   }
558 
559   // Check they are ignored when we pass it all together at once
560   std::vector<const char*> argv = ignored_args;
561   EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv);
562 }  //  TEST_F
563 
TEST_F(CmdlineParserTest,MultipleArguments)564 TEST_F(CmdlineParserTest, MultipleArguments) {
565   EXPECT_TRUE(IsResultSuccessful(parser_->Parse(
566       "-help -XX:ForegroundHeapGrowthMultiplier=0.5 "
567       "-Xmethod-trace -XX:LargeObjectSpace=map")));
568 
569   auto&& map = parser_->ReleaseArgumentsMap();
570   EXPECT_EQ(4u, map.Size());
571   EXPECT_KEY_VALUE(map, M::Help, Unit{});
572   EXPECT_KEY_VALUE(map, M::ForegroundHeapGrowthMultiplier, 0.5);
573   EXPECT_KEY_VALUE(map, M::MethodTrace, Unit{});
574   EXPECT_KEY_VALUE(map, M::LargeObjectSpace, gc::space::LargeObjectSpaceType::kMap);
575 }  //  TEST_F
576 
TEST_F(CmdlineParserTest,TypesNotInRuntime)577 TEST_F(CmdlineParserTest, TypesNotInRuntime) {
578   CmdlineType<std::vector<int32_t>> ct;
579   auto success0 =
580       CmdlineParseResult<std::vector<int32_t>>::Success(std::vector<int32_t>({1, 2, 3, 4}));
581   EXPECT_EQ(success0, ct.Parse("1,2,3,4"));
582   auto success1 = CmdlineParseResult<std::vector<int32_t>>::Success(std::vector<int32_t>({0}));
583   EXPECT_EQ(success1, ct.Parse("1"));
584 
585   EXPECT_FALSE(ct.Parse("").IsSuccess());
586   EXPECT_FALSE(ct.Parse(",").IsSuccess());
587   EXPECT_FALSE(ct.Parse("1,").IsSuccess());
588   EXPECT_FALSE(ct.Parse(",1").IsSuccess());
589   EXPECT_FALSE(ct.Parse("1a2").IsSuccess());
590   EXPECT_EQ(CmdlineResult::kOutOfRange, ct.Parse("1,10000000000000").GetStatus());
591   EXPECT_EQ(CmdlineResult::kOutOfRange, ct.Parse("-10000000000000,123").GetStatus());
592 }  // TEST_F
593 }  // namespace art
594