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