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