parsed_options.cc revision 52e4b43d62896b56f8c2bd041e528472bb4a0d8d
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
19#ifdef HAVE_ANDROID_OS
20#include "cutils/properties.h"
21#endif
22
23#include "base/stringpiece.h"
24#include "debugger.h"
25#include "gc/heap.h"
26#include "monitor.h"
27#include "utils.h"
28
29namespace art {
30
31ParsedOptions* ParsedOptions::Create(const Runtime::Options& options, bool ignore_unrecognized) {
32  std::unique_ptr<ParsedOptions> parsed(new ParsedOptions());
33  if (parsed->Parse(options, ignore_unrecognized)) {
34    return parsed.release();
35  }
36  return nullptr;
37}
38
39// Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
40// memory sizes.  [kK] indicates kilobytes, [mM] megabytes, and
41// [gG] gigabytes.
42//
43// "s" should point just past the "-Xm?" part of the string.
44// "div" specifies a divisor, e.g. 1024 if the value must be a multiple
45// of 1024.
46//
47// The spec says the -Xmx and -Xms options must be multiples of 1024.  It
48// doesn't say anything about -Xss.
49//
50// Returns 0 (a useless size) if "s" is malformed or specifies a low or
51// non-evenly-divisible value.
52//
53size_t ParseMemoryOption(const char* s, size_t div) {
54  // strtoul accepts a leading [+-], which we don't want,
55  // so make sure our string starts with a decimal digit.
56  if (isdigit(*s)) {
57    char* s2;
58    size_t val = strtoul(s, &s2, 10);
59    if (s2 != s) {
60      // s2 should be pointing just after the number.
61      // If this is the end of the string, the user
62      // has specified a number of bytes.  Otherwise,
63      // there should be exactly one more character
64      // that specifies a multiplier.
65      if (*s2 != '\0') {
66        // The remainder of the string is either a single multiplier
67        // character, or nothing to indicate that the value is in
68        // bytes.
69        char c = *s2++;
70        if (*s2 == '\0') {
71          size_t mul;
72          if (c == '\0') {
73            mul = 1;
74          } else if (c == 'k' || c == 'K') {
75            mul = KB;
76          } else if (c == 'm' || c == 'M') {
77            mul = MB;
78          } else if (c == 'g' || c == 'G') {
79            mul = GB;
80          } else {
81            // Unknown multiplier character.
82            return 0;
83          }
84
85          if (val <= std::numeric_limits<size_t>::max() / mul) {
86            val *= mul;
87          } else {
88            // Clamp to a multiple of 1024.
89            val = std::numeric_limits<size_t>::max() & ~(1024-1);
90          }
91        } else {
92          // There's more than one character after the numeric part.
93          return 0;
94        }
95      }
96      // The man page says that a -Xm value must be a multiple of 1024.
97      if (val % div == 0) {
98        return val;
99      }
100    }
101  }
102  return 0;
103}
104
105static gc::CollectorType ParseCollectorType(const std::string& option) {
106  if (option == "MS" || option == "nonconcurrent") {
107    return gc::kCollectorTypeMS;
108  } else if (option == "CMS" || option == "concurrent") {
109    return gc::kCollectorTypeCMS;
110  } else if (option == "SS") {
111    return gc::kCollectorTypeSS;
112  } else if (option == "GSS") {
113    return gc::kCollectorTypeGSS;
114  } else if (option == "CC") {
115    return gc::kCollectorTypeCC;
116  } else if (option == "MC") {
117    return gc::kCollectorTypeMC;
118  } else {
119    return gc::kCollectorTypeNone;
120  }
121}
122
123bool ParsedOptions::ParseXGcOption(const std::string& option) {
124  std::vector<std::string> gc_options;
125  Split(option.substr(strlen("-Xgc:")), ',', gc_options);
126  for (const std::string& gc_option : gc_options) {
127    gc::CollectorType collector_type = ParseCollectorType(gc_option);
128    if (collector_type != gc::kCollectorTypeNone) {
129      collector_type_ = collector_type;
130    } else if (gc_option == "preverify") {
131      verify_pre_gc_heap_ = true;
132    } else if (gc_option == "nopreverify") {
133      verify_pre_gc_heap_ = false;
134    }  else if (gc_option == "presweepingverify") {
135      verify_pre_sweeping_heap_ = true;
136    } else if (gc_option == "nopresweepingverify") {
137      verify_pre_sweeping_heap_ = false;
138    } else if (gc_option == "postverify") {
139      verify_post_gc_heap_ = true;
140    } else if (gc_option == "nopostverify") {
141      verify_post_gc_heap_ = false;
142    } else if (gc_option == "preverify_rosalloc") {
143      verify_pre_gc_rosalloc_ = true;
144    } else if (gc_option == "nopreverify_rosalloc") {
145      verify_pre_gc_rosalloc_ = false;
146    } else if (gc_option == "presweepingverify_rosalloc") {
147      verify_pre_sweeping_rosalloc_ = true;
148    } else if (gc_option == "nopresweepingverify_rosalloc") {
149      verify_pre_sweeping_rosalloc_ = false;
150    } else if (gc_option == "postverify_rosalloc") {
151      verify_post_gc_rosalloc_ = true;
152    } else if (gc_option == "nopostverify_rosalloc") {
153      verify_post_gc_rosalloc_ = false;
154    } else if ((gc_option == "precise") ||
155               (gc_option == "noprecise") ||
156               (gc_option == "verifycardtable") ||
157               (gc_option == "noverifycardtable")) {
158      // Ignored for backwards compatibility.
159    } else {
160      Usage("Unknown -Xgc option %s\n", gc_option.c_str());
161      return false;
162    }
163  }
164  return true;
165}
166
167bool ParsedOptions::Parse(const Runtime::Options& options, bool ignore_unrecognized) {
168  const char* boot_class_path_string = getenv("BOOTCLASSPATH");
169  if (boot_class_path_string != NULL) {
170    boot_class_path_string_ = boot_class_path_string;
171  }
172  const char* class_path_string = getenv("CLASSPATH");
173  if (class_path_string != NULL) {
174    class_path_string_ = class_path_string;
175  }
176  // -Xcheck:jni is off by default for regular builds but on by default in debug builds.
177  check_jni_ = kIsDebugBuild;
178
179  heap_initial_size_ = gc::Heap::kDefaultInitialSize;
180  heap_maximum_size_ = gc::Heap::kDefaultMaximumSize;
181  heap_min_free_ = gc::Heap::kDefaultMinFree;
182  heap_max_free_ = gc::Heap::kDefaultMaxFree;
183  heap_target_utilization_ = gc::Heap::kDefaultTargetUtilization;
184  foreground_heap_growth_multiplier_ = gc::Heap::kDefaultHeapGrowthMultiplier;
185  heap_growth_limit_ = 0;  // 0 means no growth limit .
186  // Default to number of processors minus one since the main GC thread also does work.
187  parallel_gc_threads_ = sysconf(_SC_NPROCESSORS_CONF) - 1;
188  // Only the main GC thread, no workers.
189  conc_gc_threads_ = 0;
190  // The default GC type is set in makefiles.
191#if ART_DEFAULT_GC_TYPE_IS_CMS
192  collector_type_ = gc::kCollectorTypeCMS;
193#elif ART_DEFAULT_GC_TYPE_IS_SS
194  collector_type_ = gc::kCollectorTypeSS;
195#elif ART_DEFAULT_GC_TYPE_IS_GSS
196  collector_type_ = gc::kCollectorTypeGSS;
197#else
198#error "ART default GC type must be set"
199#endif
200  // If background_collector_type_ is kCollectorTypeNone, it defaults to the collector_type_ after
201  // parsing options.
202  background_collector_type_ = gc::kCollectorTypeSS;
203  stack_size_ = 0;  // 0 means default.
204  max_spins_before_thin_lock_inflation_ = Monitor::kDefaultMaxSpinsBeforeThinLockInflation;
205  low_memory_mode_ = false;
206  use_tlab_ = false;
207  verify_pre_gc_heap_ = false;
208  // Pre sweeping is the one that usually fails if the GC corrupted the heap.
209  verify_pre_sweeping_heap_ = kIsDebugBuild;
210  verify_post_gc_heap_ = false;
211  verify_pre_gc_rosalloc_ = kIsDebugBuild;
212  verify_pre_sweeping_rosalloc_ = false;
213  verify_post_gc_rosalloc_ = false;
214
215  compiler_callbacks_ = nullptr;
216  is_zygote_ = false;
217  if (kPoisonHeapReferences) {
218    // kPoisonHeapReferences currently works only with the interpreter only.
219    // TODO: make it work with the compiler.
220    interpreter_only_ = true;
221  } else {
222    interpreter_only_ = false;
223  }
224  is_explicit_gc_disabled_ = false;
225
226  long_pause_log_threshold_ = gc::Heap::kDefaultLongPauseLogThreshold;
227  long_gc_log_threshold_ = gc::Heap::kDefaultLongGCLogThreshold;
228  dump_gc_performance_on_shutdown_ = false;
229  ignore_max_footprint_ = false;
230
231  lock_profiling_threshold_ = 0;
232  hook_is_sensitive_thread_ = NULL;
233
234  hook_vfprintf_ = vfprintf;
235  hook_exit_ = exit;
236  hook_abort_ = NULL;  // We don't call abort(3) by default; see Runtime::Abort.
237
238//  gLogVerbosity.class_linker = true;  // TODO: don't check this in!
239//  gLogVerbosity.compiler = true;  // TODO: don't check this in!
240//  gLogVerbosity.gc = true;  // TODO: don't check this in!
241//  gLogVerbosity.heap = true;  // TODO: don't check this in!
242//  gLogVerbosity.jdwp = true;  // TODO: don't check this in!
243//  gLogVerbosity.jni = true;  // TODO: don't check this in!
244//  gLogVerbosity.monitor = true;  // TODO: don't check this in!
245//  gLogVerbosity.profiler = true;  // TODO: don't check this in!
246//  gLogVerbosity.signals = true;  // TODO: don't check this in!
247//  gLogVerbosity.startup = true;  // TODO: don't check this in!
248//  gLogVerbosity.third_party_jni = true;  // TODO: don't check this in!
249//  gLogVerbosity.threads = true;  // TODO: don't check this in!
250//  gLogVerbosity.verifier = true;  // TODO: don't check this in!
251
252  method_trace_ = false;
253  method_trace_file_ = "/data/method-trace-file.bin";
254  method_trace_file_size_ = 10 * MB;
255
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, "null,stack");
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 (option == "-Xenable-profiler") {
537      profiler_options_.enabled_ = true;
538    } else if (StartsWith(option, "-Xprofile-filename:")) {
539      if (!ParseStringAfterChar(option, ':', &profile_output_filename_)) {
540        return false;
541      }
542    } else if (StartsWith(option, "-Xprofile-period:")) {
543      if (!ParseUnsignedInteger(option, ':', &profiler_options_.period_s_)) {
544        return false;
545      }
546    } else if (StartsWith(option, "-Xprofile-duration:")) {
547      if (!ParseUnsignedInteger(option, ':', &profiler_options_.duration_s_)) {
548        return false;
549      }
550    } else if (StartsWith(option, "-Xprofile-interval:")) {
551      if (!ParseUnsignedInteger(option, ':', &profiler_options_.interval_us_)) {
552        return false;
553      }
554    } else if (StartsWith(option, "-Xprofile-backoff:")) {
555      if (!ParseDouble(option, ':', 1.0, 10.0, &profiler_options_.backoff_coefficient_)) {
556        return false;
557      }
558    } else if (option == "-Xprofile-start-immediately") {
559      profiler_options_.start_immediately_ = true;
560    } else if (StartsWith(option, "-Xprofile-top-k-threshold:")) {
561      if (!ParseDouble(option, ':', 0.0, 100.0, &profiler_options_.top_k_threshold_)) {
562        return false;
563      }
564    } else if (StartsWith(option, "-Xprofile-top-k-change-threshold:")) {
565      if (!ParseDouble(option, ':', 0.0, 100.0, &profiler_options_.top_k_change_threshold_)) {
566        return false;
567      }
568    } else if (StartsWith(option, "-implicit-checks:")) {
569      std::string checks;
570      if (!ParseStringAfterChar(option, ':', &checks)) {
571        return false;
572      }
573      std::vector<std::string> checkvec;
574      Split(checks, ',', checkvec);
575      for (auto& str : checkvec) {
576        std::string val = Trim(str);
577        if (val == "none") {
578          explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
579            kExplicitStackOverflowCheck;
580        } else if (val == "null") {
581          explicit_checks_ &= ~kExplicitNullCheck;
582        } else if (val == "suspend") {
583          explicit_checks_ &= ~kExplicitSuspendCheck;
584        } else if (val == "stack") {
585          explicit_checks_ &= ~kExplicitStackOverflowCheck;
586        } else if (val == "all") {
587          explicit_checks_ = 0;
588        } else {
589            return false;
590        }
591      }
592    } else if (StartsWith(option, "-explicit-checks:")) {
593      std::string checks;
594      if (!ParseStringAfterChar(option, ':', &checks)) {
595        return false;
596      }
597      std::vector<std::string> checkvec;
598      Split(checks, ',', checkvec);
599      for (auto& str : checkvec) {
600        std::string val = Trim(str);
601        if (val == "none") {
602          explicit_checks_ = 0;
603        } else if (val == "null") {
604          explicit_checks_ |= kExplicitNullCheck;
605        } else if (val == "suspend") {
606          explicit_checks_ |= kExplicitSuspendCheck;
607        } else if (val == "stack") {
608          explicit_checks_ |= kExplicitStackOverflowCheck;
609        } else if (val == "all") {
610          explicit_checks_ = kExplicitNullCheck | kExplicitSuspendCheck |
611            kExplicitStackOverflowCheck;
612        } else {
613          return false;
614        }
615      }
616    } else if (StartsWith(option, "-Xcompiler:")) {
617      if (!ParseStringAfterChar(option, ':', &compiler_executable_)) {
618        return false;
619      }
620    } else if (option == "-Xcompiler-option") {
621      i++;
622      if (i == options.size()) {
623        Usage("Missing required compiler option for %s\n", option.c_str());
624        return false;
625      }
626      compiler_options_.push_back(options[i].first);
627    } else if (option == "-Ximage-compiler-option") {
628      i++;
629      if (i == options.size()) {
630        Usage("Missing required compiler option for %s\n", option.c_str());
631        return false;
632      }
633      image_compiler_options_.push_back(options[i].first);
634    } else if (StartsWith(option, "-Xverify:")) {
635      std::string verify_mode = option.substr(strlen("-Xverify:"));
636      if (verify_mode == "none") {
637        verify_ = false;
638      } else if (verify_mode == "remote" || verify_mode == "all") {
639        verify_ = true;
640      } else {
641        Usage("Unknown -Xverify option %s\n", verify_mode.c_str());
642        return false;
643      }
644    } else if (StartsWith(option, "-ea") ||
645               StartsWith(option, "-da") ||
646               StartsWith(option, "-enableassertions") ||
647               StartsWith(option, "-disableassertions") ||
648               (option == "--runtime-arg") ||
649               (option == "-esa") ||
650               (option == "-dsa") ||
651               (option == "-enablesystemassertions") ||
652               (option == "-disablesystemassertions") ||
653               (option == "-Xrs") ||
654               StartsWith(option, "-Xint:") ||
655               StartsWith(option, "-Xdexopt:") ||
656               (option == "-Xnoquithandler") ||
657               StartsWith(option, "-Xjniopts:") ||
658               StartsWith(option, "-Xjnigreflimit:") ||
659               (option == "-Xgenregmap") ||
660               (option == "-Xnogenregmap") ||
661               StartsWith(option, "-Xverifyopt:") ||
662               (option == "-Xcheckdexsum") ||
663               (option == "-Xincludeselectedop") ||
664               StartsWith(option, "-Xjitop:") ||
665               (option == "-Xincludeselectedmethod") ||
666               StartsWith(option, "-Xjitthreshold:") ||
667               StartsWith(option, "-Xjitcodecachesize:") ||
668               (option == "-Xjitblocking") ||
669               StartsWith(option, "-Xjitmethod:") ||
670               StartsWith(option, "-Xjitclass:") ||
671               StartsWith(option, "-Xjitoffset:") ||
672               StartsWith(option, "-Xjitconfig:") ||
673               (option == "-Xjitcheckcg") ||
674               (option == "-Xjitverbose") ||
675               (option == "-Xjitprofile") ||
676               (option == "-Xjitdisableopt") ||
677               (option == "-Xjitsuspendpoll") ||
678               StartsWith(option, "-XX:mainThreadStackSize=")) {
679      // Ignored for backwards compatibility.
680    } else if (!ignore_unrecognized) {
681      Usage("Unrecognized option %s\n", option.c_str());
682      return false;
683    }
684  }
685
686  // If a reference to the dalvik core.jar snuck in, replace it with
687  // the art specific version. This can happen with on device
688  // boot.art/boot.oat generation by GenerateImage which relies on the
689  // value of BOOTCLASSPATH.
690#if defined(ART_TARGET)
691  std::string core_jar("/core.jar");
692  std::string core_libart_jar("/core-libart.jar");
693#else
694  // The host uses hostdex files.
695  std::string core_jar("/core-hostdex.jar");
696  std::string core_libart_jar("/core-libart-hostdex.jar");
697#endif
698  size_t core_jar_pos = boot_class_path_string_.find(core_jar);
699  if (core_jar_pos != std::string::npos) {
700    boot_class_path_string_.replace(core_jar_pos, core_jar.size(), core_libart_jar);
701  }
702
703  if (compiler_callbacks_ == nullptr && image_.empty()) {
704    image_ += GetAndroidRoot();
705    image_ += "/framework/boot.art";
706  }
707  if (heap_growth_limit_ == 0) {
708    heap_growth_limit_ = heap_maximum_size_;
709  }
710  if (background_collector_type_ == gc::kCollectorTypeNone) {
711    background_collector_type_ = collector_type_;
712  }
713  return true;
714}  // NOLINT(readability/fn_size)
715
716void ParsedOptions::Exit(int status) {
717  hook_exit_(status);
718}
719
720void ParsedOptions::Abort() {
721  hook_abort_();
722}
723
724void ParsedOptions::UsageMessageV(FILE* stream, const char* fmt, va_list ap) {
725  hook_vfprintf_(stderr, fmt, ap);
726}
727
728void ParsedOptions::UsageMessage(FILE* stream, const char* fmt, ...) {
729  va_list ap;
730  va_start(ap, fmt);
731  UsageMessageV(stream, fmt, ap);
732  va_end(ap);
733}
734
735void ParsedOptions::Usage(const char* fmt, ...) {
736  bool error = (fmt != nullptr);
737  FILE* stream = error ? stderr : stdout;
738
739  if (fmt != nullptr) {
740    va_list ap;
741    va_start(ap, fmt);
742    UsageMessageV(stream, fmt, ap);
743    va_end(ap);
744  }
745
746  const char* program = "dalvikvm";
747  UsageMessage(stream, "%s: [options] class [argument ...]\n", program);
748  UsageMessage(stream, "\n");
749  UsageMessage(stream, "The following standard options are supported:\n");
750  UsageMessage(stream, "  -classpath classpath (-cp classpath)\n");
751  UsageMessage(stream, "  -Dproperty=value\n");
752  UsageMessage(stream, "  -verbose:tag  ('gc', 'jni', or 'class')\n");
753  UsageMessage(stream, "  -showversion\n");
754  UsageMessage(stream, "  -help\n");
755  UsageMessage(stream, "  -agentlib:jdwp=options\n");
756  UsageMessage(stream, "\n");
757
758  UsageMessage(stream, "The following extended options are supported:\n");
759  UsageMessage(stream, "  -Xrunjdwp:<options>\n");
760  UsageMessage(stream, "  -Xbootclasspath:bootclasspath\n");
761  UsageMessage(stream, "  -Xcheck:tag  (e.g. 'jni')\n");
762  UsageMessage(stream, "  -XmsN  (min heap, must be multiple of 1K, >= 1MB)\n");
763  UsageMessage(stream, "  -XmxN  (max heap, must be multiple of 1K, >= 2MB)\n");
764  UsageMessage(stream, "  -XssN  (stack size)\n");
765  UsageMessage(stream, "  -Xint\n");
766  UsageMessage(stream, "\n");
767
768  UsageMessage(stream, "The following Dalvik options are supported:\n");
769  UsageMessage(stream, "  -Xzygote\n");
770  UsageMessage(stream, "  -Xjnitrace:substring (eg NativeClass or nativeMethod)\n");
771  UsageMessage(stream, "  -Xstacktracefile:<filename>\n");
772  UsageMessage(stream, "  -Xgc:[no]preverify\n");
773  UsageMessage(stream, "  -Xgc:[no]postverify\n");
774  UsageMessage(stream, "  -XX:+DisableExplicitGC\n");
775  UsageMessage(stream, "  -XX:HeapGrowthLimit=N\n");
776  UsageMessage(stream, "  -XX:HeapMinFree=N\n");
777  UsageMessage(stream, "  -XX:HeapMaxFree=N\n");
778  UsageMessage(stream, "  -XX:HeapTargetUtilization=doublevalue\n");
779  UsageMessage(stream, "  -XX:ForegroundHeapGrowthMultiplier=doublevalue\n");
780  UsageMessage(stream, "  -XX:LowMemoryMode\n");
781  UsageMessage(stream, "  -Xprofile:{threadcpuclock,wallclock,dualclock}\n");
782  UsageMessage(stream, "\n");
783
784  UsageMessage(stream, "The following unique to ART options are supported:\n");
785  UsageMessage(stream, "  -Xgc:[no]preverify_rosalloc\n");
786  UsageMessage(stream, "  -Xgc:[no]postsweepingverify_rosalloc\n");
787  UsageMessage(stream, "  -Xgc:[no]postverify_rosalloc\n");
788  UsageMessage(stream, "  -Xgc:[no]presweepingverify\n");
789  UsageMessage(stream, "  -Ximage:filename\n");
790  UsageMessage(stream, "  -XX:ParallelGCThreads=integervalue\n");
791  UsageMessage(stream, "  -XX:ConcGCThreads=integervalue\n");
792  UsageMessage(stream, "  -XX:MaxSpinsBeforeThinLockInflation=integervalue\n");
793  UsageMessage(stream, "  -XX:LongPauseLogThreshold=integervalue\n");
794  UsageMessage(stream, "  -XX:LongGCLogThreshold=integervalue\n");
795  UsageMessage(stream, "  -XX:DumpGCPerformanceOnShutdown\n");
796  UsageMessage(stream, "  -XX:IgnoreMaxFootprint\n");
797  UsageMessage(stream, "  -XX:UseTLAB\n");
798  UsageMessage(stream, "  -XX:BackgroundGC=none\n");
799  UsageMessage(stream, "  -Xmethod-trace\n");
800  UsageMessage(stream, "  -Xmethod-trace-file:filename");
801  UsageMessage(stream, "  -Xmethod-trace-file-size:integervalue\n");
802  UsageMessage(stream, "  -Xenable-profiler\n");
803  UsageMessage(stream, "  -Xprofile-filename:filename\n");
804  UsageMessage(stream, "  -Xprofile-period:integervalue\n");
805  UsageMessage(stream, "  -Xprofile-duration:integervalue\n");
806  UsageMessage(stream, "  -Xprofile-interval:integervalue\n");
807  UsageMessage(stream, "  -Xprofile-backoff:doublevalue\n");
808  UsageMessage(stream, "  -Xprofile-start-immediately\n");
809  UsageMessage(stream, "  -Xprofile-top-k-threshold:doublevalue\n");
810  UsageMessage(stream, "  -Xprofile-top-k-change-threshold:doublevalue\n");
811  UsageMessage(stream, "  -Xcompiler:filename\n");
812  UsageMessage(stream, "  -Xcompiler-option dex2oat-option\n");
813  UsageMessage(stream, "  -Ximage-compiler-option dex2oat-option\n");
814  UsageMessage(stream, "\n");
815
816  UsageMessage(stream, "The following previously supported Dalvik options are ignored:\n");
817  UsageMessage(stream, "  -ea[:<package name>... |:<class name>]\n");
818  UsageMessage(stream, "  -da[:<package name>... |:<class name>]\n");
819  UsageMessage(stream, "   (-enableassertions, -disableassertions)\n");
820  UsageMessage(stream, "  -esa\n");
821  UsageMessage(stream, "  -dsa\n");
822  UsageMessage(stream, "   (-enablesystemassertions, -disablesystemassertions)\n");
823  UsageMessage(stream, "  -Xverify:{none,remote,all}\n");
824  UsageMessage(stream, "  -Xrs\n");
825  UsageMessage(stream, "  -Xint:portable, -Xint:fast, -Xint:jit\n");
826  UsageMessage(stream, "  -Xdexopt:{none,verified,all,full}\n");
827  UsageMessage(stream, "  -Xnoquithandler\n");
828  UsageMessage(stream, "  -Xjniopts:{warnonly,forcecopy}\n");
829  UsageMessage(stream, "  -Xjnigreflimit:integervalue\n");
830  UsageMessage(stream, "  -Xgc:[no]precise\n");
831  UsageMessage(stream, "  -Xgc:[no]verifycardtable\n");
832  UsageMessage(stream, "  -X[no]genregmap\n");
833  UsageMessage(stream, "  -Xverifyopt:[no]checkmon\n");
834  UsageMessage(stream, "  -Xcheckdexsum\n");
835  UsageMessage(stream, "  -Xincludeselectedop\n");
836  UsageMessage(stream, "  -Xjitop:hexopvalue[-endvalue][,hexopvalue[-endvalue]]*\n");
837  UsageMessage(stream, "  -Xincludeselectedmethod\n");
838  UsageMessage(stream, "  -Xjitthreshold:integervalue\n");
839  UsageMessage(stream, "  -Xjitcodecachesize:decimalvalueofkbytes\n");
840  UsageMessage(stream, "  -Xjitblocking\n");
841  UsageMessage(stream, "  -Xjitmethod:signature[,signature]* (eg Ljava/lang/String\\;replace)\n");
842  UsageMessage(stream, "  -Xjitclass:classname[,classname]*\n");
843  UsageMessage(stream, "  -Xjitoffset:offset[,offset]\n");
844  UsageMessage(stream, "  -Xjitconfig:filename\n");
845  UsageMessage(stream, "  -Xjitcheckcg\n");
846  UsageMessage(stream, "  -Xjitverbose\n");
847  UsageMessage(stream, "  -Xjitprofile\n");
848  UsageMessage(stream, "  -Xjitdisableopt\n");
849  UsageMessage(stream, "  -Xjitsuspendpoll\n");
850  UsageMessage(stream, "  -XX:mainThreadStackSize=N\n");
851  UsageMessage(stream, "\n");
852
853  Exit((error) ? 1 : 0);
854}
855
856bool ParsedOptions::ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
857  std::string::size_type colon = s.find(c);
858  if (colon == std::string::npos) {
859    Usage("Missing char %c in option %s\n", c, s.c_str());
860    return false;
861  }
862  // Add one to remove the char we were trimming until.
863  *parsed_value = s.substr(colon + 1);
864  return true;
865}
866
867bool ParsedOptions::ParseInteger(const std::string& s, char after_char, int* parsed_value) {
868  std::string::size_type colon = s.find(after_char);
869  if (colon == std::string::npos) {
870    Usage("Missing char %c in option %s\n", after_char, s.c_str());
871    return false;
872  }
873  const char* begin = &s[colon + 1];
874  char* end;
875  size_t result = strtoul(begin, &end, 10);
876  if (begin == end || *end != '\0') {
877    Usage("Failed to parse integer from %s\n", s.c_str());
878    return false;
879  }
880  *parsed_value = result;
881  return true;
882}
883
884bool ParsedOptions::ParseUnsignedInteger(const std::string& s, char after_char,
885                                         unsigned int* parsed_value) {
886  int i;
887  if (!ParseInteger(s, after_char, &i)) {
888    return false;
889  }
890  if (i < 0) {
891    Usage("Negative value %d passed for unsigned option %s\n", i, s.c_str());
892    return false;
893  }
894  *parsed_value = i;
895  return true;
896}
897
898bool ParsedOptions::ParseDouble(const std::string& option, char after_char,
899                                double min, double max, double* parsed_value) {
900  std::string substring;
901  if (!ParseStringAfterChar(option, after_char, &substring)) {
902    return false;
903  }
904  bool sane_val = true;
905  double value;
906  if (false) {
907    // TODO: this doesn't seem to work on the emulator.  b/15114595
908    std::stringstream iss(substring);
909    iss >> value;
910    // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
911    sane_val = iss.eof() && (value >= min) && (value <= max);
912  } else {
913    char* end = nullptr;
914    value = strtod(substring.c_str(), &end);
915    sane_val = *end == '\0' && value >= min && value <= max;
916  }
917  if (!sane_val) {
918    Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
919    return false;
920  }
921  *parsed_value = value;
922  return true;
923}
924
925}  // namespace art
926