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