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