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.min_methods_to_save_ == rhs.min_methods_to_save_ &&
42         lhs.min_classes_to_save_ == rhs.min_classes_to_save_ &&
43         lhs.min_notification_before_wake_ == rhs.min_notification_before_wake_ &&
44         lhs.max_notification_before_wake_ == rhs.max_notification_before_wake_;
45   }
46 
UsuallyEquals(double expected,double actual)47   bool UsuallyEquals(double expected, double actual) {
48     using FloatingPoint = ::testing::internal::FloatingPoint<double>;
49 
50     FloatingPoint exp(expected);
51     FloatingPoint act(actual);
52 
53     // Compare with ULPs instead of comparing with ==
54     return exp.AlmostEquals(act);
55   }
56 
57   template <typename T>
UsuallyEquals(const T & expected,const T & actual,typename std::enable_if<detail::SupportsEqualityOperator<T>::value>::type * =nullptr)58   bool UsuallyEquals(const T& expected, const T& actual,
59                      typename std::enable_if<
60                          detail::SupportsEqualityOperator<T>::value>::type* = nullptr) {
61     return expected == actual;
62   }
63 
64   template <char Separator>
UsuallyEquals(const std::vector<std::string> & expected,const ParseStringList<Separator> & actual)65   bool UsuallyEquals(const std::vector<std::string>& expected,
66                      const ParseStringList<Separator>& actual) {
67     return expected == static_cast<std::vector<std::string>>(actual);
68   }
69 
70   // Try to use memcmp to compare simple plain-old-data structs.
71   //
72   // This should *not* generate false positives, but it can generate false negatives.
73   // This will mostly work except for fields like float which can have different bit patterns
74   // that are nevertheless equal.
75   // If a test is failing because the structs aren't "equal" when they really are
76   // then it's recommended to implement operator== for it instead.
77   template <typename T, typename... Ignore>
UsuallyEquals(const T & expected,const T & actual,const Ignore &...more,typename std::enable_if<std::is_pod<T>::value>::type * =nullptr,typename std::enable_if<!detail::SupportsEqualityOperator<T>::value>::type * =nullptr)78   bool UsuallyEquals(
79       const T& expected,
80       const T& actual,
81       [[maybe_unused]] const Ignore&... more,
82       typename std::enable_if<std::is_pod<T>::value>::type* = nullptr,
83       typename std::enable_if<!detail::SupportsEqualityOperator<T>::value>::type* = nullptr) {
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   EXPECT_SINGLE_PARSE_VALUE(10u,
240                             "-XX:ParallelGCThreads=5 -XX:ParallelGCThreads=10",
241                             M::ParallelGCThreads);
242 }  // TEST_F
243 
TEST_F(CmdlineParserTest,TestSimpleFailures)244 TEST_F(CmdlineParserTest, TestSimpleFailures) {
245   // Test argument is unknown to the parser
246   EXPECT_SINGLE_PARSE_FAIL("abcdefg^%@#*(@#", CmdlineResult::kUnknown);
247   // Test value map substitution fails
248   EXPECT_SINGLE_PARSE_FAIL("-Xverify:whatever", CmdlineResult::kFailure);
249   // Test value type parsing failures
250   EXPECT_SINGLE_PARSE_FAIL("-Xsswhatever", CmdlineResult::kFailure);  // invalid memory value
251   EXPECT_SINGLE_PARSE_FAIL("-Xms123", CmdlineResult::kFailure);       // memory value too small
252   EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=0.0", CmdlineResult::kOutOfRange);  // toosmal
253   EXPECT_SINGLE_PARSE_FAIL("-XX:HeapTargetUtilization=2.0", CmdlineResult::kOutOfRange);  // toolarg
254   EXPECT_SINGLE_PARSE_FAIL("-XX:ParallelGCThreads=-5", CmdlineResult::kOutOfRange);  // too small
255   EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage);  // not a valid suboption
256 }  // TEST_F
257 
TEST_F(CmdlineParserTest,TestLogVerbosity)258 TEST_F(CmdlineParserTest, TestLogVerbosity) {
259   {
260     const char* log_args = "-verbose:"
261         "class,compiler,gc,heap,interpreter,jdwp,jni,monitor,profiler,signals,simulator,startup,"
262         "third-party-jni,threads,verifier,verifier-debug";
263 
264     LogVerbosity log_verbosity = LogVerbosity();
265     log_verbosity.class_linker = true;
266     log_verbosity.compiler = true;
267     log_verbosity.gc = true;
268     log_verbosity.heap = true;
269     log_verbosity.interpreter = true;
270     log_verbosity.jdwp = true;
271     log_verbosity.jni = true;
272     log_verbosity.monitor = true;
273     log_verbosity.profiler = true;
274     log_verbosity.signals = true;
275     log_verbosity.simulator = true;
276     log_verbosity.startup = true;
277     log_verbosity.third_party_jni = true;
278     log_verbosity.threads = true;
279     log_verbosity.verifier = true;
280     log_verbosity.verifier_debug = true;
281 
282     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
283   }
284 
285   {
286     const char* log_args = "-verbose:"
287         "class,compiler,gc,heap,jdwp,jni,monitor";
288 
289     LogVerbosity log_verbosity = LogVerbosity();
290     log_verbosity.class_linker = true;
291     log_verbosity.compiler = true;
292     log_verbosity.gc = true;
293     log_verbosity.heap = true;
294     log_verbosity.jdwp = true;
295     log_verbosity.jni = true;
296     log_verbosity.monitor = true;
297 
298     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
299   }
300 
301   EXPECT_SINGLE_PARSE_FAIL("-verbose:blablabla", CmdlineResult::kUsage);  // invalid verbose opt
302 
303   {
304     const char* log_args = "-verbose:deopt";
305     LogVerbosity log_verbosity = LogVerbosity();
306     log_verbosity.deopt = true;
307     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
308   }
309 
310   {
311     const char* log_args = "-verbose:collector";
312     LogVerbosity log_verbosity = LogVerbosity();
313     log_verbosity.collector = true;
314     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
315   }
316 
317   {
318     const char* log_args = "-verbose:oat";
319     LogVerbosity log_verbosity = LogVerbosity();
320     log_verbosity.oat = true;
321     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
322   }
323 
324   {
325     const char* log_args = "-verbose:dex";
326     LogVerbosity log_verbosity = LogVerbosity();
327     log_verbosity.dex = true;
328     EXPECT_SINGLE_PARSE_VALUE(log_verbosity, log_args, M::Verbose);
329   }
330 }  // TEST_F
331 
TEST_F(CmdlineParserTest,TestXGcOption)332 TEST_F(CmdlineParserTest, TestXGcOption) {
333   /*
334    * Test success
335    */
336   {
337     XGcOption option_all_true{};
338     option_all_true.collector_type_ = gc::CollectorType::kCollectorTypeCMS;
339     option_all_true.verify_pre_gc_heap_ = true;
340     option_all_true.verify_pre_sweeping_heap_ = true;
341     option_all_true.verify_post_gc_heap_ = true;
342     option_all_true.verify_pre_gc_rosalloc_ = true;
343     option_all_true.verify_pre_sweeping_rosalloc_ = true;
344     option_all_true.verify_post_gc_rosalloc_ = true;
345 
346     const char * xgc_args_all_true = "-Xgc:concurrent,"
347         "preverify,presweepingverify,postverify,"
348         "preverify_rosalloc,presweepingverify_rosalloc,"
349         "postverify_rosalloc,precise,"
350         "verifycardtable";
351 
352     EXPECT_SINGLE_PARSE_VALUE(option_all_true, xgc_args_all_true, M::GcOption);
353 
354     XGcOption option_all_false{};
355     option_all_false.collector_type_ = gc::CollectorType::kCollectorTypeMS;
356     option_all_false.verify_pre_gc_heap_ = false;
357     option_all_false.verify_pre_sweeping_heap_ = false;
358     option_all_false.verify_post_gc_heap_ = false;
359     option_all_false.verify_pre_gc_rosalloc_ = false;
360     option_all_false.verify_pre_sweeping_rosalloc_ = false;
361     option_all_false.verify_post_gc_rosalloc_ = false;
362 
363     const char* xgc_args_all_false = "-Xgc:nonconcurrent,"
364         "nopreverify,nopresweepingverify,nopostverify,nopreverify_rosalloc,"
365         "nopresweepingverify_rosalloc,nopostverify_rosalloc,noprecise,noverifycardtable";
366 
367     EXPECT_SINGLE_PARSE_VALUE(option_all_false, xgc_args_all_false, M::GcOption);
368 
369     XGcOption option_all_default{};
370 
371     const char* xgc_args_blank = "-Xgc:";
372     EXPECT_SINGLE_PARSE_VALUE(option_all_default, xgc_args_blank, M::GcOption);
373   }
374 
375   /*
376    * Test failures
377    */
378   EXPECT_SINGLE_PARSE_FAIL("-Xgc:blablabla", CmdlineResult::kUsage);  // invalid Xgc opt
379 }  // TEST_F
380 
381 /*
382  * { "-XjdwpProvider:_" }
383  */
TEST_F(CmdlineParserTest,TestJdwpProviderEmpty)384 TEST_F(CmdlineParserTest, TestJdwpProviderEmpty) {
385   {
386     EXPECT_SINGLE_PARSE_DEFAULT_VALUE(JdwpProvider::kUnset, "", M::JdwpProvider);
387   }
388 }  // TEST_F
389 
TEST_F(CmdlineParserTest,TestJdwpProviderDefault)390 TEST_F(CmdlineParserTest, TestJdwpProviderDefault) {
391   const char* opt_args = "-XjdwpProvider:default";
392   EXPECT_SINGLE_PARSE_VALUE(JdwpProvider::kDefaultJdwpProvider, opt_args, M::JdwpProvider);
393 }  // TEST_F
394 
TEST_F(CmdlineParserTest,TestJdwpProviderNone)395 TEST_F(CmdlineParserTest, TestJdwpProviderNone) {
396   const char* opt_args = "-XjdwpProvider:none";
397   EXPECT_SINGLE_PARSE_VALUE(JdwpProvider::kNone, opt_args, M::JdwpProvider);
398 }  // TEST_F
399 
TEST_F(CmdlineParserTest,TestJdwpProviderAdbconnection)400 TEST_F(CmdlineParserTest, TestJdwpProviderAdbconnection) {
401   const char* opt_args = "-XjdwpProvider:adbconnection";
402   EXPECT_SINGLE_PARSE_VALUE(JdwpProvider::kAdbConnection, opt_args, M::JdwpProvider);
403 }  // TEST_F
404 
TEST_F(CmdlineParserTest,TestJdwpProviderHelp)405 TEST_F(CmdlineParserTest, TestJdwpProviderHelp) {
406   EXPECT_SINGLE_PARSE_FAIL("-XjdwpProvider:help", CmdlineResult::kUsage);
407 }  // TEST_F
408 
TEST_F(CmdlineParserTest,TestJdwpProviderFail)409 TEST_F(CmdlineParserTest, TestJdwpProviderFail) {
410   EXPECT_SINGLE_PARSE_FAIL("-XjdwpProvider:blablabla", CmdlineResult::kFailure);
411 }  // TEST_F
412 
413 /*
414  * -D_ -D_ -D_ ...
415  */
TEST_F(CmdlineParserTest,TestPropertiesList)416 TEST_F(CmdlineParserTest, TestPropertiesList) {
417   /*
418    * Test successes
419    */
420   {
421     std::vector<std::string> opt = {"hello"};
422 
423     EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello", M::PropertiesList);
424   }
425 
426   {
427     std::vector<std::string> opt = {"hello", "world"};
428 
429     EXPECT_SINGLE_PARSE_VALUE(opt, "-Dhello -Dworld", M::PropertiesList);
430   }
431 
432   {
433     std::vector<std::string> opt = {"one", "two", "three"};
434 
435     EXPECT_SINGLE_PARSE_VALUE(opt, "-Done -Dtwo -Dthree", M::PropertiesList);
436   }
437 }  // TEST_F
438 
439 /*
440 * -Xcompiler-option foo -Xcompiler-option bar ...
441 */
TEST_F(CmdlineParserTest,TestCompilerOption)442 TEST_F(CmdlineParserTest, TestCompilerOption) {
443  /*
444   * Test successes
445   */
446   {
447     std::vector<std::string> opt = {"hello"};
448     EXPECT_SINGLE_PARSE_VALUE(opt, "-Xcompiler-option hello", M::CompilerOptions);
449   }
450 
451   {
452     std::vector<std::string> opt = {"hello", "world"};
453     EXPECT_SINGLE_PARSE_VALUE(opt,
454                               "-Xcompiler-option hello -Xcompiler-option world",
455                               M::CompilerOptions);
456   }
457 
458   {
459     std::vector<std::string> opt = {"one", "two", "three"};
460     EXPECT_SINGLE_PARSE_VALUE(opt,
461                               "-Xcompiler-option one -Xcompiler-option two -Xcompiler-option three",
462                               M::CompilerOptions);
463   }
464 }  // TEST_F
465 
466 /*
467 * -Xjit, -Xnojit, -Xjitcodecachesize, Xjitcompilethreshold
468 */
TEST_F(CmdlineParserTest,TestJitOptions)469 TEST_F(CmdlineParserTest, TestJitOptions) {
470  /*
471   * Test successes
472   */
473   {
474     EXPECT_SINGLE_PARSE_VALUE(true, "-Xusejit:true", M::UseJitCompilation);
475     EXPECT_SINGLE_PARSE_VALUE(false, "-Xusejit:false", M::UseJitCompilation);
476   }
477   {
478     EXPECT_SINGLE_PARSE_VALUE(
479         MemoryKiB(16 * KB), "-Xjitinitialsize:16K", M::JITCodeCacheInitialCapacity);
480     EXPECT_SINGLE_PARSE_VALUE(
481         MemoryKiB(16 * MB), "-Xjitmaxsize:16M", M::JITCodeCacheMaxCapacity);
482   }
483   {
484     EXPECT_SINGLE_PARSE_VALUE(12345u, "-Xjitthreshold:12345", M::JITOptimizeThreshold);
485   }
486 }  // TEST_F
487 
488 /*
489 * -Xps-*
490 */
TEST_F(CmdlineParserTest,ProfileSaverOptions)491 TEST_F(CmdlineParserTest, ProfileSaverOptions) {
492   ProfileSaverOptions opt = ProfileSaverOptions(true, 1, 2, 3, 4, 5, 6, 7, 8, "abc", true);
493 
494   EXPECT_SINGLE_PARSE_VALUE(opt,
495                             "-Xjitsaveprofilinginfo "
496                             "-Xps-min-save-period-ms:1 "
497                             "-Xps-min-first-save-ms:2 "
498                             "-Xps-save-resolved-classes-delay-ms:3 "
499                             "-Xps-min-methods-to-save:4 "
500                             "-Xps-min-classes-to-save:5 "
501                             "-Xps-min-notification-before-wake:6 "
502                             "-Xps-max-notification-before-wake:7 "
503                             "-Xps-inline-cache-threshold:8 "
504                             "-Xps-profile-path:abc "
505                             "-Xps-profile-boot-class-path",
506                             M::ProfileSaverOpts);
507 }  // TEST_F
508 
509 /* -Xexperimental:_ */
TEST_F(CmdlineParserTest,TestExperimentalFlags)510 TEST_F(CmdlineParserTest, TestExperimentalFlags) {
511   // Default
512   EXPECT_SINGLE_PARSE_DEFAULT_VALUE(ExperimentalFlags::kNone,
513                                     "",
514                                     M::Experimental);
515 
516   // Disabled explicitly
517   EXPECT_SINGLE_PARSE_VALUE(ExperimentalFlags::kNone,
518                             "-Xexperimental:none",
519                             M::Experimental);
520 }
521 
522 // -Xverify:_
TEST_F(CmdlineParserTest,TestVerify)523 TEST_F(CmdlineParserTest, TestVerify) {
524   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kNone,     "-Xverify:none",     M::Verify);
525   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kEnable,   "-Xverify:remote",   M::Verify);
526   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kEnable,   "-Xverify:all",      M::Verify);
527   EXPECT_SINGLE_PARSE_VALUE(verifier::VerifyMode::kSoftFail, "-Xverify:softfail", M::Verify);
528 }
529 
TEST_F(CmdlineParserTest,TestIgnoreUnrecognized)530 TEST_F(CmdlineParserTest, TestIgnoreUnrecognized) {
531   RuntimeParser::Builder parserBuilder;
532 
533   // clang-format off
534   parserBuilder
535       .Define("-help")
536           .IntoKey(M::Help)
537       .IgnoreUnrecognized(true);
538   // clang-format on
539 
540   parser_.reset(new RuntimeParser(parserBuilder.Build()));
541 
542   EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option");
543   EXPECT_SINGLE_PARSE_EMPTY_SUCCESS("-non-existent-option1 --non-existent-option-2");
544 }  //  TEST_F
545 
TEST_F(CmdlineParserTest,TestIgnoredArguments)546 TEST_F(CmdlineParserTest, TestIgnoredArguments) {
547   std::initializer_list<const char*> ignored_args = {
548       "-ea", "-da", "-enableassertions", "-disableassertions", "--runtime-arg", "-esa",
549       "-dsa", "-enablesystemassertions", "-disablesystemassertions", "-Xrs", "-Xint:abdef",
550       "-Xdexopt:foobar", "-Xnoquithandler", "-Xjnigreflimit:ixnay", "-Xgenregmap", "-Xnogenregmap",
551       "-Xverifyopt:never", "-Xcheckdexsum", "-Xincludeselectedop", "-Xjitop:noop",
552       "-Xincludeselectedmethod", "-Xjitblocking", "-Xjitmethod:_", "-Xjitclass:nosuchluck",
553       "-Xjitoffset:none", "-Xjitconfig:yes", "-Xjitcheckcg", "-Xjitverbose", "-Xjitprofile",
554       "-Xjitdisableopt", "-Xjitsuspendpoll", "-XX:mainThreadStackSize=1337"
555   };
556 
557   // Check they are ignored when parsed one at a time
558   for (auto&& arg : ignored_args) {
559     SCOPED_TRACE(arg);
560     EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(arg);
561   }
562 
563   // Check they are ignored when we pass it all together at once
564   std::vector<const char*> argv = ignored_args;
565   EXPECT_SINGLE_PARSE_EMPTY_SUCCESS(argv);
566 }  //  TEST_F
567 
TEST_F(CmdlineParserTest,MultipleArguments)568 TEST_F(CmdlineParserTest, MultipleArguments) {
569   EXPECT_TRUE(IsResultSuccessful(parser_->Parse(
570       "-help -XX:ForegroundHeapGrowthMultiplier=0.5 "
571       "-Xmethod-trace -XX:LargeObjectSpace=map")));
572 
573   auto&& map = parser_->ReleaseArgumentsMap();
574   EXPECT_EQ(4u, map.Size());
575   EXPECT_KEY_VALUE(map, M::Help, Unit{});
576   EXPECT_KEY_VALUE(map, M::ForegroundHeapGrowthMultiplier, 0.5);
577   EXPECT_KEY_VALUE(map, M::MethodTrace, Unit{});
578   EXPECT_KEY_VALUE(map, M::LargeObjectSpace, gc::space::LargeObjectSpaceType::kMap);
579 }  //  TEST_F
580 
TEST_F(CmdlineParserTest,TypesNotInRuntime)581 TEST_F(CmdlineParserTest, TypesNotInRuntime) {
582   using ParseCommaSeparatedIntList = ParseIntList<','>;
583   CmdlineType<ParseCommaSeparatedIntList> ct;
584   auto success0 =
585       CmdlineParseResult<ParseCommaSeparatedIntList>::Success(ParseCommaSeparatedIntList({1, 2, 3, 4}));
586   EXPECT_EQ(success0, ct.Parse("1,2,3,4"));
587   auto success1 =
588       CmdlineParseResult<ParseCommaSeparatedIntList>::Success(ParseCommaSeparatedIntList({0}));
589   EXPECT_EQ(success1, ct.Parse("1"));
590 
591   EXPECT_FALSE(ct.Parse("").IsSuccess());
592   EXPECT_FALSE(ct.Parse(",").IsSuccess());
593   EXPECT_FALSE(ct.Parse("1,").IsSuccess());
594   EXPECT_FALSE(ct.Parse(",1").IsSuccess());
595   EXPECT_FALSE(ct.Parse("1a2").IsSuccess());
596   EXPECT_EQ(CmdlineResult::kOutOfRange, ct.Parse("1,10000000000000").GetStatus());
597   EXPECT_EQ(CmdlineResult::kOutOfRange, ct.Parse("-10000000000000,123").GetStatus());
598 }  // TEST_F
599 }  // namespace art
600