parsed_options.cc revision 455820e1fd233a65a10675d380fe6620b5ec2730
1/*
2 * Copyright (C) 2011 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 "parsed_options.h"
18#ifdef HAVE_ANDROID_OS
19#include "cutils/properties.h"
20#endif
21
22#include "debugger.h"
23#include "monitor.h"
24
25namespace art {
26
27ParsedOptions* ParsedOptions::Create(const Runtime::Options& options, bool ignore_unrecognized) {
28  UniquePtr<ParsedOptions> parsed(new ParsedOptions());
29  if (parsed->Parse(options, ignore_unrecognized)) {
30    return parsed.release();
31  }
32  return nullptr;
33}
34
35// Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
36// memory sizes.  [kK] indicates kilobytes, [mM] megabytes, and
37// [gG] gigabytes.
38//
39// "s" should point just past the "-Xm?" part of the string.
40// "div" specifies a divisor, e.g. 1024 if the value must be a multiple
41// of 1024.
42//
43// The spec says the -Xmx and -Xms options must be multiples of 1024.  It
44// doesn't say anything about -Xss.
45//
46// Returns 0 (a useless size) if "s" is malformed or specifies a low or
47// non-evenly-divisible value.
48//
49size_t ParseMemoryOption(const char* s, size_t div) {
50  // strtoul accepts a leading [+-], which we don't want,
51  // so make sure our string starts with a decimal digit.
52  if (isdigit(*s)) {
53    char* s2;
54    size_t val = strtoul(s, &s2, 10);
55    if (s2 != s) {
56      // s2 should be pointing just after the number.
57      // If this is the end of the string, the user
58      // has specified a number of bytes.  Otherwise,
59      // there should be exactly one more character
60      // that specifies a multiplier.
61      if (*s2 != '\0') {
62        // The remainder of the string is either a single multiplier
63        // character, or nothing to indicate that the value is in
64        // bytes.
65        char c = *s2++;
66        if (*s2 == '\0') {
67          size_t mul;
68          if (c == '\0') {
69            mul = 1;
70          } else if (c == 'k' || c == 'K') {
71            mul = KB;
72          } else if (c == 'm' || c == 'M') {
73            mul = MB;
74          } else if (c == 'g' || c == 'G') {
75            mul = GB;
76          } else {
77            // Unknown multiplier character.
78            return 0;
79          }
80
81          if (val <= std::numeric_limits<size_t>::max() / mul) {
82            val *= mul;
83          } else {
84            // Clamp to a multiple of 1024.
85            val = std::numeric_limits<size_t>::max() & ~(1024-1);
86          }
87        } else {
88          // There's more than one character after the numeric part.
89          return 0;
90        }
91      }
92      // The man page says that a -Xm value must be a multiple of 1024.
93      if (val % div == 0) {
94        return val;
95      }
96    }
97  }
98  return 0;
99}
100
101static gc::CollectorType ParseCollectorType(const std::string& option) {
102  if (option == "MS" || option == "nonconcurrent") {
103    return gc::kCollectorTypeMS;
104  } else if (option == "CMS" || option == "concurrent") {
105    return gc::kCollectorTypeCMS;
106  } else if (option == "SS") {
107    return gc::kCollectorTypeSS;
108  } else if (option == "GSS") {
109    return gc::kCollectorTypeGSS;
110  } else if (option == "CC") {
111    return gc::kCollectorTypeCC;
112  } else {
113    return gc::kCollectorTypeNone;
114  }
115}
116
117bool ParsedOptions::Parse(const Runtime::Options& options, bool ignore_unrecognized) {
118  const char* boot_class_path_string = getenv("BOOTCLASSPATH");
119  if (boot_class_path_string != NULL) {
120    boot_class_path_string_ = boot_class_path_string;
121  }
122  const char* class_path_string = getenv("CLASSPATH");
123  if (class_path_string != NULL) {
124    class_path_string_ = class_path_string;
125  }
126  // -Xcheck:jni is off by default for regular builds but on by default in debug builds.
127  check_jni_ = kIsDebugBuild;
128
129  heap_initial_size_ = gc::Heap::kDefaultInitialSize;
130  heap_maximum_size_ = gc::Heap::kDefaultMaximumSize;
131  heap_min_free_ = gc::Heap::kDefaultMinFree;
132  heap_max_free_ = gc::Heap::kDefaultMaxFree;
133  heap_target_utilization_ = gc::Heap::kDefaultTargetUtilization;
134  foreground_heap_growth_multiplier_ = gc::Heap::kDefaultHeapGrowthMultiplier;
135  heap_growth_limit_ = 0;  // 0 means no growth limit .
136  // Default to number of processors minus one since the main GC thread also does work.
137  parallel_gc_threads_ = sysconf(_SC_NPROCESSORS_CONF) - 1;
138  // Only the main GC thread, no workers.
139  conc_gc_threads_ = 0;
140  // Default is CMS which is Sticky + Partial + Full CMS GC.
141  collector_type_ = gc::kCollectorTypeCMS;
142  // If background_collector_type_ is kCollectorTypeNone, it defaults to the collector_type_ after
143  // parsing options.
144  background_collector_type_ = gc::kCollectorTypeNone;
145  stack_size_ = 0;  // 0 means default.
146  max_spins_before_thin_lock_inflation_ = Monitor::kDefaultMaxSpinsBeforeThinLockInflation;
147  low_memory_mode_ = false;
148  use_tlab_ = false;
149  verify_pre_gc_heap_ = false;
150  verify_post_gc_heap_ = kIsDebugBuild;
151  verify_pre_gc_rosalloc_ = kIsDebugBuild;
152  verify_post_gc_rosalloc_ = false;
153
154  compiler_callbacks_ = nullptr;
155  is_zygote_ = false;
156  if (kPoisonHeapReferences) {
157    // kPoisonHeapReferences currently works only with the interpreter only.
158    // TODO: make it work with the compiler.
159    interpreter_only_ = true;
160  } else {
161    interpreter_only_ = false;
162  }
163  is_explicit_gc_disabled_ = false;
164
165  long_pause_log_threshold_ = gc::Heap::kDefaultLongPauseLogThreshold;
166  long_gc_log_threshold_ = gc::Heap::kDefaultLongGCLogThreshold;
167  dump_gc_performance_on_shutdown_ = false;
168  ignore_max_footprint_ = false;
169
170  lock_profiling_threshold_ = 0;
171  hook_is_sensitive_thread_ = NULL;
172
173  hook_vfprintf_ = vfprintf;
174  hook_exit_ = exit;
175  hook_abort_ = NULL;  // We don't call abort(3) by default; see Runtime::Abort.
176
177//  gLogVerbosity.class_linker = true;  // TODO: don't check this in!
178//  gLogVerbosity.compiler = true;  // TODO: don't check this in!
179//  gLogVerbosity.verifier = true;  // TODO: don't check this in!
180//  gLogVerbosity.heap = true;  // TODO: don't check this in!
181//  gLogVerbosity.gc = true;  // TODO: don't check this in!
182//  gLogVerbosity.jdwp = true;  // TODO: don't check this in!
183//  gLogVerbosity.jni = true;  // TODO: don't check this in!
184//  gLogVerbosity.monitor = true;  // TODO: don't check this in!
185//  gLogVerbosity.startup = true;  // TODO: don't check this in!
186//  gLogVerbosity.third_party_jni = true;  // TODO: don't check this in!
187//  gLogVerbosity.threads = true;  // TODO: don't check this in!
188
189  method_trace_ = false;
190  method_trace_file_ = "/data/method-trace-file.bin";
191  method_trace_file_size_ = 10 * MB;
192
193  profile_ = false;
194  profile_period_s_ = 10;           // Seconds.
195  profile_duration_s_ = 20;          // Seconds.
196  profile_interval_us_ = 500;       // Microseconds.
197  profile_backoff_coefficient_ = 2.0;
198  profile_start_immediately_ = true;
199  profile_clock_source_ = kDefaultProfilerClockSource;
200
201  verify_ = true;
202
203  // Default to explicit checks.  Switch off with -implicit-checks:.
204  // or setprop dalvik.vm.implicit_checks check1,check2,...
205#ifdef HAVE_ANDROID_OS
206  {
207    char buf[PROP_VALUE_MAX];
208    property_get("dalvik.vm.implicit_checks", buf, "none");
209    std::string checks(buf);
210    std::vector<std::string> checkvec;
211    Split(checks, ',', checkvec);
212    explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
213        kExplicitStackOverflowCheck;
214    for (auto& str : checkvec) {
215      std::string val = Trim(str);
216      if (val == "none") {
217        explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
218          kExplicitStackOverflowCheck;
219      } else if (val == "null") {
220        explicit_checks_ &= ~kExplicitNullCheck;
221      } else if (val == "suspend") {
222        explicit_checks_ &= ~kExplicitSuspendCheck;
223      } else if (val == "stack") {
224        explicit_checks_ &= ~kExplicitStackOverflowCheck;
225      } else if (val == "all") {
226        explicit_checks_ = 0;
227      }
228    }
229  }
230#else
231  explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
232    kExplicitStackOverflowCheck;
233#endif
234
235  for (size_t i = 0; i < options.size(); ++i) {
236    if (true && options[0].first == "-Xzygote") {
237      LOG(INFO) << "option[" << i << "]=" << options[i].first;
238    }
239  }
240  for (size_t i = 0; i < options.size(); ++i) {
241    const std::string option(options[i].first);
242    if (StartsWith(option, "-help")) {
243      Usage(nullptr);
244      return false;
245    } else if (StartsWith(option, "-showversion")) {
246      UsageMessage(stdout, "ART version %s\n", Runtime::GetVersion());
247      Exit(0);
248    } else if (StartsWith(option, "-Xbootclasspath:")) {
249      boot_class_path_string_ = option.substr(strlen("-Xbootclasspath:")).data();
250    } else if (option == "-classpath" || option == "-cp") {
251      // TODO: support -Djava.class.path
252      i++;
253      if (i == options.size()) {
254        Usage("Missing required class path value for %s", option.c_str());
255        return false;
256      }
257      const StringPiece& value = options[i].first;
258      class_path_string_ = value.data();
259    } else if (option == "bootclasspath") {
260      boot_class_path_
261          = reinterpret_cast<const std::vector<const DexFile*>*>(options[i].second);
262    } else if (StartsWith(option, "-Ximage:")) {
263      if (!ParseStringAfterChar(option, ':', &image_)) {
264        return false;
265      }
266    } else if (StartsWith(option, "-Xcheck:jni")) {
267      check_jni_ = true;
268    } else if (StartsWith(option, "-Xrunjdwp:") || StartsWith(option, "-agentlib:jdwp=")) {
269      std::string tail(option.substr(option[1] == 'X' ? 10 : 15));
270      // TODO: move parsing logic out of Dbg
271      if (tail == "help" || !Dbg::ParseJdwpOptions(tail)) {
272        if (tail != "help") {
273          UsageMessage(stderr, "Failed to parse JDWP option %s\n", tail.c_str());
274        }
275        Usage("Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
276              "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
277        return false;
278      }
279    } else if (StartsWith(option, "-Xms")) {
280      size_t size = ParseMemoryOption(option.substr(strlen("-Xms")).c_str(), 1024);
281      if (size == 0) {
282        Usage("Failed to parse memory option %s", option.c_str());
283        return false;
284      }
285      heap_initial_size_ = size;
286    } else if (StartsWith(option, "-Xmx")) {
287      size_t size = ParseMemoryOption(option.substr(strlen("-Xmx")).c_str(), 1024);
288      if (size == 0) {
289        Usage("Failed to parse memory option %s", option.c_str());
290        return false;
291      }
292      heap_maximum_size_ = size;
293    } else if (StartsWith(option, "-XX:HeapGrowthLimit=")) {
294      size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapGrowthLimit=")).c_str(), 1024);
295      if (size == 0) {
296        Usage("Failed to parse memory option %s", option.c_str());
297        return false;
298      }
299      heap_growth_limit_ = size;
300    } else if (StartsWith(option, "-XX:HeapMinFree=")) {
301      size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMinFree=")).c_str(), 1024);
302      if (size == 0) {
303        Usage("Failed to parse memory option %s", option.c_str());
304        return false;
305      }
306      heap_min_free_ = size;
307    } else if (StartsWith(option, "-XX:HeapMaxFree=")) {
308      size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMaxFree=")).c_str(), 1024);
309      if (size == 0) {
310        Usage("Failed to parse memory option %s", option.c_str());
311        return false;
312      }
313      heap_max_free_ = size;
314    } else if (StartsWith(option, "-XX:HeapTargetUtilization=")) {
315      if (!ParseDouble(option, '=', 0.1, 0.9, &heap_target_utilization_)) {
316        return false;
317      }
318    } else if (StartsWith(option, "-XX:ForegroundHeapGrowthMultiplier=")) {
319      if (!ParseDouble(option, '=', 0.1, 10.0, &foreground_heap_growth_multiplier_)) {
320        return false;
321      }
322    } else if (StartsWith(option, "-XX:ParallelGCThreads=")) {
323      if (!ParseUnsignedInteger(option, '=', &parallel_gc_threads_)) {
324        return false;
325      }
326    } else if (StartsWith(option, "-XX:ConcGCThreads=")) {
327      if (!ParseUnsignedInteger(option, '=', &conc_gc_threads_)) {
328        return false;
329      }
330    } else if (StartsWith(option, "-Xss")) {
331      size_t size = ParseMemoryOption(option.substr(strlen("-Xss")).c_str(), 1);
332      if (size == 0) {
333        Usage("Failed to parse memory option %s", option.c_str());
334        return false;
335      }
336      stack_size_ = size;
337    } else if (StartsWith(option, "-XX:MaxSpinsBeforeThinLockInflation=")) {
338      if (!ParseUnsignedInteger(option, '=', &max_spins_before_thin_lock_inflation_)) {
339        return false;
340      }
341    } else if (StartsWith(option, "-XX:LongPauseLogThreshold=")) {
342      unsigned int value;
343      if (!ParseUnsignedInteger(option, '=', &value)) {
344        return false;
345      }
346      long_pause_log_threshold_ = MsToNs(value);
347    } else if (StartsWith(option, "-XX:LongGCLogThreshold=")) {
348      unsigned int value;
349      if (!ParseUnsignedInteger(option, '=', &value)) {
350        return false;
351      }
352      long_gc_log_threshold_ = MsToNs(value);
353    } else if (option == "-XX:DumpGCPerformanceOnShutdown") {
354      dump_gc_performance_on_shutdown_ = true;
355    } else if (option == "-XX:IgnoreMaxFootprint") {
356      ignore_max_footprint_ = true;
357    } else if (option == "-XX:LowMemoryMode") {
358      low_memory_mode_ = true;
359    } else if (option == "-XX:UseTLAB") {
360      use_tlab_ = true;
361    } else if (StartsWith(option, "-D")) {
362      properties_.push_back(option.substr(strlen("-D")));
363    } else if (StartsWith(option, "-Xjnitrace:")) {
364      jni_trace_ = option.substr(strlen("-Xjnitrace:"));
365    } else if (option == "compilercallbacks") {
366      compiler_callbacks_ =
367          reinterpret_cast<CompilerCallbacks*>(const_cast<void*>(options[i].second));
368    } else if (option == "-Xzygote") {
369      is_zygote_ = true;
370    } else if (option == "-Xint") {
371      interpreter_only_ = true;
372    } else if (StartsWith(option, "-Xgc:")) {
373      std::vector<std::string> gc_options;
374      Split(option.substr(strlen("-Xgc:")), ',', gc_options);
375      for (const std::string& gc_option : gc_options) {
376        gc::CollectorType collector_type = ParseCollectorType(gc_option);
377        if (collector_type != gc::kCollectorTypeNone) {
378          collector_type_ = collector_type;
379        } else if (gc_option == "preverify") {
380          verify_pre_gc_heap_ = true;
381        } else if (gc_option == "nopreverify") {
382          verify_pre_gc_heap_ = false;
383        }  else if (gc_option == "postverify") {
384          verify_post_gc_heap_ = true;
385        } else if (gc_option == "nopostverify") {
386          verify_post_gc_heap_ = false;
387        } else if (gc_option == "preverify_rosalloc") {
388          verify_pre_gc_rosalloc_ = true;
389        } else if (gc_option == "nopreverify_rosalloc") {
390          verify_pre_gc_rosalloc_ = false;
391        } else if (gc_option == "postverify_rosalloc") {
392          verify_post_gc_rosalloc_ = true;
393        } else if (gc_option == "nopostverify_rosalloc") {
394          verify_post_gc_rosalloc_ = false;
395        } else if ((gc_option == "precise") ||
396                   (gc_option == "noprecise") ||
397                   (gc_option == "verifycardtable") ||
398                   (gc_option == "noverifycardtable")) {
399          // Ignored for backwards compatibility.
400        } else {
401          Usage("Unknown -Xgc option %s", gc_option.c_str());
402          return false;
403        }
404      }
405    } else if (StartsWith(option, "-XX:BackgroundGC=")) {
406      std::string substring;
407      if (!ParseStringAfterChar(option, '=', &substring)) {
408        return false;
409      }
410      gc::CollectorType collector_type = ParseCollectorType(substring);
411      if (collector_type != gc::kCollectorTypeNone) {
412        background_collector_type_ = collector_type;
413      } else {
414        Usage("Unknown -XX:BackgroundGC option %s", substring.c_str());
415        return false;
416      }
417    } else if (option == "-XX:+DisableExplicitGC") {
418      is_explicit_gc_disabled_ = true;
419    } else if (StartsWith(option, "-verbose:")) {
420      std::vector<std::string> verbose_options;
421      Split(option.substr(strlen("-verbose:")), ',', verbose_options);
422      for (size_t i = 0; i < verbose_options.size(); ++i) {
423        if (verbose_options[i] == "class") {
424          gLogVerbosity.class_linker = true;
425        } else if (verbose_options[i] == "verifier") {
426          gLogVerbosity.verifier = true;
427        } else if (verbose_options[i] == "compiler") {
428          gLogVerbosity.compiler = true;
429        } else if (verbose_options[i] == "heap") {
430          gLogVerbosity.heap = true;
431        } else if (verbose_options[i] == "gc") {
432          gLogVerbosity.gc = true;
433        } else if (verbose_options[i] == "jdwp") {
434          gLogVerbosity.jdwp = true;
435        } else if (verbose_options[i] == "jni") {
436          gLogVerbosity.jni = true;
437        } else if (verbose_options[i] == "monitor") {
438          gLogVerbosity.monitor = true;
439        } else if (verbose_options[i] == "startup") {
440          gLogVerbosity.startup = true;
441        } else if (verbose_options[i] == "third-party-jni") {
442          gLogVerbosity.third_party_jni = true;
443        } else if (verbose_options[i] == "threads") {
444          gLogVerbosity.threads = true;
445        } else {
446          Usage("Unknown -verbose option %s", verbose_options[i].c_str());
447          return false;
448        }
449      }
450    } else if (StartsWith(option, "-Xlockprofthreshold:")) {
451      if (!ParseUnsignedInteger(option, ':', &lock_profiling_threshold_)) {
452        return false;
453      }
454    } else if (StartsWith(option, "-Xstacktracefile:")) {
455      if (!ParseStringAfterChar(option, ':', &stack_trace_file_)) {
456        return false;
457      }
458    } else if (option == "sensitiveThread") {
459      const void* hook = options[i].second;
460      hook_is_sensitive_thread_ = reinterpret_cast<bool (*)()>(const_cast<void*>(hook));
461    } else if (option == "vfprintf") {
462      const void* hook = options[i].second;
463      if (hook == nullptr) {
464        Usage("vfprintf argument was NULL");
465        return false;
466      }
467      hook_vfprintf_ =
468          reinterpret_cast<int (*)(FILE *, const char*, va_list)>(const_cast<void*>(hook));
469    } else if (option == "exit") {
470      const void* hook = options[i].second;
471      if (hook == nullptr) {
472        Usage("exit argument was NULL");
473        return false;
474      }
475      hook_exit_ = reinterpret_cast<void(*)(jint)>(const_cast<void*>(hook));
476    } else if (option == "abort") {
477      const void* hook = options[i].second;
478      if (hook == nullptr) {
479        Usage("abort was NULL");
480        return false;
481      }
482      hook_abort_ = reinterpret_cast<void(*)()>(const_cast<void*>(hook));
483    } else if (option == "-Xmethod-trace") {
484      method_trace_ = true;
485    } else if (StartsWith(option, "-Xmethod-trace-file:")) {
486      method_trace_file_ = option.substr(strlen("-Xmethod-trace-file:"));
487    } else if (StartsWith(option, "-Xmethod-trace-file-size:")) {
488      if (!ParseUnsignedInteger(option, ':', &method_trace_file_size_)) {
489        return false;
490      }
491    } else if (option == "-Xprofile:threadcpuclock") {
492      Trace::SetDefaultClockSource(kProfilerClockSourceThreadCpu);
493    } else if (option == "-Xprofile:wallclock") {
494      Trace::SetDefaultClockSource(kProfilerClockSourceWall);
495    } else if (option == "-Xprofile:dualclock") {
496      Trace::SetDefaultClockSource(kProfilerClockSourceDual);
497    } else if (StartsWith(option, "-Xprofile:")) {
498      if (!ParseStringAfterChar(option, ';', &profile_output_filename_)) {
499        return false;
500      }
501      profile_ = true;
502    } else if (StartsWith(option, "-Xprofile-period:")) {
503      if (!ParseUnsignedInteger(option, ':', &profile_period_s_)) {
504        return false;
505      }
506    } else if (StartsWith(option, "-Xprofile-duration:")) {
507      if (!ParseUnsignedInteger(option, ':', &profile_duration_s_)) {
508        return false;
509      }
510    } else if (StartsWith(option, "-Xprofile-interval:")) {
511      if (!ParseUnsignedInteger(option, ':', &profile_interval_us_)) {
512        return false;
513      }
514    } else if (StartsWith(option, "-Xprofile-backoff:")) {
515      if (!ParseDouble(option, ':', 1.0, 10.0, &profile_backoff_coefficient_)) {
516        return false;
517      }
518    } else if (option == "-Xprofile-start-lazy") {
519      profile_start_immediately_ = false;
520    } else if (StartsWith(option, "-implicit-checks:")) {
521      std::string checks;
522      if (!ParseStringAfterChar(option, ':', &checks)) {
523        return false;
524      }
525      std::vector<std::string> checkvec;
526      Split(checks, ',', checkvec);
527      for (auto& str : checkvec) {
528        std::string val = Trim(str);
529        if (val == "none") {
530          explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
531            kExplicitStackOverflowCheck;
532        } else if (val == "null") {
533          explicit_checks_ &= ~kExplicitNullCheck;
534        } else if (val == "suspend") {
535          explicit_checks_ &= ~kExplicitSuspendCheck;
536        } else if (val == "stack") {
537          explicit_checks_ &= ~kExplicitStackOverflowCheck;
538        } else if (val == "all") {
539          explicit_checks_ = 0;
540        } else {
541            return false;
542        }
543      }
544    } else if (StartsWith(option, "-explicit-checks:")) {
545      std::string checks;
546      if (!ParseStringAfterChar(option, ':', &checks)) {
547        return false;
548      }
549      std::vector<std::string> checkvec;
550      Split(checks, ',', checkvec);
551      for (auto& str : checkvec) {
552        std::string val = Trim(str);
553        if (val == "none") {
554          explicit_checks_ = 0;
555        } else if (val == "null") {
556          explicit_checks_ |= kExplicitNullCheck;
557        } else if (val == "suspend") {
558          explicit_checks_ |= kExplicitSuspendCheck;
559        } else if (val == "stack") {
560          explicit_checks_ |= kExplicitStackOverflowCheck;
561        } else if (val == "all") {
562          explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
563            kExplicitStackOverflowCheck;
564        } else {
565          return false;
566        }
567      }
568    } else if (option == "-Xcompiler-option") {
569      i++;
570      if (i == options.size()) {
571        Usage("Missing required compiler option for %s", option.c_str());
572        return false;
573      }
574      compiler_options_.push_back(options[i].first);
575    } else if (option == "-Ximage-compiler-option") {
576      i++;
577      if (i == options.size()) {
578        Usage("Missing required compiler option for %s", option.c_str());
579        return false;
580      }
581      image_compiler_options_.push_back(options[i].first);
582    } else if (StartsWith(option, "-Xverify:")) {
583      std::string verify_mode = option.substr(strlen("-Xverify:"));
584      if (verify_mode == "none") {
585        verify_ = false;
586      } else if (verify_mode == "remote" || verify_mode == "all") {
587        verify_ = true;
588      } else {
589        Usage("Unknown -Xverify option %s", verify_mode.c_str());
590        return false;
591      }
592    } else if (StartsWith(option, "-ea") ||
593               StartsWith(option, "-da") ||
594               StartsWith(option, "-enableassertions") ||
595               StartsWith(option, "-disableassertions") ||
596               (option == "--runtime-arg") ||
597               (option == "-esa") ||
598               (option == "-dsa") ||
599               (option == "-enablesystemassertions") ||
600               (option == "-disablesystemassertions") ||
601               (option == "-Xrs") ||
602               StartsWith(option, "-Xint:") ||
603               StartsWith(option, "-Xdexopt:") ||
604               (option == "-Xnoquithandler") ||
605               StartsWith(option, "-Xjniopts:") ||
606               StartsWith(option, "-Xjnigreflimit:") ||
607               (option == "-Xgenregmap") ||
608               (option == "-Xnogenregmap") ||
609               StartsWith(option, "-Xverifyopt:") ||
610               (option == "-Xcheckdexsum") ||
611               (option == "-Xincludeselectedop") ||
612               StartsWith(option, "-Xjitop:") ||
613               (option == "-Xincludeselectedmethod") ||
614               StartsWith(option, "-Xjitthreshold:") ||
615               StartsWith(option, "-Xjitcodecachesize:") ||
616               (option == "-Xjitblocking") ||
617               StartsWith(option, "-Xjitmethod:") ||
618               StartsWith(option, "-Xjitclass:") ||
619               StartsWith(option, "-Xjitoffset:") ||
620               StartsWith(option, "-Xjitconfig:") ||
621               (option == "-Xjitcheckcg") ||
622               (option == "-Xjitverbose") ||
623               (option == "-Xjitprofile") ||
624               (option == "-Xjitdisableopt") ||
625               (option == "-Xjitsuspendpoll") ||
626               StartsWith(option, "-XX:mainThreadStackSize=")) {
627      // Ignored for backwards compatibility.
628    } else if (!ignore_unrecognized) {
629      Usage("Unrecognized option %s", option.c_str());
630      return false;
631    }
632  }
633
634  // If a reference to the dalvik core.jar snuck in, replace it with
635  // the art specific version. This can happen with on device
636  // boot.art/boot.oat generation by GenerateImage which relies on the
637  // value of BOOTCLASSPATH.
638  std::string core_jar("/core.jar");
639  size_t core_jar_pos = boot_class_path_string_.find(core_jar);
640  if (core_jar_pos != std::string::npos) {
641    boot_class_path_string_.replace(core_jar_pos, core_jar.size(), "/core-libart.jar");
642  }
643
644  if (compiler_callbacks_ == nullptr && image_.empty()) {
645    image_ += GetAndroidRoot();
646    image_ += "/framework/boot.art";
647  }
648  if (heap_growth_limit_ == 0) {
649    heap_growth_limit_ = heap_maximum_size_;
650  }
651  if (background_collector_type_ == gc::kCollectorTypeNone) {
652    background_collector_type_ = collector_type_;
653  }
654  return true;
655}
656
657void ParsedOptions::Exit(int status) {
658  hook_exit_(status);
659}
660
661void ParsedOptions::Abort() {
662  hook_abort_();
663}
664
665void ParsedOptions::UsageMessageV(FILE* stream, const char* fmt, va_list ap) {
666  hook_vfprintf_(stderr, fmt, ap);
667}
668
669void ParsedOptions::UsageMessage(FILE* stream, const char* fmt, ...) {
670  va_list ap;
671  va_start(ap, fmt);
672  UsageMessageV(stream, fmt, ap);
673  va_end(ap);
674}
675
676void ParsedOptions::Usage(const char* fmt, ...) {
677  bool error = (fmt != nullptr);
678  FILE* stream = error ? stderr : stdout;
679
680  if (fmt != nullptr) {
681    va_list ap;
682    va_start(ap, fmt);
683    UsageMessageV(stream, fmt, ap);
684    va_end(ap);
685  }
686
687  const char* program = "dalvikvm";
688  UsageMessage(stream, "%s: [options] class [argument ...]\n", program);
689  UsageMessage(stream, "\n");
690  UsageMessage(stream, "The following standard options are supported:\n");
691  UsageMessage(stream, "  -classpath classpath (-cp classpath)\n");
692  UsageMessage(stream, "  -Dproperty=value\n");
693  UsageMessage(stream, "  -verbose:tag  ('gc', 'jni', or 'class')\n");
694  UsageMessage(stream, "  -showversion\n");
695  UsageMessage(stream, "  -help\n");
696  UsageMessage(stream, "  -agentlib:jdwp=options\n");
697  UsageMessage(stream, "\n");
698
699  UsageMessage(stream, "The following extended options are supported:\n");
700  UsageMessage(stream, "  -Xrunjdwp:<options>\n");
701  UsageMessage(stream, "  -Xbootclasspath:bootclasspath\n");
702  UsageMessage(stream, "  -Xcheck:tag  (e.g. 'jni')\n");
703  UsageMessage(stream, "  -XmsN  (min heap, must be multiple of 1K, >= 1MB)\n");
704  UsageMessage(stream, "  -XmxN  (max heap, must be multiple of 1K, >= 2MB)\n");
705  UsageMessage(stream, "  -XssN  (stack size)\n");
706  UsageMessage(stream, "  -Xint\n");
707  UsageMessage(stream, "\n");
708
709  UsageMessage(stream, "The following Dalvik options are supported:\n");
710  UsageMessage(stream, "  -Xzygote\n");
711  UsageMessage(stream, "  -Xjnitrace:substring (eg NativeClass or nativeMethod)\n");
712  UsageMessage(stream, "  -Xstacktracefile:<filename>\n");
713  UsageMessage(stream, "  -Xgc:[no]preverify\n");
714  UsageMessage(stream, "  -Xgc:[no]postverify\n");
715  UsageMessage(stream, "  -XX:+DisableExplicitGC\n");
716  UsageMessage(stream, "  -XX:HeapGrowthLimit=N\n");
717  UsageMessage(stream, "  -XX:HeapMinFree=N\n");
718  UsageMessage(stream, "  -XX:HeapMaxFree=N\n");
719  UsageMessage(stream, "  -XX:HeapTargetUtilization=doublevalue\n");
720  UsageMessage(stream, "  -XX:ForegroundHeapGrowthMultiplier=doublevalue\n");
721  UsageMessage(stream, "  -XX:LowMemoryMode\n");
722  UsageMessage(stream, "  -Xprofile:{threadcpuclock,wallclock,dualclock}\n");
723  UsageMessage(stream, "\n");
724
725  UsageMessage(stream, "The following unique to ART options are supported:\n");
726  UsageMessage(stream, "  -Xgc:[no]preverify_rosalloc\n");
727  UsageMessage(stream, "  -Xgc:[no]postverify_rosalloc\n");
728  UsageMessage(stream, "  -Ximage:filename\n");
729  UsageMessage(stream, "  -XX:ParallelGCThreads=integervalue\n");
730  UsageMessage(stream, "  -XX:ConcGCThreads=integervalue\n");
731  UsageMessage(stream, "  -XX:MaxSpinsBeforeThinLockInflation=integervalue\n");
732  UsageMessage(stream, "  -XX:LongPauseLogThreshold=integervalue\n");
733  UsageMessage(stream, "  -XX:LongGCLogThreshold=integervalue\n");
734  UsageMessage(stream, "  -XX:DumpGCPerformanceOnShutdown\n");
735  UsageMessage(stream, "  -XX:IgnoreMaxFootprint\n");
736  UsageMessage(stream, "  -XX:UseTLAB\n");
737  UsageMessage(stream, "  -XX:BackgroundGC=none\n");
738  UsageMessage(stream, "  -Xmethod-trace\n");
739  UsageMessage(stream, "  -Xmethod-trace-file:filename");
740  UsageMessage(stream, "  -Xmethod-trace-file-size:integervalue\n");
741  UsageMessage(stream, "  -Xprofile=filename\n");
742  UsageMessage(stream, "  -Xprofile-period:integervalue\n");
743  UsageMessage(stream, "  -Xprofile-duration:integervalue\n");
744  UsageMessage(stream, "  -Xprofile-interval:integervalue\n");
745  UsageMessage(stream, "  -Xprofile-backoff:integervalue\n");
746  UsageMessage(stream, "  -Xcompiler-option dex2oat-option\n");
747  UsageMessage(stream, "  -Ximage-compiler-option dex2oat-option\n");
748  UsageMessage(stream, "\n");
749
750  UsageMessage(stream, "The following previously supported Dalvik options are ignored:\n");
751  UsageMessage(stream, "  -ea[:<package name>... |:<class name>]\n");
752  UsageMessage(stream, "  -da[:<package name>... |:<class name>]\n");
753  UsageMessage(stream, "   (-enableassertions, -disableassertions)\n");
754  UsageMessage(stream, "  -esa\n");
755  UsageMessage(stream, "  -dsa\n");
756  UsageMessage(stream, "   (-enablesystemassertions, -disablesystemassertions)\n");
757  UsageMessage(stream, "  -Xverify:{none,remote,all}\n");
758  UsageMessage(stream, "  -Xrs\n");
759  UsageMessage(stream, "  -Xint:portable, -Xint:fast, -Xint:jit\n");
760  UsageMessage(stream, "  -Xdexopt:{none,verified,all,full}\n");
761  UsageMessage(stream, "  -Xnoquithandler\n");
762  UsageMessage(stream, "  -Xjniopts:{warnonly,forcecopy}\n");
763  UsageMessage(stream, "  -Xjnigreflimit:integervalue\n");
764  UsageMessage(stream, "  -Xgc:[no]precise\n");
765  UsageMessage(stream, "  -Xgc:[no]verifycardtable\n");
766  UsageMessage(stream, "  -X[no]genregmap\n");
767  UsageMessage(stream, "  -Xverifyopt:[no]checkmon\n");
768  UsageMessage(stream, "  -Xcheckdexsum\n");
769  UsageMessage(stream, "  -Xincludeselectedop\n");
770  UsageMessage(stream, "  -Xjitop:hexopvalue[-endvalue][,hexopvalue[-endvalue]]*\n");
771  UsageMessage(stream, "  -Xincludeselectedmethod\n");
772  UsageMessage(stream, "  -Xjitthreshold:integervalue\n");
773  UsageMessage(stream, "  -Xjitcodecachesize:decimalvalueofkbytes\n");
774  UsageMessage(stream, "  -Xjitblocking\n");
775  UsageMessage(stream, "  -Xjitmethod:signature[,signature]* (eg Ljava/lang/String\\;replace)\n");
776  UsageMessage(stream, "  -Xjitclass:classname[,classname]*\n");
777  UsageMessage(stream, "  -Xjitoffset:offset[,offset]\n");
778  UsageMessage(stream, "  -Xjitconfig:filename\n");
779  UsageMessage(stream, "  -Xjitcheckcg\n");
780  UsageMessage(stream, "  -Xjitverbose\n");
781  UsageMessage(stream, "  -Xjitprofile\n");
782  UsageMessage(stream, "  -Xjitdisableopt\n");
783  UsageMessage(stream, "  -Xjitsuspendpoll\n");
784  UsageMessage(stream, "  -XX:mainThreadStackSize=N\n");
785  UsageMessage(stream, "\n");
786
787  Exit((error) ? 1 : 0);
788}
789
790bool ParsedOptions::ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
791  std::string::size_type colon = s.find(c);
792  if (colon == std::string::npos) {
793    Usage("Missing char %c in option %s", c, s.c_str());
794    return false;
795  }
796  // Add one to remove the char we were trimming until.
797  *parsed_value = s.substr(colon + 1);
798  return true;
799}
800
801bool ParsedOptions::ParseInteger(const std::string& s, char after_char, int* parsed_value) {
802  std::string::size_type colon = s.find(after_char);
803  if (colon == std::string::npos) {
804    Usage("Missing char %c in option %s", after_char, s.c_str());
805    return false;
806  }
807  const char* begin = &s[colon + 1];
808  char* end;
809  size_t result = strtoul(begin, &end, 10);
810  if (begin == end || *end != '\0') {
811    Usage("Failed to parse integer from %s ", s.c_str());
812    return false;
813  }
814  *parsed_value = result;
815  return true;
816}
817
818bool ParsedOptions::ParseUnsignedInteger(const std::string& s, char after_char,
819                                         unsigned int* parsed_value) {
820  int i;
821  if (!ParseInteger(s, after_char, &i)) {
822    return false;
823  }
824  if (i < 0) {
825    Usage("Negative value %d passed for unsigned option %s\n", i, s.c_str());
826    return false;
827  }
828  *parsed_value = i;
829  return true;
830}
831
832bool ParsedOptions::ParseDouble(const std::string& option, char after_char,
833                                double min, double max, double* parsed_value) {
834  std::string substring;
835  if (!ParseStringAfterChar(option, after_char, &substring)) {
836    return false;
837  }
838  std::istringstream iss(substring);
839  double value;
840  iss >> value;
841  // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
842  const bool sane_val = iss.eof() && (value >= min) && (value <= max);
843  if (!sane_val) {
844    Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
845    return false;
846  }
847  *parsed_value = value;
848  return true;
849}
850
851}  // namespace art
852