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