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