1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "parsed_options.h"
18 
19 #include <memory>
20 #include <sstream>
21 
22 #include <android-base/logging.h>
23 #include <android-base/strings.h>
24 
25 #include "base/file_utils.h"
26 #include "base/macros.h"
27 #include "base/utils.h"
28 #include "debugger.h"
29 #include "gc/heap.h"
30 #include "jni_id_type.h"
31 #include "monitor.h"
32 #include "runtime.h"
33 #include "ti/agent.h"
34 #include "trace.h"
35 
36 #include "cmdline_parser.h"
37 #include "runtime_options.h"
38 
39 namespace art {
40 
41 using MemoryKiB = Memory<1024>;
42 
ParsedOptions()43 ParsedOptions::ParsedOptions()
44   : hook_is_sensitive_thread_(nullptr),
45     hook_vfprintf_(vfprintf),
46     hook_exit_(exit),
47     hook_abort_(nullptr) {                          // We don't call abort(3) by default; see
48                                                     // Runtime::Abort
49 }
50 
Parse(const RuntimeOptions & options,bool ignore_unrecognized,RuntimeArgumentMap * runtime_options)51 bool ParsedOptions::Parse(const RuntimeOptions& options,
52                           bool ignore_unrecognized,
53                           RuntimeArgumentMap* runtime_options) {
54   CHECK(runtime_options != nullptr);
55 
56   ParsedOptions parser;
57   return parser.DoParse(options, ignore_unrecognized, runtime_options);
58 }
59 
60 using RuntimeParser = CmdlineParser<RuntimeArgumentMap, RuntimeArgumentMap::Key>;
61 using HiddenapiPolicyValueMap =
62     std::initializer_list<std::pair<const char*, hiddenapi::EnforcementPolicy>>;
63 
64 // Yes, the stack frame is huge. But we get called super early on (and just once)
65 // to pass the command line arguments, so we'll probably be ok.
66 // Ideas to avoid suppressing this diagnostic are welcome!
67 #pragma GCC diagnostic push
68 #pragma GCC diagnostic ignored "-Wframe-larger-than="
69 
MakeParser(bool ignore_unrecognized)70 std::unique_ptr<RuntimeParser> ParsedOptions::MakeParser(bool ignore_unrecognized) {
71   using M = RuntimeArgumentMap;
72 
73   std::unique_ptr<RuntimeParser::Builder> parser_builder =
74       std::make_unique<RuntimeParser::Builder>();
75 
76   HiddenapiPolicyValueMap hiddenapi_policy_valuemap =
77       {{"disabled",  hiddenapi::EnforcementPolicy::kDisabled},
78        {"just-warn", hiddenapi::EnforcementPolicy::kJustWarn},
79        {"enabled",   hiddenapi::EnforcementPolicy::kEnabled}};
80   DCHECK_EQ(hiddenapi_policy_valuemap.size(),
81             static_cast<size_t>(hiddenapi::EnforcementPolicy::kMax) + 1);
82 
83   parser_builder->
84        Define("-Xzygote")
85           .IntoKey(M::Zygote)
86       .Define("-Xprimaryzygote")
87           .IntoKey(M::PrimaryZygote)
88       .Define("-help")
89           .IntoKey(M::Help)
90       .Define("-showversion")
91           .IntoKey(M::ShowVersion)
92       .Define("-Xbootclasspath:_")
93           .WithType<ParseStringList<':'>>()  // std::vector<std::string>, split by :
94           .IntoKey(M::BootClassPath)
95       .Define("-Xbootclasspath-locations:_")
96           .WithType<ParseStringList<':'>>()  // std::vector<std::string>, split by :
97           .IntoKey(M::BootClassPathLocations)
98       .Define({"-classpath _", "-cp _"})
99           .WithType<std::string>()
100           .IntoKey(M::ClassPath)
101       .Define("-Ximage:_")
102           .WithType<std::string>()
103           .IntoKey(M::Image)
104       .Define("-Ximage-load-order:_")
105           .WithType<gc::space::ImageSpaceLoadingOrder>()
106           .WithValueMap({{"system", gc::space::ImageSpaceLoadingOrder::kSystemFirst},
107                          {"data", gc::space::ImageSpaceLoadingOrder::kDataFirst}})
108           .IntoKey(M::ImageSpaceLoadingOrder)
109       .Define("-Xcheck:jni")
110           .IntoKey(M::CheckJni)
111       .Define("-Xjniopts:forcecopy")
112           .IntoKey(M::JniOptsForceCopy)
113       .Define("-XjdwpProvider:_")
114           .WithType<JdwpProvider>()
115           .IntoKey(M::JdwpProvider)
116       .Define("-XjdwpOptions:_")
117           .WithType<std::string>()
118           .IntoKey(M::JdwpOptions)
119       // TODO Re-enable -agentlib: once I have a good way to transform the values.
120       // .Define("-agentlib:_")
121       //     .WithType<std::vector<ti::Agent>>().AppendValues()
122       //     .IntoKey(M::AgentLib)
123       .Define("-agentpath:_")
124           .WithType<std::list<ti::AgentSpec>>().AppendValues()
125           .IntoKey(M::AgentPath)
126       .Define("-Xms_")
127           .WithType<MemoryKiB>()
128           .IntoKey(M::MemoryInitialSize)
129       .Define("-Xmx_")
130           .WithType<MemoryKiB>()
131           .IntoKey(M::MemoryMaximumSize)
132       .Define("-XX:HeapGrowthLimit=_")
133           .WithType<MemoryKiB>()
134           .IntoKey(M::HeapGrowthLimit)
135       .Define("-XX:HeapMinFree=_")
136           .WithType<MemoryKiB>()
137           .IntoKey(M::HeapMinFree)
138       .Define("-XX:HeapMaxFree=_")
139           .WithType<MemoryKiB>()
140           .IntoKey(M::HeapMaxFree)
141       .Define("-XX:NonMovingSpaceCapacity=_")
142           .WithType<MemoryKiB>()
143           .IntoKey(M::NonMovingSpaceCapacity)
144       .Define("-XX:StopForNativeAllocs=_")
145           .WithType<MemoryKiB>()
146           .IntoKey(M::StopForNativeAllocs)
147       .Define("-XX:HeapTargetUtilization=_")
148           .WithType<double>().WithRange(0.1, 0.9)
149           .IntoKey(M::HeapTargetUtilization)
150       .Define("-XX:ForegroundHeapGrowthMultiplier=_")
151           .WithType<double>().WithRange(0.1, 5.0)
152           .IntoKey(M::ForegroundHeapGrowthMultiplier)
153       .Define("-XX:ParallelGCThreads=_")
154           .WithType<unsigned int>()
155           .IntoKey(M::ParallelGCThreads)
156       .Define("-XX:ConcGCThreads=_")
157           .WithType<unsigned int>()
158           .IntoKey(M::ConcGCThreads)
159       .Define("-XX:FinalizerTimeoutMs=_")
160           .WithType<unsigned int>()
161           .IntoKey(M::FinalizerTimeoutMs)
162       .Define("-Xss_")
163           .WithType<Memory<1>>()
164           .IntoKey(M::StackSize)
165       .Define("-XX:MaxSpinsBeforeThinLockInflation=_")
166           .WithType<unsigned int>()
167           .IntoKey(M::MaxSpinsBeforeThinLockInflation)
168       .Define("-XX:LongPauseLogThreshold=_")  // in ms
169           .WithType<MillisecondsToNanoseconds>()  // store as ns
170           .IntoKey(M::LongPauseLogThreshold)
171       .Define("-XX:LongGCLogThreshold=_")  // in ms
172           .WithType<MillisecondsToNanoseconds>()  // store as ns
173           .IntoKey(M::LongGCLogThreshold)
174       .Define("-XX:DumpGCPerformanceOnShutdown")
175           .IntoKey(M::DumpGCPerformanceOnShutdown)
176       .Define("-XX:DumpRegionInfoBeforeGC")
177           .IntoKey(M::DumpRegionInfoBeforeGC)
178       .Define("-XX:DumpRegionInfoAfterGC")
179           .IntoKey(M::DumpRegionInfoAfterGC)
180       .Define("-XX:DumpJITInfoOnShutdown")
181           .IntoKey(M::DumpJITInfoOnShutdown)
182       .Define("-XX:IgnoreMaxFootprint")
183           .IntoKey(M::IgnoreMaxFootprint)
184       .Define("-XX:LowMemoryMode")
185           .IntoKey(M::LowMemoryMode)
186       .Define("-XX:UseTLAB")
187           .WithValue(true)
188           .IntoKey(M::UseTLAB)
189       .Define({"-XX:EnableHSpaceCompactForOOM", "-XX:DisableHSpaceCompactForOOM"})
190           .WithValues({true, false})
191           .IntoKey(M::EnableHSpaceCompactForOOM)
192       .Define("-XX:DumpNativeStackOnSigQuit:_")
193           .WithType<bool>()
194           .WithValueMap({{"false", false}, {"true", true}})
195           .IntoKey(M::DumpNativeStackOnSigQuit)
196       .Define("-XX:MadviseRandomAccess:_")
197           .WithType<bool>()
198           .WithValueMap({{"false", false}, {"true", true}})
199           .IntoKey(M::MadviseRandomAccess)
200       .Define("-Xusejit:_")
201           .WithType<bool>()
202           .WithValueMap({{"false", false}, {"true", true}})
203           .IntoKey(M::UseJitCompilation)
204       .Define("-Xusetieredjit:_")
205           .WithType<bool>()
206           .WithValueMap({{"false", false}, {"true", true}})
207           .IntoKey(M::UseTieredJitCompilation)
208       .Define("-Xjitinitialsize:_")
209           .WithType<MemoryKiB>()
210           .IntoKey(M::JITCodeCacheInitialCapacity)
211       .Define("-Xjitmaxsize:_")
212           .WithType<MemoryKiB>()
213           .IntoKey(M::JITCodeCacheMaxCapacity)
214       .Define("-Xjitthreshold:_")
215           .WithType<unsigned int>()
216           .IntoKey(M::JITCompileThreshold)
217       .Define("-Xjitwarmupthreshold:_")
218           .WithType<unsigned int>()
219           .IntoKey(M::JITWarmupThreshold)
220       .Define("-Xjitosrthreshold:_")
221           .WithType<unsigned int>()
222           .IntoKey(M::JITOsrThreshold)
223       .Define("-Xjitprithreadweight:_")
224           .WithType<unsigned int>()
225           .IntoKey(M::JITPriorityThreadWeight)
226       .Define("-Xjittransitionweight:_")
227           .WithType<unsigned int>()
228           .IntoKey(M::JITInvokeTransitionWeight)
229       .Define("-Xjitpthreadpriority:_")
230           .WithType<int>()
231           .IntoKey(M::JITPoolThreadPthreadPriority)
232       .Define("-Xjitsaveprofilinginfo")
233           .WithType<ProfileSaverOptions>()
234           .AppendValues()
235           .IntoKey(M::ProfileSaverOpts)
236       .Define("-Xps-_")  // profile saver options -Xps-<key>:<value>
237           .WithType<ProfileSaverOptions>()
238           .AppendValues()
239           .IntoKey(M::ProfileSaverOpts)  // NOTE: Appends into same key as -Xjitsaveprofilinginfo
240       .Define("-XX:HspaceCompactForOOMMinIntervalMs=_")  // in ms
241           .WithType<MillisecondsToNanoseconds>()  // store as ns
242           .IntoKey(M::HSpaceCompactForOOMMinIntervalsMs)
243       .Define("-D_")
244           .WithType<std::vector<std::string>>().AppendValues()
245           .IntoKey(M::PropertiesList)
246       .Define("-Xjnitrace:_")
247           .WithType<std::string>()
248           .IntoKey(M::JniTrace)
249       .Define({"-Xrelocate", "-Xnorelocate"})
250           .WithValues({true, false})
251           .IntoKey(M::Relocate)
252       .Define({"-Ximage-dex2oat", "-Xnoimage-dex2oat"})
253           .WithValues({true, false})
254           .IntoKey(M::ImageDex2Oat)
255       .Define("-Xint")
256           .WithValue(true)
257           .IntoKey(M::Interpret)
258       .Define("-Xgc:_")
259           .WithType<XGcOption>()
260           .IntoKey(M::GcOption)
261       .Define("-XX:LargeObjectSpace=_")
262           .WithType<gc::space::LargeObjectSpaceType>()
263           .WithValueMap({{"disabled", gc::space::LargeObjectSpaceType::kDisabled},
264                          {"freelist", gc::space::LargeObjectSpaceType::kFreeList},
265                          {"map",      gc::space::LargeObjectSpaceType::kMap}})
266           .IntoKey(M::LargeObjectSpace)
267       .Define("-XX:LargeObjectThreshold=_")
268           .WithType<Memory<1>>()
269           .IntoKey(M::LargeObjectThreshold)
270       .Define("-XX:BackgroundGC=_")
271           .WithType<BackgroundGcOption>()
272           .IntoKey(M::BackgroundGc)
273       .Define("-XX:+DisableExplicitGC")
274           .IntoKey(M::DisableExplicitGC)
275       .Define("-verbose:_")
276           .WithType<LogVerbosity>()
277           .IntoKey(M::Verbose)
278       .Define("-Xlockprofthreshold:_")
279           .WithType<unsigned int>()
280           .IntoKey(M::LockProfThreshold)
281       .Define("-Xstackdumplockprofthreshold:_")
282           .WithType<unsigned int>()
283           .IntoKey(M::StackDumpLockProfThreshold)
284       .Define("-Xmethod-trace")
285           .IntoKey(M::MethodTrace)
286       .Define("-Xmethod-trace-file:_")
287           .WithType<std::string>()
288           .IntoKey(M::MethodTraceFile)
289       .Define("-Xmethod-trace-file-size:_")
290           .WithType<unsigned int>()
291           .IntoKey(M::MethodTraceFileSize)
292       .Define("-Xmethod-trace-stream")
293           .IntoKey(M::MethodTraceStreaming)
294       .Define("-Xprofile:_")
295           .WithType<TraceClockSource>()
296           .WithValueMap({{"threadcpuclock", TraceClockSource::kThreadCpu},
297                          {"wallclock",      TraceClockSource::kWall},
298                          {"dualclock",      TraceClockSource::kDual}})
299           .IntoKey(M::ProfileClock)
300       .Define("-Xcompiler:_")
301           .WithType<std::string>()
302           .IntoKey(M::Compiler)
303       .Define("-Xcompiler-option _")
304           .WithType<std::vector<std::string>>()
305           .AppendValues()
306           .IntoKey(M::CompilerOptions)
307       .Define("-Ximage-compiler-option _")
308           .WithType<std::vector<std::string>>()
309           .AppendValues()
310           .IntoKey(M::ImageCompilerOptions)
311       .Define("-Xverify:_")
312           .WithType<verifier::VerifyMode>()
313           .WithValueMap({{"none",     verifier::VerifyMode::kNone},
314                          {"remote",   verifier::VerifyMode::kEnable},
315                          {"all",      verifier::VerifyMode::kEnable},
316                          {"softfail", verifier::VerifyMode::kSoftFail}})
317           .IntoKey(M::Verify)
318       .Define("-XX:NativeBridge=_")
319           .WithType<std::string>()
320           .IntoKey(M::NativeBridge)
321       .Define("-Xzygote-max-boot-retry=_")
322           .WithType<unsigned int>()
323           .IntoKey(M::ZygoteMaxFailedBoots)
324       .Define("-Xno-dex-file-fallback")
325           .IntoKey(M::NoDexFileFallback)
326       .Define("-Xno-sig-chain")
327           .IntoKey(M::NoSigChain)
328       .Define("--cpu-abilist=_")
329           .WithType<std::string>()
330           .IntoKey(M::CpuAbiList)
331       .Define("-Xfingerprint:_")
332           .WithType<std::string>()
333           .IntoKey(M::Fingerprint)
334       .Define("-Xexperimental:_")
335           .WithType<ExperimentalFlags>()
336           .AppendValues()
337           .IntoKey(M::Experimental)
338       .Define("-Xforce-nb-testing")
339           .IntoKey(M::ForceNativeBridge)
340       .Define("-Xplugin:_")
341           .WithType<std::vector<Plugin>>().AppendValues()
342           .IntoKey(M::Plugins)
343       .Define("-XX:ThreadSuspendTimeout=_")  // in ms
344           .WithType<MillisecondsToNanoseconds>()  // store as ns
345           .IntoKey(M::ThreadSuspendTimeout)
346       .Define("-XX:GlobalRefAllocStackTraceLimit=_")  // Number of free slots to enable tracing.
347           .WithType<unsigned int>()
348           .IntoKey(M::GlobalRefAllocStackTraceLimit)
349       .Define("-XX:SlowDebug=_")
350           .WithType<bool>()
351           .WithValueMap({{"false", false}, {"true", true}})
352           .IntoKey(M::SlowDebug)
353       .Define("-Xtarget-sdk-version:_")
354           .WithType<unsigned int>()
355           .IntoKey(M::TargetSdkVersion)
356       .Define("-Xhidden-api-policy:_")
357           .WithType<hiddenapi::EnforcementPolicy>()
358           .WithValueMap(hiddenapi_policy_valuemap)
359           .IntoKey(M::HiddenApiPolicy)
360       .Define("-Xcore-platform-api-policy:_")
361           .WithType<hiddenapi::EnforcementPolicy>()
362           .WithValueMap(hiddenapi_policy_valuemap)
363           .IntoKey(M::CorePlatformApiPolicy)
364       .Define("-Xuse-stderr-logger")
365           .IntoKey(M::UseStderrLogger)
366       .Define("-Xonly-use-system-oat-files")
367           .IntoKey(M::OnlyUseSystemOatFiles)
368       .Define("-Xverifier-logging-threshold=_")
369           .WithType<unsigned int>()
370           .IntoKey(M::VerifierLoggingThreshold)
371       .Define("-XX:FastClassNotFoundException=_")
372           .WithType<bool>()
373           .WithValueMap({{"false", false}, {"true", true}})
374           .IntoKey(M::FastClassNotFoundException)
375       .Define("-Xopaque-jni-ids:_")
376           .WithType<JniIdType>()
377           .WithValueMap({{"true", JniIdType::kIndices},
378                          {"false", JniIdType::kPointer},
379                          {"swapable", JniIdType::kSwapablePointer},
380                          {"pointer", JniIdType::kPointer},
381                          {"indices", JniIdType::kIndices},
382                          {"default", JniIdType::kDefault}})
383           .IntoKey(M::OpaqueJniIds)
384       .Define("-Xauto-promote-opaque-jni-ids:_")
385           .WithType<bool>()
386           .WithValueMap({{"true", true}, {"false", false}})
387           .IntoKey(M::AutoPromoteOpaqueJniIds)
388       .Define("-XX:VerifierMissingKThrowFatal=_")
389           .WithType<bool>()
390           .WithValueMap({{"false", false}, {"true", true}})
391           .IntoKey(M::VerifierMissingKThrowFatal)
392       .Define("-XX:PerfettoHprof=_")
393           .WithType<bool>()
394           .WithValueMap({{"false", false}, {"true", true}})
395           .IntoKey(M::PerfettoHprof)
396       .Ignore({
397           "-ea", "-da", "-enableassertions", "-disableassertions", "--runtime-arg", "-esa",
398           "-dsa", "-enablesystemassertions", "-disablesystemassertions", "-Xrs", "-Xint:_",
399           "-Xdexopt:_", "-Xnoquithandler", "-Xjnigreflimit:_", "-Xgenregmap", "-Xnogenregmap",
400           "-Xverifyopt:_", "-Xcheckdexsum", "-Xincludeselectedop", "-Xjitop:_",
401           "-Xincludeselectedmethod", "-Xjitthreshold:_",
402           "-Xjitblocking", "-Xjitmethod:_", "-Xjitclass:_", "-Xjitoffset:_",
403           "-Xjitconfig:_", "-Xjitcheckcg", "-Xjitverbose", "-Xjitprofile",
404           "-Xjitdisableopt", "-Xjitsuspendpoll", "-XX:mainThreadStackSize=_"})
405       .IgnoreUnrecognized(ignore_unrecognized);
406 
407   // TODO: Move Usage information into this DSL.
408 
409   return std::make_unique<RuntimeParser>(parser_builder->Build());
410 }
411 
412 #pragma GCC diagnostic pop
413 
414 // Remove all the special options that have something in the void* part of the option.
415 // If runtime_options is not null, put the options in there.
416 // As a side-effect, populate the hooks from options.
ProcessSpecialOptions(const RuntimeOptions & options,RuntimeArgumentMap * runtime_options,std::vector<std::string> * out_options)417 bool ParsedOptions::ProcessSpecialOptions(const RuntimeOptions& options,
418                                           RuntimeArgumentMap* runtime_options,
419                                           std::vector<std::string>* out_options) {
420   using M = RuntimeArgumentMap;
421 
422   // TODO: Move the below loop into JNI
423   // Handle special options that set up hooks
424   for (size_t i = 0; i < options.size(); ++i) {
425     const std::string option(options[i].first);
426       // TODO: support -Djava.class.path
427     if (option == "bootclasspath") {
428       auto boot_class_path = static_cast<std::vector<std::unique_ptr<const DexFile>>*>(
429           const_cast<void*>(options[i].second));
430 
431       if (runtime_options != nullptr) {
432         runtime_options->Set(M::BootClassPathDexList, boot_class_path);
433       }
434     } else if (option == "compilercallbacks") {
435       CompilerCallbacks* compiler_callbacks =
436           reinterpret_cast<CompilerCallbacks*>(const_cast<void*>(options[i].second));
437       if (runtime_options != nullptr) {
438         runtime_options->Set(M::CompilerCallbacksPtr, compiler_callbacks);
439       }
440     } else if (option == "imageinstructionset") {
441       const char* isa_str = reinterpret_cast<const char*>(options[i].second);
442       auto&& image_isa = GetInstructionSetFromString(isa_str);
443       if (image_isa == InstructionSet::kNone) {
444         Usage("%s is not a valid instruction set.", isa_str);
445         return false;
446       }
447       if (runtime_options != nullptr) {
448         runtime_options->Set(M::ImageInstructionSet, image_isa);
449       }
450     } else if (option == "sensitiveThread") {
451       const void* hook = options[i].second;
452       bool (*hook_is_sensitive_thread)() = reinterpret_cast<bool (*)()>(const_cast<void*>(hook));
453 
454       if (runtime_options != nullptr) {
455         runtime_options->Set(M::HookIsSensitiveThread, hook_is_sensitive_thread);
456       }
457     } else if (option == "vfprintf") {
458       const void* hook = options[i].second;
459       if (hook == nullptr) {
460         Usage("vfprintf argument was nullptr");
461         return false;
462       }
463       int (*hook_vfprintf)(FILE *, const char*, va_list) =
464           reinterpret_cast<int (*)(FILE *, const char*, va_list)>(const_cast<void*>(hook));
465 
466       if (runtime_options != nullptr) {
467         runtime_options->Set(M::HookVfprintf, hook_vfprintf);
468       }
469       hook_vfprintf_ = hook_vfprintf;
470     } else if (option == "exit") {
471       const void* hook = options[i].second;
472       if (hook == nullptr) {
473         Usage("exit argument was nullptr");
474         return false;
475       }
476       void(*hook_exit)(jint) = reinterpret_cast<void(*)(jint)>(const_cast<void*>(hook));
477       if (runtime_options != nullptr) {
478         runtime_options->Set(M::HookExit, hook_exit);
479       }
480       hook_exit_ = hook_exit;
481     } else if (option == "abort") {
482       const void* hook = options[i].second;
483       if (hook == nullptr) {
484         Usage("abort was nullptr\n");
485         return false;
486       }
487       void(*hook_abort)() = reinterpret_cast<void(*)()>(const_cast<void*>(hook));
488       if (runtime_options != nullptr) {
489         runtime_options->Set(M::HookAbort, hook_abort);
490       }
491       hook_abort_ = hook_abort;
492     } else {
493       // It is a regular option, that doesn't have a known 'second' value.
494       // Push it on to the regular options which will be parsed by our parser.
495       if (out_options != nullptr) {
496         out_options->push_back(option);
497       }
498     }
499   }
500 
501   return true;
502 }
503 
504 // Intended for local changes only.
MaybeOverrideVerbosity()505 static void MaybeOverrideVerbosity() {
506   //  gLogVerbosity.class_linker = true;  // TODO: don't check this in!
507   //  gLogVerbosity.collector = true;  // TODO: don't check this in!
508   //  gLogVerbosity.compiler = true;  // TODO: don't check this in!
509   //  gLogVerbosity.deopt = true;  // TODO: don't check this in!
510   //  gLogVerbosity.gc = true;  // TODO: don't check this in!
511   //  gLogVerbosity.heap = true;  // TODO: don't check this in!
512   //  gLogVerbosity.interpreter = true;  // TODO: don't check this in!
513   //  gLogVerbosity.jdwp = true;  // TODO: don't check this in!
514   //  gLogVerbosity.jit = true;  // TODO: don't check this in!
515   //  gLogVerbosity.jni = true;  // TODO: don't check this in!
516   //  gLogVerbosity.monitor = true;  // TODO: don't check this in!
517   //  gLogVerbosity.oat = true;  // TODO: don't check this in!
518   //  gLogVerbosity.profiler = true;  // TODO: don't check this in!
519   //  gLogVerbosity.signals = true;  // TODO: don't check this in!
520   //  gLogVerbosity.simulator = true; // TODO: don't check this in!
521   //  gLogVerbosity.startup = true;  // TODO: don't check this in!
522   //  gLogVerbosity.third_party_jni = true;  // TODO: don't check this in!
523   //  gLogVerbosity.threads = true;  // TODO: don't check this in!
524   //  gLogVerbosity.verifier = true;  // TODO: don't check this in!
525 }
526 
DoParse(const RuntimeOptions & options,bool ignore_unrecognized,RuntimeArgumentMap * runtime_options)527 bool ParsedOptions::DoParse(const RuntimeOptions& options,
528                             bool ignore_unrecognized,
529                             RuntimeArgumentMap* runtime_options) {
530   for (size_t i = 0; i < options.size(); ++i) {
531     if (true && options[0].first == "-Xzygote") {
532       LOG(INFO) << "option[" << i << "]=" << options[i].first;
533     }
534   }
535 
536   auto parser = MakeParser(ignore_unrecognized);
537 
538   // Convert to a simple string list (without the magic pointer options)
539   std::vector<std::string> argv_list;
540   if (!ProcessSpecialOptions(options, nullptr, &argv_list)) {
541     return false;
542   }
543 
544   CmdlineResult parse_result = parser->Parse(argv_list);
545 
546   // Handle parse errors by displaying the usage and potentially exiting.
547   if (parse_result.IsError()) {
548     if (parse_result.GetStatus() == CmdlineResult::kUsage) {
549       UsageMessage(stdout, "%s\n", parse_result.GetMessage().c_str());
550       Exit(0);
551     } else if (parse_result.GetStatus() == CmdlineResult::kUnknown && !ignore_unrecognized) {
552       Usage("%s\n", parse_result.GetMessage().c_str());
553       return false;
554     } else {
555       Usage("%s\n", parse_result.GetMessage().c_str());
556       Exit(0);
557     }
558 
559     UNREACHABLE();
560   }
561 
562   using M = RuntimeArgumentMap;
563   RuntimeArgumentMap args = parser->ReleaseArgumentsMap();
564 
565   // -help, -showversion, etc.
566   if (args.Exists(M::Help)) {
567     Usage(nullptr);
568     return false;
569   } else if (args.Exists(M::ShowVersion)) {
570     UsageMessage(stdout,
571                  "ART version %s %s\n",
572                  Runtime::GetVersion(),
573                  GetInstructionSetString(kRuntimeISA));
574     Exit(0);
575   } else if (args.Exists(M::BootClassPath)) {
576     LOG(INFO) << "setting boot class path to " << args.Get(M::BootClassPath)->Join();
577   }
578 
579   if (args.GetOrDefault(M::Interpret)) {
580     if (args.Exists(M::UseJitCompilation) && *args.Get(M::UseJitCompilation)) {
581       Usage("-Xusejit:true and -Xint cannot be specified together\n");
582       Exit(0);
583     }
584     args.Set(M::UseJitCompilation, false);
585   }
586 
587   // Set a default boot class path if we didn't get an explicit one via command line.
588   const char* env_bcp = getenv("BOOTCLASSPATH");
589   if (env_bcp != nullptr) {
590     args.SetIfMissing(M::BootClassPath, ParseStringList<':'>::Split(env_bcp));
591   }
592 
593   // Set a default class path if we didn't get an explicit one via command line.
594   if (getenv("CLASSPATH") != nullptr) {
595     args.SetIfMissing(M::ClassPath, std::string(getenv("CLASSPATH")));
596   }
597 
598   // Default to number of processors minus one since the main GC thread also does work.
599   args.SetIfMissing(M::ParallelGCThreads, gc::Heap::kDefaultEnableParallelGC ?
600       static_cast<unsigned int>(sysconf(_SC_NPROCESSORS_CONF) - 1u) : 0u);
601 
602   // -verbose:
603   {
604     LogVerbosity *log_verbosity = args.Get(M::Verbose);
605     if (log_verbosity != nullptr) {
606       gLogVerbosity = *log_verbosity;
607     }
608   }
609 
610   MaybeOverrideVerbosity();
611 
612   SetRuntimeDebugFlagsEnabled(args.GetOrDefault(M::SlowDebug));
613 
614   // -Xprofile:
615   Trace::SetDefaultClockSource(args.GetOrDefault(M::ProfileClock));
616 
617   if (!ProcessSpecialOptions(options, &args, nullptr)) {
618       return false;
619   }
620 
621   {
622     // If not set, background collector type defaults to homogeneous compaction.
623     // If not low memory mode, semispace otherwise.
624 
625     gc::CollectorType background_collector_type_;
626     gc::CollectorType collector_type_ = (XGcOption{}).collector_type_;
627     bool low_memory_mode_ = args.Exists(M::LowMemoryMode);
628 
629     background_collector_type_ = args.GetOrDefault(M::BackgroundGc);
630     {
631       XGcOption* xgc = args.Get(M::GcOption);
632       if (xgc != nullptr && xgc->collector_type_ != gc::kCollectorTypeNone) {
633         collector_type_ = xgc->collector_type_;
634       }
635     }
636 
637     if (background_collector_type_ == gc::kCollectorTypeNone) {
638       background_collector_type_ = low_memory_mode_ ?
639           gc::kCollectorTypeSS : gc::kCollectorTypeHomogeneousSpaceCompact;
640     }
641 
642     args.Set(M::BackgroundGc, BackgroundGcOption { background_collector_type_ });
643   }
644 
645   const ParseStringList<':'>* boot_class_path_locations = args.Get(M::BootClassPathLocations);
646   if (boot_class_path_locations != nullptr && boot_class_path_locations->Size() != 0u) {
647     const ParseStringList<':'>* boot_class_path = args.Get(M::BootClassPath);
648     if (boot_class_path == nullptr ||
649         boot_class_path_locations->Size() != boot_class_path->Size()) {
650       Usage("The number of boot class path files does not match"
651           " the number of boot class path locations given\n"
652           "  boot class path files     (%zu): %s\n"
653           "  boot class path locations (%zu): %s\n",
654           (boot_class_path != nullptr) ? boot_class_path->Size() : 0u,
655           (boot_class_path != nullptr) ? boot_class_path->Join().c_str() : "<nil>",
656           boot_class_path_locations->Size(),
657           boot_class_path_locations->Join().c_str());
658       return false;
659     }
660   }
661 
662   if (!args.Exists(M::CompilerCallbacksPtr) && !args.Exists(M::Image)) {
663     std::string image = GetDefaultBootImageLocation(GetAndroidRoot());
664     args.Set(M::Image, image);
665   }
666 
667   // 0 means no growth limit, and growth limit should be always <= heap size
668   if (args.GetOrDefault(M::HeapGrowthLimit) <= 0u ||
669       args.GetOrDefault(M::HeapGrowthLimit) > args.GetOrDefault(M::MemoryMaximumSize)) {
670     args.Set(M::HeapGrowthLimit, args.GetOrDefault(M::MemoryMaximumSize));
671   }
672 
673   *runtime_options = std::move(args);
674   return true;
675 }
676 
Exit(int status)677 void ParsedOptions::Exit(int status) {
678   hook_exit_(status);
679 }
680 
Abort()681 void ParsedOptions::Abort() {
682   hook_abort_();
683 }
684 
UsageMessageV(FILE * stream,const char * fmt,va_list ap)685 void ParsedOptions::UsageMessageV(FILE* stream, const char* fmt, va_list ap) {
686   hook_vfprintf_(stream, fmt, ap);
687 }
688 
UsageMessage(FILE * stream,const char * fmt,...)689 void ParsedOptions::UsageMessage(FILE* stream, const char* fmt, ...) {
690   va_list ap;
691   va_start(ap, fmt);
692   UsageMessageV(stream, fmt, ap);
693   va_end(ap);
694 }
695 
Usage(const char * fmt,...)696 void ParsedOptions::Usage(const char* fmt, ...) {
697   bool error = (fmt != nullptr);
698   FILE* stream = error ? stderr : stdout;
699 
700   if (fmt != nullptr) {
701     va_list ap;
702     va_start(ap, fmt);
703     UsageMessageV(stream, fmt, ap);
704     va_end(ap);
705   }
706 
707   const char* program = "dalvikvm";
708   UsageMessage(stream, "%s: [options] class [argument ...]\n", program);
709   UsageMessage(stream, "\n");
710   UsageMessage(stream, "The following standard options are supported:\n");
711   UsageMessage(stream, "  -classpath classpath (-cp classpath)\n");
712   UsageMessage(stream, "  -Dproperty=value\n");
713   UsageMessage(stream, "  -verbose:tag[,tag...] (currently valid tags: 'agents', 'class',\n"
714                        "    'collector', 'compiler', 'deopt', 'dex', 'gc', 'heap', 'image',\n"
715                        "    'interpreter', 'jdwp', 'jit', 'jni', 'monitor', 'oat', 'profiler',\n"
716                        "    'signals', 'simulator', 'startup', 'systrace-locks',\n"
717                        "    'third-party-jni', 'threads', 'verifier', 'verifier-debug')\n");
718   UsageMessage(stream, "  -showversion\n");
719   UsageMessage(stream, "  -help\n");
720   // TODO add back in once -agentlib actually does something.
721   // UsageMessage(stream, "  -agentlib:library=options (Experimental feature, "
722   //                      "requires -Xexperimental:agent, some features might not be supported)\n");
723   UsageMessage(stream, "  -agentpath:library_path=options (Experimental feature, requires\n"
724                        "    -Xexperimental:agent, some features might not be supported)\n");
725   UsageMessage(stream, "\n");
726 
727   UsageMessage(stream, "The following extended options are supported:\n");
728   UsageMessage(stream, "  -Xbootclasspath:bootclasspath\n");
729   UsageMessage(stream, "  -Xcheck:tag  (e.g. 'jni')\n");
730   UsageMessage(stream, "  -XmsN (min heap, must be multiple of 1K, >= 1MB)\n");
731   UsageMessage(stream, "  -XmxN (max heap, must be multiple of 1K, >= 2MB)\n");
732   UsageMessage(stream, "  -XssN (stack size)\n");
733   UsageMessage(stream, "  -Xint\n");
734   UsageMessage(stream, "\n");
735 
736   UsageMessage(stream, "The following Dalvik options are supported:\n");
737   UsageMessage(stream, "  -Xzygote\n");
738   UsageMessage(stream, "  -Xjnitrace:substring (eg NativeClass or nativeMethod)\n");
739   UsageMessage(stream, "  -Xgc:[no]preverify\n");
740   UsageMessage(stream, "  -Xgc:[no]postverify\n");
741   UsageMessage(stream, "  -XX:HeapGrowthLimit=N\n");
742   UsageMessage(stream, "  -XX:HeapMinFree=N\n");
743   UsageMessage(stream, "  -XX:HeapMaxFree=N\n");
744   UsageMessage(stream, "  -XX:NonMovingSpaceCapacity=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, "  -Xjitthreshold:integervalue\n");
750   UsageMessage(stream, "\n");
751 
752   UsageMessage(stream, "The following unique to ART options are supported:\n");
753   UsageMessage(stream, "  -Xgc:[no]preverify_rosalloc\n");
754   UsageMessage(stream, "  -Xgc:[no]postsweepingverify_rosalloc\n");
755   UsageMessage(stream, "  -Xgc:[no]postverify_rosalloc\n");
756   UsageMessage(stream, "  -Xgc:[no]presweepingverify\n");
757   UsageMessage(stream, "  -Xgc:[no]generational_cc\n");
758   UsageMessage(stream, "  -Ximage:filename\n");
759   UsageMessage(stream, "  -Xbootclasspath-locations:bootclasspath\n"
760                        "     (override the dex locations of the -Xbootclasspath files)\n");
761   UsageMessage(stream, "  -XX:+DisableExplicitGC\n");
762   UsageMessage(stream, "  -XX:ParallelGCThreads=integervalue\n");
763   UsageMessage(stream, "  -XX:ConcGCThreads=integervalue\n");
764   UsageMessage(stream, "  -XX:FinalizerTimeoutMs=integervalue\n");
765   UsageMessage(stream, "  -XX:MaxSpinsBeforeThinLockInflation=integervalue\n");
766   UsageMessage(stream, "  -XX:LongPauseLogThreshold=integervalue\n");
767   UsageMessage(stream, "  -XX:LongGCLogThreshold=integervalue\n");
768   UsageMessage(stream, "  -XX:ThreadSuspendTimeout=integervalue\n");
769   UsageMessage(stream, "  -XX:DumpGCPerformanceOnShutdown\n");
770   UsageMessage(stream, "  -XX:DumpJITInfoOnShutdown\n");
771   UsageMessage(stream, "  -XX:IgnoreMaxFootprint\n");
772   UsageMessage(stream, "  -XX:UseTLAB\n");
773   UsageMessage(stream, "  -XX:BackgroundGC=none\n");
774   UsageMessage(stream, "  -XX:LargeObjectSpace={disabled,map,freelist}\n");
775   UsageMessage(stream, "  -XX:LargeObjectThreshold=N\n");
776   UsageMessage(stream, "  -XX:StopForNativeAllocs=N\n");
777   UsageMessage(stream, "  -XX:DumpNativeStackOnSigQuit=booleanvalue\n");
778   UsageMessage(stream, "  -XX:MadviseRandomAccess:booleanvalue\n");
779   UsageMessage(stream, "  -XX:SlowDebug={false,true}\n");
780   UsageMessage(stream, "  -Xmethod-trace\n");
781   UsageMessage(stream, "  -Xmethod-trace-file:filename\n");
782   UsageMessage(stream, "  -Xmethod-trace-file-size:integervalue\n");
783   UsageMessage(stream, "  -Xps-min-save-period-ms:integervalue\n");
784   UsageMessage(stream, "  -Xps-save-resolved-classes-delay-ms:integervalue\n");
785   UsageMessage(stream, "  -Xps-hot-startup-method-samples:integervalue\n");
786   UsageMessage(stream, "  -Xps-min-methods-to-save:integervalue\n");
787   UsageMessage(stream, "  -Xps-min-classes-to-save:integervalue\n");
788   UsageMessage(stream, "  -Xps-min-notification-before-wake:integervalue\n");
789   UsageMessage(stream, "  -Xps-max-notification-before-wake:integervalue\n");
790   UsageMessage(stream, "  -Xps-profile-path:file-path\n");
791   UsageMessage(stream, "  -Xcompiler:filename\n");
792   UsageMessage(stream, "  -Xcompiler-option dex2oat-option\n");
793   UsageMessage(stream, "  -Ximage-compiler-option dex2oat-option\n");
794   UsageMessage(stream, "  -Xusejit:booleanvalue\n");
795   UsageMessage(stream, "  -Xjitinitialsize:N\n");
796   UsageMessage(stream, "  -Xjitmaxsize:N\n");
797   UsageMessage(stream, "  -Xjitwarmupthreshold:integervalue\n");
798   UsageMessage(stream, "  -Xjitosrthreshold:integervalue\n");
799   UsageMessage(stream, "  -Xjitprithreadweight:integervalue\n");
800   UsageMessage(stream, "  -X[no]relocate\n");
801   UsageMessage(stream, "  -X[no]dex2oat (Whether to invoke dex2oat on the application)\n");
802   UsageMessage(stream, "  -X[no]image-dex2oat (Whether to create and use a boot image)\n");
803   UsageMessage(stream, "  -Xno-dex-file-fallback "
804                        "(Don't fall back to dex files without oat files)\n");
805   UsageMessage(stream, "  -Xplugin:<library.so> "
806                        "(Load a runtime plugin, requires -Xexperimental:runtime-plugins)\n");
807   UsageMessage(stream, "  -Xexperimental:runtime-plugins"
808                        "(Enable new and experimental agent support)\n");
809   UsageMessage(stream, "  -Xexperimental:agents"
810                        "(Enable new and experimental agent support)\n");
811   UsageMessage(stream, "  -Xopaque-jni-ids:{true,false,swapable}");
812   UsageMessage(stream, "(Use opauque integers for jni ids, yes, no or punt for later)\n");
813   UsageMessage(stream, "\n");
814 
815   UsageMessage(stream, "The following previously supported Dalvik options are ignored:\n");
816   UsageMessage(stream, "  -ea[:<package name>... |:<class name>]\n");
817   UsageMessage(stream, "  -da[:<package name>... |:<class name>]\n");
818   UsageMessage(stream, "   (-enableassertions, -disableassertions)\n");
819   UsageMessage(stream, "  -esa\n");
820   UsageMessage(stream, "  -dsa\n");
821   UsageMessage(stream, "   (-enablesystemassertions, -disablesystemassertions)\n");
822   UsageMessage(stream, "  -Xverify:{none,remote,all,softfail}\n");
823   UsageMessage(stream, "  -Xrs\n");
824   UsageMessage(stream, "  -Xint:portable, -Xint:fast, -Xint:jit\n");
825   UsageMessage(stream, "  -Xdexopt:{none,verified,all,full}\n");
826   UsageMessage(stream, "  -Xnoquithandler\n");
827   UsageMessage(stream, "  -Xjniopts:{warnonly,forcecopy}\n");
828   UsageMessage(stream, "  -Xjnigreflimit:integervalue\n");
829   UsageMessage(stream, "  -Xgc:[no]precise\n");
830   UsageMessage(stream, "  -Xgc:[no]verifycardtable\n");
831   UsageMessage(stream, "  -X[no]genregmap\n");
832   UsageMessage(stream, "  -Xverifyopt:[no]checkmon\n");
833   UsageMessage(stream, "  -Xcheckdexsum\n");
834   UsageMessage(stream, "  -Xincludeselectedop\n");
835   UsageMessage(stream, "  -Xjitop:hexopvalue[-endvalue][,hexopvalue[-endvalue]]*\n");
836   UsageMessage(stream, "  -Xincludeselectedmethod\n");
837   UsageMessage(stream, "  -Xjitblocking\n");
838   UsageMessage(stream, "  -Xjitmethod:signature[,signature]* (eg Ljava/lang/String\\;replace)\n");
839   UsageMessage(stream, "  -Xjitclass:classname[,classname]*\n");
840   UsageMessage(stream, "  -Xjitcodecachesize:N\n");
841   UsageMessage(stream, "  -Xjitoffset:offset[,offset]\n");
842   UsageMessage(stream, "  -Xjitconfig:filename\n");
843   UsageMessage(stream, "  -Xjitcheckcg\n");
844   UsageMessage(stream, "  -Xjitverbose\n");
845   UsageMessage(stream, "  -Xjitprofile\n");
846   UsageMessage(stream, "  -Xjitdisableopt\n");
847   UsageMessage(stream, "  -Xjitsuspendpoll\n");
848   UsageMessage(stream, "  -XX:mainThreadStackSize=N\n");
849   UsageMessage(stream, "\n");
850 
851   Exit((error) ? 1 : 0);
852 }
853 
854 }  // namespace art
855