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