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