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