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