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