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