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