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