1 /*
2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "classfile/classLoader.hpp"
27 #include "classfile/javaAssertions.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "compiler/compilerOracle.hpp"
30 #include "memory/allocation.inline.hpp"
31 #include "memory/cardTableRS.hpp"
32 #include "memory/genCollectedHeap.hpp"
33 #include "memory/referenceProcessor.hpp"
34 #include "memory/universe.inline.hpp"
35 #include "oops/oop.inline.hpp"
36 #include "prims/jvmtiExport.hpp"
37 #include "runtime/arguments.hpp"
38 #include "runtime/arguments_ext.hpp"
39 #include "runtime/globals_extension.hpp"
40 #include "runtime/java.hpp"
41 #include "services/management.hpp"
42 #include "services/memTracker.hpp"
43 #include "utilities/defaultStream.hpp"
44 #include "utilities/macros.hpp"
45 #include "utilities/stringUtils.hpp"
46 #include "utilities/taskqueue.hpp"
47 #if INCLUDE_JFR
48 #include "jfr/jfr.hpp"
49 #endif
50 #ifdef TARGET_OS_FAMILY_linux
51 # include "os_linux.inline.hpp"
52 #endif
53 #ifdef TARGET_OS_FAMILY_solaris
54 # include "os_solaris.inline.hpp"
55 #endif
56 #ifdef TARGET_OS_FAMILY_windows
57 # include "os_windows.inline.hpp"
58 #endif
59 #ifdef TARGET_OS_FAMILY_aix
60 # include "os_aix.inline.hpp"
61 #endif
62 #ifdef TARGET_OS_FAMILY_bsd
63 # include "os_bsd.inline.hpp"
64 #endif
65 #if INCLUDE_ALL_GCS
66 #include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
67 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
68 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
69 #endif // INCLUDE_ALL_GCS
70 
71 // Note: This is a special bug reporting site for the JVM
72 #ifdef VENDOR_URL_VM_BUG
73 # define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG
74 #else
75 # define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
76 #endif
77 #define DEFAULT_JAVA_LAUNCHER  "generic"
78 
79 // Disable options not supported in this release, with a warning if they
80 // were explicitly requested on the command-line
81 #define UNSUPPORTED_OPTION(opt, description)                    \
82 do {                                                            \
83   if (opt) {                                                    \
84     if (FLAG_IS_CMDLINE(opt)) {                                 \
85       warning(description " is disabled in this release.");     \
86     }                                                           \
87     FLAG_SET_DEFAULT(opt, false);                               \
88   }                                                             \
89 } while(0)
90 
91 #define UNSUPPORTED_GC_OPTION(gc)                                     \
92 do {                                                                  \
93   if (gc) {                                                           \
94     if (FLAG_IS_CMDLINE(gc)) {                                        \
95       warning(#gc " is not supported in this VM.  Using Serial GC."); \
96     }                                                                 \
97     FLAG_SET_DEFAULT(gc, false);                                      \
98   }                                                                   \
99 } while(0)
100 
101 char**  Arguments::_jvm_flags_array             = NULL;
102 int     Arguments::_num_jvm_flags               = 0;
103 char**  Arguments::_jvm_args_array              = NULL;
104 int     Arguments::_num_jvm_args                = 0;
105 char*  Arguments::_java_command                 = NULL;
106 SystemProperty* Arguments::_system_properties   = NULL;
107 const char*  Arguments::_gc_log_filename        = NULL;
108 bool   Arguments::_has_profile                  = false;
109 size_t Arguments::_conservative_max_heap_alignment = 0;
110 uintx  Arguments::_min_heap_size                = 0;
111 uintx  Arguments::_min_heap_free_ratio          = 0;
112 uintx  Arguments::_max_heap_free_ratio          = 0;
113 Arguments::Mode Arguments::_mode                = _mixed;
114 bool   Arguments::_java_compiler                = false;
115 bool   Arguments::_xdebug_mode                  = false;
116 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
117 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
118 int    Arguments::_sun_java_launcher_pid        = -1;
119 bool   Arguments::_created_by_gamma_launcher    = false;
120 
121 // These parameters are reset in method parse_vm_init_args(JavaVMInitArgs*)
122 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
123 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
124 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
125 bool   Arguments::_ClipInlining                 = ClipInlining;
126 
127 char*  Arguments::SharedArchivePath             = NULL;
128 
129 AgentLibraryList Arguments::_libraryList;
130 AgentLibraryList Arguments::_agentList;
131 
132 abort_hook_t     Arguments::_abort_hook         = NULL;
133 exit_hook_t      Arguments::_exit_hook          = NULL;
134 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
135 
136 
137 SystemProperty *Arguments::_java_ext_dirs = NULL;
138 SystemProperty *Arguments::_java_endorsed_dirs = NULL;
139 SystemProperty *Arguments::_sun_boot_library_path = NULL;
140 SystemProperty *Arguments::_java_library_path = NULL;
141 SystemProperty *Arguments::_java_home = NULL;
142 SystemProperty *Arguments::_java_class_path = NULL;
143 SystemProperty *Arguments::_sun_boot_class_path = NULL;
144 
145 char* Arguments::_meta_index_path = NULL;
146 char* Arguments::_meta_index_dir = NULL;
147 
148 // Check if head of 'option' matches 'name', and sets 'tail' remaining part of option string
149 
match_option(const JavaVMOption * option,const char * name,const char ** tail)150 static bool match_option(const JavaVMOption *option, const char* name,
151                          const char** tail) {
152   int len = (int)strlen(name);
153   if (strncmp(option->optionString, name, len) == 0) {
154     *tail = option->optionString + len;
155     return true;
156   } else {
157     return false;
158   }
159 }
160 
161 #if INCLUDE_JFR
162 // return true on failure
match_jfr_option(const JavaVMOption ** option)163 static bool match_jfr_option(const JavaVMOption** option) {
164   assert((*option)->optionString != NULL, "invariant");
165   char* tail = NULL;
166   if (match_option(*option, "-XX:StartFlightRecording", (const char**)&tail)) {
167     return Jfr::on_start_flight_recording_option(option, tail);
168   } else if (match_option(*option, "-XX:FlightRecorderOptions", (const char**)&tail)) {
169     return Jfr::on_flight_recorder_option(option, tail);
170   }
171   return false;
172 }
173 #endif
174 
logOption(const char * opt)175 static void logOption(const char* opt) {
176   if (PrintVMOptions) {
177     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
178   }
179 }
180 
181 // Process java launcher properties.
process_sun_java_launcher_properties(JavaVMInitArgs * args)182 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
183   // See if sun.java.launcher or sun.java.launcher.pid is defined.
184   // Must do this before setting up other system properties,
185   // as some of them may depend on launcher type.
186   for (int index = 0; index < args->nOptions; index++) {
187     const JavaVMOption* option = args->options + index;
188     const char* tail;
189 
190     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
191       process_java_launcher_argument(tail, option->extraInfo);
192       continue;
193     }
194     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
195       _sun_java_launcher_pid = atoi(tail);
196       continue;
197     }
198   }
199 }
200 
201 // Initialize system properties key and value.
init_system_properties()202 void Arguments::init_system_properties() {
203 
204   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
205                                                                  "Java Virtual Machine Specification",  false));
206   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
207   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
208   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
209 
210   // following are JVMTI agent writeable properties.
211   // Properties values are set to NULL and they are
212   // os specific they are initialized in os::init_system_properties_values().
213   _java_ext_dirs = new SystemProperty("java.ext.dirs", NULL,  true);
214   _java_endorsed_dirs = new SystemProperty("java.endorsed.dirs", NULL,  true);
215   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
216   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
217   _java_home =  new SystemProperty("java.home", NULL,  true);
218   _sun_boot_class_path = new SystemProperty("sun.boot.class.path", NULL,  true);
219 
220   _java_class_path = new SystemProperty("java.class.path", "",  true);
221 
222   // Add to System Property list.
223   PropertyList_add(&_system_properties, _java_ext_dirs);
224   PropertyList_add(&_system_properties, _java_endorsed_dirs);
225   PropertyList_add(&_system_properties, _sun_boot_library_path);
226   PropertyList_add(&_system_properties, _java_library_path);
227   PropertyList_add(&_system_properties, _java_home);
228   PropertyList_add(&_system_properties, _java_class_path);
229   PropertyList_add(&_system_properties, _sun_boot_class_path);
230 
231   // Set OS specific system properties values
232   os::init_system_properties_values();
233 }
234 
235 
236   // Update/Initialize System properties after JDK version number is known
init_version_specific_system_properties()237 void Arguments::init_version_specific_system_properties() {
238   enum { bufsz = 16 };
239   char buffer[bufsz];
240   const char* spec_vendor = "Sun Microsystems Inc.";
241   uint32_t spec_version = 0;
242 
243   if (JDK_Version::is_gte_jdk17x_version()) {
244     spec_vendor = "Oracle Corporation";
245     spec_version = JDK_Version::current().major_version();
246   }
247   jio_snprintf(buffer, bufsz, "1." UINT32_FORMAT, spec_version);
248 
249   PropertyList_add(&_system_properties,
250       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
251   PropertyList_add(&_system_properties,
252       new SystemProperty("java.vm.specification.version", buffer, false));
253   PropertyList_add(&_system_properties,
254       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
255 }
256 
257 /**
258  * Provide a slightly more user-friendly way of eliminating -XX flags.
259  * When a flag is eliminated, it can be added to this list in order to
260  * continue accepting this flag on the command-line, while issuing a warning
261  * and ignoring the value.  Once the JDK version reaches the 'accept_until'
262  * limit, we flatly refuse to admit the existence of the flag.  This allows
263  * a flag to die correctly over JDK releases using HSX.
264  */
265 typedef struct {
266   const char* name;
267   JDK_Version obsoleted_in; // when the flag went away
268   JDK_Version accept_until; // which version to start denying the existence
269 } ObsoleteFlag;
270 
271 static ObsoleteFlag obsolete_jvm_flags[] = {
272   { "UseTrainGC",                    JDK_Version::jdk(5), JDK_Version::jdk(7) },
273   { "UseSpecialLargeObjectHandling", JDK_Version::jdk(5), JDK_Version::jdk(7) },
274   { "UseOversizedCarHandling",       JDK_Version::jdk(5), JDK_Version::jdk(7) },
275   { "TraceCarAllocation",            JDK_Version::jdk(5), JDK_Version::jdk(7) },
276   { "PrintTrainGCProcessingStats",   JDK_Version::jdk(5), JDK_Version::jdk(7) },
277   { "LogOfCarSpaceSize",             JDK_Version::jdk(5), JDK_Version::jdk(7) },
278   { "OversizedCarThreshold",         JDK_Version::jdk(5), JDK_Version::jdk(7) },
279   { "MinTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
280   { "DefaultTickInterval",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
281   { "MaxTickInterval",               JDK_Version::jdk(5), JDK_Version::jdk(7) },
282   { "DelayTickAdjustment",           JDK_Version::jdk(5), JDK_Version::jdk(7) },
283   { "ProcessingToTenuringRatio",     JDK_Version::jdk(5), JDK_Version::jdk(7) },
284   { "MinTrainLength",                JDK_Version::jdk(5), JDK_Version::jdk(7) },
285   { "AppendRatio",         JDK_Version::jdk_update(6,10), JDK_Version::jdk(7) },
286   { "DefaultMaxRAM",       JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
287   { "DefaultInitialRAMFraction",
288                            JDK_Version::jdk_update(6,18), JDK_Version::jdk(7) },
289   { "UseDepthFirstScavengeOrder",
290                            JDK_Version::jdk_update(6,22), JDK_Version::jdk(7) },
291   { "HandlePromotionFailure",
292                            JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
293   { "MaxLiveObjectEvacuationRatio",
294                            JDK_Version::jdk_update(6,24), JDK_Version::jdk(8) },
295   { "ForceSharedSpaces",   JDK_Version::jdk_update(6,25), JDK_Version::jdk(8) },
296   { "UseParallelOldGCCompacting",
297                            JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
298   { "UseParallelDensePrefixUpdate",
299                            JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
300   { "UseParallelOldGCDensePrefix",
301                            JDK_Version::jdk_update(6,27), JDK_Version::jdk(8) },
302   { "AllowTransitionalJSR292",       JDK_Version::jdk(7), JDK_Version::jdk(8) },
303   { "UseCompressedStrings",          JDK_Version::jdk(7), JDK_Version::jdk(8) },
304   { "CMSPermGenPrecleaningEnabled", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
305   { "CMSTriggerPermRatio", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
306   { "CMSInitiatingPermOccupancyFraction", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
307   { "AdaptivePermSizeWeight", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
308   { "PermGenPadding", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
309   { "PermMarkSweepDeadRatio", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
310   { "PermSize", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
311   { "MaxPermSize", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
312   { "MinPermHeapExpansion", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
313   { "MaxPermHeapExpansion", JDK_Version::jdk(8),  JDK_Version::jdk(9) },
314   { "CMSRevisitStackSize",           JDK_Version::jdk(8), JDK_Version::jdk(9) },
315   { "PrintRevisitStats",             JDK_Version::jdk(8), JDK_Version::jdk(9) },
316   { "UseVectoredExceptions",         JDK_Version::jdk(8), JDK_Version::jdk(9) },
317   { "UseSplitVerifier",              JDK_Version::jdk(8), JDK_Version::jdk(9) },
318   { "UseISM",                        JDK_Version::jdk(8), JDK_Version::jdk(9) },
319   { "UsePermISM",                    JDK_Version::jdk(8), JDK_Version::jdk(9) },
320   { "UseMPSS",                       JDK_Version::jdk(8), JDK_Version::jdk(9) },
321   { "UseStringCache",                JDK_Version::jdk(8), JDK_Version::jdk(9) },
322   { "UseOldInlining",                JDK_Version::jdk_update(8, 20), JDK_Version::jdk(10) },
323   { "AutoShutdownNMT",               JDK_Version::jdk_update(8, 40), JDK_Version::jdk(10) },
324   { "CompilationRepeat",             JDK_Version::jdk(8), JDK_Version::jdk(9) },
325   { "SegmentedHeapDumpThreshold",    JDK_Version::jdk_update(8, 252), JDK_Version::jdk(10) },
326 #ifdef PRODUCT
327   { "DesiredMethodLimit",
328                            JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
329 #endif // PRODUCT
330   { NULL, JDK_Version(0), JDK_Version(0) }
331 };
332 
333 // Returns true if the flag is obsolete and fits into the range specified
334 // for being ignored.  In the case that the flag is ignored, the 'version'
335 // value is filled in with the version number when the flag became
336 // obsolete so that that value can be displayed to the user.
is_newly_obsolete(const char * s,JDK_Version * version)337 bool Arguments::is_newly_obsolete(const char *s, JDK_Version* version) {
338   int i = 0;
339   assert(version != NULL, "Must provide a version buffer");
340   while (obsolete_jvm_flags[i].name != NULL) {
341     const ObsoleteFlag& flag_status = obsolete_jvm_flags[i];
342     // <flag>=xxx form
343     // [-|+]<flag> form
344     if ((strncmp(flag_status.name, s, strlen(flag_status.name)) == 0) ||
345         ((s[0] == '+' || s[0] == '-') &&
346         (strncmp(flag_status.name, &s[1], strlen(flag_status.name)) == 0))) {
347       if (JDK_Version::current().compare(flag_status.accept_until) == -1) {
348           *version = flag_status.obsoleted_in;
349           return true;
350       }
351     }
352     i++;
353   }
354   return false;
355 }
356 
357 // Constructs the system class path (aka boot class path) from the following
358 // components, in order:
359 //
360 //     prefix           // from -Xbootclasspath/p:...
361 //     endorsed         // the expansion of -Djava.endorsed.dirs=...
362 //     base             // from os::get_system_properties() or -Xbootclasspath=
363 //     suffix           // from -Xbootclasspath/a:...
364 //
365 // java.endorsed.dirs is a list of directories; any jar or zip files in the
366 // directories are added to the sysclasspath just before the base.
367 //
368 // This could be AllStatic, but it isn't needed after argument processing is
369 // complete.
370 class SysClassPath: public StackObj {
371 public:
372   SysClassPath(const char* base);
373   ~SysClassPath();
374 
375   inline void set_base(const char* base);
376   inline void add_prefix(const char* prefix);
377   inline void add_suffix_to_prefix(const char* suffix);
378   inline void add_suffix(const char* suffix);
379   inline void reset_path(const char* base);
380 
381   // Expand the jar/zip files in each directory listed by the java.endorsed.dirs
382   // property.  Must be called after all command-line arguments have been
383   // processed (in particular, -Djava.endorsed.dirs=...) and before calling
384   // combined_path().
385   void expand_endorsed();
386 
get_base() const387   inline const char* get_base()     const { return _items[_scp_base]; }
get_prefix() const388   inline const char* get_prefix()   const { return _items[_scp_prefix]; }
get_suffix() const389   inline const char* get_suffix()   const { return _items[_scp_suffix]; }
get_endorsed() const390   inline const char* get_endorsed() const { return _items[_scp_endorsed]; }
391 
392   // Combine all the components into a single c-heap-allocated string; caller
393   // must free the string if/when no longer needed.
394   char* combined_path();
395 
396 private:
397   // Utility routines.
398   static char* add_to_path(const char* path, const char* str, bool prepend);
399   static char* add_jars_to_path(char* path, const char* directory);
400 
401   inline void reset_item_at(int index);
402 
403   // Array indices for the items that make up the sysclasspath.  All except the
404   // base are allocated in the C heap and freed by this class.
405   enum {
406     _scp_prefix,        // from -Xbootclasspath/p:...
407     _scp_endorsed,      // the expansion of -Djava.endorsed.dirs=...
408     _scp_base,          // the default sysclasspath
409     _scp_suffix,        // from -Xbootclasspath/a:...
410     _scp_nitems         // the number of items, must be last.
411   };
412 
413   const char* _items[_scp_nitems];
414   DEBUG_ONLY(bool _expansion_done;)
415 };
416 
SysClassPath(const char * base)417 SysClassPath::SysClassPath(const char* base) {
418   memset(_items, 0, sizeof(_items));
419   _items[_scp_base] = base;
420   DEBUG_ONLY(_expansion_done = false;)
421 }
422 
~SysClassPath()423 SysClassPath::~SysClassPath() {
424   // Free everything except the base.
425   for (int i = 0; i < _scp_nitems; ++i) {
426     if (i != _scp_base) reset_item_at(i);
427   }
428   DEBUG_ONLY(_expansion_done = false;)
429 }
430 
set_base(const char * base)431 inline void SysClassPath::set_base(const char* base) {
432   _items[_scp_base] = base;
433 }
434 
add_prefix(const char * prefix)435 inline void SysClassPath::add_prefix(const char* prefix) {
436   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], prefix, true);
437 }
438 
add_suffix_to_prefix(const char * suffix)439 inline void SysClassPath::add_suffix_to_prefix(const char* suffix) {
440   _items[_scp_prefix] = add_to_path(_items[_scp_prefix], suffix, false);
441 }
442 
add_suffix(const char * suffix)443 inline void SysClassPath::add_suffix(const char* suffix) {
444   _items[_scp_suffix] = add_to_path(_items[_scp_suffix], suffix, false);
445 }
446 
reset_item_at(int index)447 inline void SysClassPath::reset_item_at(int index) {
448   assert(index < _scp_nitems && index != _scp_base, "just checking");
449   if (_items[index] != NULL) {
450     FREE_C_HEAP_ARRAY(char, _items[index], mtInternal);
451     _items[index] = NULL;
452   }
453 }
454 
reset_path(const char * base)455 inline void SysClassPath::reset_path(const char* base) {
456   // Clear the prefix and suffix.
457   reset_item_at(_scp_prefix);
458   reset_item_at(_scp_suffix);
459   set_base(base);
460 }
461 
462 //------------------------------------------------------------------------------
463 
expand_endorsed()464 void SysClassPath::expand_endorsed() {
465   assert(_items[_scp_endorsed] == NULL, "can only be called once.");
466 
467   const char* path = Arguments::get_property("java.endorsed.dirs");
468   if (path == NULL) {
469     path = Arguments::get_endorsed_dir();
470     assert(path != NULL, "no default for java.endorsed.dirs");
471   }
472 
473   char* expanded_path = NULL;
474   const char separator = *os::path_separator();
475   const char* const end = path + strlen(path);
476   while (path < end) {
477     const char* tmp_end = strchr(path, separator);
478     if (tmp_end == NULL) {
479       expanded_path = add_jars_to_path(expanded_path, path);
480       path = end;
481     } else {
482       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
483       memcpy(dirpath, path, tmp_end - path);
484       dirpath[tmp_end - path] = '\0';
485       expanded_path = add_jars_to_path(expanded_path, dirpath);
486       FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);
487       path = tmp_end + 1;
488     }
489   }
490   _items[_scp_endorsed] = expanded_path;
491   DEBUG_ONLY(_expansion_done = true;)
492 }
493 
494 // Combine the bootclasspath elements, some of which may be null, into a single
495 // c-heap-allocated string.
combined_path()496 char* SysClassPath::combined_path() {
497   assert(_items[_scp_base] != NULL, "empty default sysclasspath");
498   assert(_expansion_done, "must call expand_endorsed() first.");
499 
500   size_t lengths[_scp_nitems];
501   size_t total_len = 0;
502 
503   const char separator = *os::path_separator();
504 
505   // Get the lengths.
506   int i;
507   for (i = 0; i < _scp_nitems; ++i) {
508     if (_items[i] != NULL) {
509       lengths[i] = strlen(_items[i]);
510       // Include space for the separator char (or a NULL for the last item).
511       total_len += lengths[i] + 1;
512     }
513   }
514   assert(total_len > 0, "empty sysclasspath not allowed");
515 
516   // Copy the _items to a single string.
517   char* cp = NEW_C_HEAP_ARRAY(char, total_len, mtInternal);
518   char* cp_tmp = cp;
519   for (i = 0; i < _scp_nitems; ++i) {
520     if (_items[i] != NULL) {
521       memcpy(cp_tmp, _items[i], lengths[i]);
522       cp_tmp += lengths[i];
523       *cp_tmp++ = separator;
524     }
525   }
526   *--cp_tmp = '\0';     // Replace the extra separator.
527   return cp;
528 }
529 
530 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
531 char*
add_to_path(const char * path,const char * str,bool prepend)532 SysClassPath::add_to_path(const char* path, const char* str, bool prepend) {
533   char *cp;
534 
535   assert(str != NULL, "just checking");
536   if (path == NULL) {
537     size_t len = strlen(str) + 1;
538     cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
539     memcpy(cp, str, len);                       // copy the trailing null
540   } else {
541     const char separator = *os::path_separator();
542     size_t old_len = strlen(path);
543     size_t str_len = strlen(str);
544     size_t len = old_len + str_len + 2;
545 
546     if (prepend) {
547       cp = NEW_C_HEAP_ARRAY(char, len, mtInternal);
548       char* cp_tmp = cp;
549       memcpy(cp_tmp, str, str_len);
550       cp_tmp += str_len;
551       *cp_tmp = separator;
552       memcpy(++cp_tmp, path, old_len + 1);      // copy the trailing null
553       FREE_C_HEAP_ARRAY(char, path, mtInternal);
554     } else {
555       cp = REALLOC_C_HEAP_ARRAY(char, path, len, mtInternal);
556       char* cp_tmp = cp + old_len;
557       *cp_tmp = separator;
558       memcpy(++cp_tmp, str, str_len + 1);       // copy the trailing null
559     }
560   }
561   return cp;
562 }
563 
564 // Scan the directory and append any jar or zip files found to path.
565 // Note:  path must be c-heap-allocated (or NULL); it is freed if non-null.
add_jars_to_path(char * path,const char * directory)566 char* SysClassPath::add_jars_to_path(char* path, const char* directory) {
567   DIR* dir = os::opendir(directory);
568   if (dir == NULL) return path;
569 
570   char dir_sep[2] = { '\0', '\0' };
571   size_t directory_len = strlen(directory);
572   const char fileSep = *os::file_separator();
573   if (directory[directory_len - 1] != fileSep) dir_sep[0] = fileSep;
574 
575   /* Scan the directory for jars/zips, appending them to path. */
576   struct dirent *entry;
577   while ((entry = os::readdir(dir)) != NULL) {
578     const char* name = entry->d_name;
579     const char* ext = name + strlen(name) - 4;
580     bool isJarOrZip = ext > name &&
581       (os::file_name_strcmp(ext, ".jar") == 0 ||
582        os::file_name_strcmp(ext, ".zip") == 0);
583     if (isJarOrZip) {
584       size_t length = directory_len + 2 + strlen(name);
585       char* jarpath = NEW_C_HEAP_ARRAY(char, length, mtInternal);
586       jio_snprintf(jarpath, length, "%s%s%s", directory, dir_sep, name);
587       path = add_to_path(path, jarpath, false);
588       FREE_C_HEAP_ARRAY(char, jarpath, mtInternal);
589     }
590   }
591   os::closedir(dir);
592   return path;
593 }
594 
595 // Parses a memory size specification string.
atomull(const char * s,julong * result)596 static bool atomull(const char *s, julong* result) {
597   julong n = 0;
598   int args_read = sscanf(s, JULONG_FORMAT, &n);
599   if (args_read != 1) {
600     return false;
601   }
602   while (*s != '\0' && isdigit(*s)) {
603     s++;
604   }
605   // 4705540: illegal if more characters are found after the first non-digit
606   if (strlen(s) > 1) {
607     return false;
608   }
609   switch (*s) {
610     case 'T': case 't':
611       *result = n * G * K;
612       // Check for overflow.
613       if (*result/((julong)G * K) != n) return false;
614       return true;
615     case 'G': case 'g':
616       *result = n * G;
617       if (*result/G != n) return false;
618       return true;
619     case 'M': case 'm':
620       *result = n * M;
621       if (*result/M != n) return false;
622       return true;
623     case 'K': case 'k':
624       *result = n * K;
625       if (*result/K != n) return false;
626       return true;
627     case '\0':
628       *result = n;
629       return true;
630     default:
631       return false;
632   }
633 }
634 
check_memory_size(julong size,julong min_size)635 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
636   if (size < min_size) return arg_too_small;
637   // Check that size will fit in a size_t (only relevant on 32-bit)
638   if (size > max_uintx) return arg_too_big;
639   return arg_in_range;
640 }
641 
642 // Describe an argument out of range error
describe_range_error(ArgsRange errcode)643 void Arguments::describe_range_error(ArgsRange errcode) {
644   switch(errcode) {
645   case arg_too_big:
646     jio_fprintf(defaultStream::error_stream(),
647                 "The specified size exceeds the maximum "
648                 "representable size.\n");
649     break;
650   case arg_too_small:
651   case arg_unreadable:
652   case arg_in_range:
653     // do nothing for now
654     break;
655   default:
656     ShouldNotReachHere();
657   }
658 }
659 
set_bool_flag(char * name,bool value,Flag::Flags origin)660 static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
661   return CommandLineFlags::boolAtPut(name, &value, origin);
662 }
663 
set_fp_numeric_flag(char * name,char * value,Flag::Flags origin)664 static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
665   double v;
666   if (sscanf(value, "%lf", &v) != 1) {
667     return false;
668   }
669 
670   if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
671     return true;
672   }
673   return false;
674 }
675 
set_numeric_flag(char * name,char * value,Flag::Flags origin)676 static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
677   julong v;
678   intx intx_v;
679   bool is_neg = false;
680   // Check the sign first since atomull() parses only unsigned values.
681   if (*value == '-') {
682     if (!CommandLineFlags::intxAt(name, &intx_v)) {
683       return false;
684     }
685     value++;
686     is_neg = true;
687   }
688   if (!atomull(value, &v)) {
689     return false;
690   }
691   intx_v = (intx) v;
692   if (is_neg) {
693     intx_v = -intx_v;
694   }
695   if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
696     return true;
697   }
698   uintx uintx_v = (uintx) v;
699   if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
700     return true;
701   }
702   uint64_t uint64_t_v = (uint64_t) v;
703   if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
704     return true;
705   }
706   return false;
707 }
708 
set_string_flag(char * name,const char * value,Flag::Flags origin)709 static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
710   if (!CommandLineFlags::ccstrAtPut(name, &value, origin))  return false;
711   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
712   FREE_C_HEAP_ARRAY(char, value, mtInternal);
713   return true;
714 }
715 
append_to_string_flag(char * name,const char * new_value,Flag::Flags origin)716 static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
717   const char* old_value = "";
718   if (!CommandLineFlags::ccstrAt(name, &old_value))  return false;
719   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
720   size_t new_len = strlen(new_value);
721   const char* value;
722   char* free_this_too = NULL;
723   if (old_len == 0) {
724     value = new_value;
725   } else if (new_len == 0) {
726     value = old_value;
727   } else {
728     size_t length = old_len + 1 + new_len + 1;
729     char* buf = NEW_C_HEAP_ARRAY(char, length, mtInternal);
730     // each new setting adds another LINE to the switch:
731     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
732     value = buf;
733     free_this_too = buf;
734   }
735   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
736   // CommandLineFlags always returns a pointer that needs freeing.
737   FREE_C_HEAP_ARRAY(char, value, mtInternal);
738   if (free_this_too != NULL) {
739     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
740     FREE_C_HEAP_ARRAY(char, free_this_too, mtInternal);
741   }
742   return true;
743 }
744 
parse_argument(const char * arg,Flag::Flags origin)745 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
746 
747   // range of acceptable characters spelled out for portability reasons
748 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
749 #define BUFLEN 255
750   char name[BUFLEN+1];
751   char dummy;
752 
753   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
754     return set_bool_flag(name, false, origin);
755   }
756   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
757     return set_bool_flag(name, true, origin);
758   }
759 
760   char punct;
761   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
762     const char* value = strchr(arg, '=') + 1;
763     Flag* flag = Flag::find_flag(name, strlen(name));
764     if (flag != NULL && flag->is_ccstr()) {
765       if (flag->ccstr_accumulates()) {
766         return append_to_string_flag(name, value, origin);
767       } else {
768         if (value[0] == '\0') {
769           value = NULL;
770         }
771         return set_string_flag(name, value, origin);
772       }
773     }
774   }
775 
776   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
777     const char* value = strchr(arg, '=') + 1;
778     // -XX:Foo:=xxx will reset the string flag to the given value.
779     if (value[0] == '\0') {
780       value = NULL;
781     }
782     return set_string_flag(name, value, origin);
783   }
784 
785 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
786 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
787 #define        NUMBER_RANGE    "[0123456789]"
788   char value[BUFLEN + 1];
789   char value2[BUFLEN + 1];
790   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
791     // Looks like a floating-point number -- try again with more lenient format string
792     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
793       return set_fp_numeric_flag(name, value, origin);
794     }
795   }
796 
797 #define VALUE_RANGE "[-kmgtKMGT0123456789]"
798   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
799     return set_numeric_flag(name, value, origin);
800   }
801 
802   return false;
803 }
804 
add_string(char *** bldarray,int * count,const char * arg)805 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
806   assert(bldarray != NULL, "illegal argument");
807 
808   if (arg == NULL) {
809     return;
810   }
811 
812   int new_count = *count + 1;
813 
814   // expand the array and add arg to the last element
815   if (*bldarray == NULL) {
816     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
817   } else {
818     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
819   }
820   (*bldarray)[*count] = strdup(arg);
821   *count = new_count;
822 }
823 
build_jvm_args(const char * arg)824 void Arguments::build_jvm_args(const char* arg) {
825   add_string(&_jvm_args_array, &_num_jvm_args, arg);
826 }
827 
build_jvm_flags(const char * arg)828 void Arguments::build_jvm_flags(const char* arg) {
829   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
830 }
831 
832 // utility function to return a string that concatenates all
833 // strings in a given char** array
build_resource_string(char ** args,int count)834 const char* Arguments::build_resource_string(char** args, int count) {
835   if (args == NULL || count == 0) {
836     return NULL;
837   }
838   size_t length = 0;
839   for (int i = 0; i < count; i++) {
840     length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
841   }
842   char* s = NEW_RESOURCE_ARRAY(char, length);
843   char* dst = s;
844   for (int j = 0; j < count; j++) {
845     size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
846     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
847     dst += offset;
848     length -= offset;
849   }
850   return (const char*) s;
851 }
852 
print_on(outputStream * st)853 void Arguments::print_on(outputStream* st) {
854   st->print_cr("VM Arguments:");
855   if (num_jvm_flags() > 0) {
856     st->print("jvm_flags: "); print_jvm_flags_on(st);
857   }
858   if (num_jvm_args() > 0) {
859     st->print("jvm_args: "); print_jvm_args_on(st);
860   }
861   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
862   if (_java_class_path != NULL) {
863     char* path = _java_class_path->value();
864     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
865   }
866   st->print_cr("Launcher Type: %s", _sun_java_launcher);
867 }
868 
print_jvm_flags_on(outputStream * st)869 void Arguments::print_jvm_flags_on(outputStream* st) {
870   if (_num_jvm_flags > 0) {
871     for (int i=0; i < _num_jvm_flags; i++) {
872       st->print("%s ", _jvm_flags_array[i]);
873     }
874     st->cr();
875   }
876 }
877 
print_jvm_args_on(outputStream * st)878 void Arguments::print_jvm_args_on(outputStream* st) {
879   if (_num_jvm_args > 0) {
880     for (int i=0; i < _num_jvm_args; i++) {
881       st->print("%s ", _jvm_args_array[i]);
882     }
883     st->cr();
884   }
885 }
886 
process_argument(const char * arg,jboolean ignore_unrecognized,Flag::Flags origin)887 bool Arguments::process_argument(const char* arg,
888     jboolean ignore_unrecognized, Flag::Flags origin) {
889 
890   JDK_Version since = JDK_Version();
891 
892   if (parse_argument(arg, origin) || ignore_unrecognized) {
893     return true;
894   }
895 
896   bool has_plus_minus = (*arg == '+' || *arg == '-');
897   const char* const argname = has_plus_minus ? arg + 1 : arg;
898   if (is_newly_obsolete(arg, &since)) {
899     char version[256];
900     since.to_string(version, sizeof(version));
901     warning("ignoring option %s; support was removed in %s", argname, version);
902     return true;
903   }
904 
905   // For locked flags, report a custom error message if available.
906   // Otherwise, report the standard unrecognized VM option.
907 
908   size_t arg_len;
909   const char* equal_sign = strchr(argname, '=');
910   if (equal_sign == NULL) {
911     arg_len = strlen(argname);
912   } else {
913     arg_len = equal_sign - argname;
914   }
915 
916   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
917   if (found_flag != NULL) {
918     char locked_message_buf[BUFLEN];
919     found_flag->get_locked_message(locked_message_buf, BUFLEN);
920     if (strlen(locked_message_buf) == 0) {
921       if (found_flag->is_bool() && !has_plus_minus) {
922         jio_fprintf(defaultStream::error_stream(),
923           "Missing +/- setting for VM option '%s'\n", argname);
924       } else if (!found_flag->is_bool() && has_plus_minus) {
925         jio_fprintf(defaultStream::error_stream(),
926           "Unexpected +/- setting in VM option '%s'\n", argname);
927       } else {
928         jio_fprintf(defaultStream::error_stream(),
929           "Improperly specified VM option '%s'\n", argname);
930       }
931     } else {
932       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
933     }
934   } else {
935     jio_fprintf(defaultStream::error_stream(),
936                 "Unrecognized VM option '%s'\n", argname);
937     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
938     if (fuzzy_matched != NULL) {
939       jio_fprintf(defaultStream::error_stream(),
940                   "Did you mean '%s%s%s'?\n",
941                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
942                   fuzzy_matched->_name,
943                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
944     }
945   }
946 
947   // allow for commandline "commenting out" options like -XX:#+Verbose
948   return arg[0] == '#';
949 }
950 
process_settings_file(const char * file_name,bool should_exist,jboolean ignore_unrecognized)951 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
952   FILE* stream = fopen(file_name, "rb");
953   if (stream == NULL) {
954     if (should_exist) {
955       jio_fprintf(defaultStream::error_stream(),
956                   "Could not open settings file %s\n", file_name);
957       return false;
958     } else {
959       return true;
960     }
961   }
962 
963   char token[1024];
964   int  pos = 0;
965 
966   bool in_white_space = true;
967   bool in_comment     = false;
968   bool in_quote       = false;
969   char quote_c        = 0;
970   bool result         = true;
971 
972   int c = getc(stream);
973   while(c != EOF && pos < (int)(sizeof(token)-1)) {
974     if (in_white_space) {
975       if (in_comment) {
976         if (c == '\n') in_comment = false;
977       } else {
978         if (c == '#') in_comment = true;
979         else if (!isspace(c)) {
980           in_white_space = false;
981           token[pos++] = c;
982         }
983       }
984     } else {
985       if (c == '\n' || (!in_quote && isspace(c))) {
986         // token ends at newline, or at unquoted whitespace
987         // this allows a way to include spaces in string-valued options
988         token[pos] = '\0';
989         logOption(token);
990         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
991         build_jvm_flags(token);
992         pos = 0;
993         in_white_space = true;
994         in_quote = false;
995       } else if (!in_quote && (c == '\'' || c == '"')) {
996         in_quote = true;
997         quote_c = c;
998       } else if (in_quote && (c == quote_c)) {
999         in_quote = false;
1000       } else {
1001         token[pos++] = c;
1002       }
1003     }
1004     c = getc(stream);
1005   }
1006   if (pos > 0) {
1007     token[pos] = '\0';
1008     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1009     build_jvm_flags(token);
1010   }
1011   fclose(stream);
1012   return result;
1013 }
1014 
1015 //=============================================================================================================
1016 // Parsing of properties (-D)
1017 
get_property(const char * key)1018 const char* Arguments::get_property(const char* key) {
1019   return PropertyList_get_value(system_properties(), key);
1020 }
1021 
add_property(const char * prop)1022 bool Arguments::add_property(const char* prop) {
1023   const char* eq = strchr(prop, '=');
1024   char* key;
1025   // ns must be static--its address may be stored in a SystemProperty object.
1026   const static char ns[1] = {0};
1027   char* value = (char *)ns;
1028 
1029   size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
1030   key = AllocateHeap(key_len + 1, mtInternal);
1031   strncpy(key, prop, key_len);
1032   key[key_len] = '\0';
1033 
1034   if (eq != NULL) {
1035     size_t value_len = strlen(prop) - key_len - 1;
1036     value = AllocateHeap(value_len + 1, mtInternal);
1037     strncpy(value, &prop[key_len + 1], value_len + 1);
1038   }
1039 
1040   if (strcmp(key, "java.compiler") == 0) {
1041     process_java_compiler_argument(value);
1042     FreeHeap(key);
1043     if (eq != NULL) {
1044       FreeHeap(value);
1045     }
1046     return true;
1047   } else if (strcmp(key, "sun.java.command") == 0) {
1048     _java_command = value;
1049 
1050     // Record value in Arguments, but let it get passed to Java.
1051   } else if (strcmp(key, "sun.java.launcher.pid") == 0) {
1052     // launcher.pid property is private and is processed
1053     // in process_sun_java_launcher_properties();
1054     // the sun.java.launcher property is passed on to the java application
1055     FreeHeap(key);
1056     if (eq != NULL) {
1057       FreeHeap(value);
1058     }
1059     return true;
1060   } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1061     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1062     // its value without going through the property list or making a Java call.
1063     _java_vendor_url_bug = value;
1064   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1065     PropertyList_unique_add(&_system_properties, key, value, true);
1066     return true;
1067   }
1068   // Create new property and add at the end of the list
1069   PropertyList_unique_add(&_system_properties, key, value);
1070   return true;
1071 }
1072 
1073 //===========================================================================================================
1074 // Setting int/mixed/comp mode flags
1075 
set_mode_flags(Mode mode)1076 void Arguments::set_mode_flags(Mode mode) {
1077   // Set up default values for all flags.
1078   // If you add a flag to any of the branches below,
1079   // add a default value for it here.
1080   set_java_compiler(false);
1081   _mode                      = mode;
1082 
1083   // Ensure Agent_OnLoad has the correct initial values.
1084   // This may not be the final mode; mode may change later in onload phase.
1085   PropertyList_unique_add(&_system_properties, "java.vm.info",
1086                           (char*)VM_Version::vm_info_string(), false);
1087 
1088   UseInterpreter             = true;
1089   UseCompiler                = true;
1090   UseLoopCounter             = true;
1091 
1092 #ifndef ZERO
1093   // Turn these off for mixed and comp.  Leave them on for Zero.
1094   if (FLAG_IS_DEFAULT(UseFastAccessorMethods)) {
1095     UseFastAccessorMethods = (mode == _int);
1096   }
1097   if (FLAG_IS_DEFAULT(UseFastEmptyMethods)) {
1098     UseFastEmptyMethods = (mode == _int);
1099   }
1100 #endif
1101 
1102   // Default values may be platform/compiler dependent -
1103   // use the saved values
1104   ClipInlining               = Arguments::_ClipInlining;
1105   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1106   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1107   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1108 
1109   // Change from defaults based on mode
1110   switch (mode) {
1111   default:
1112     ShouldNotReachHere();
1113     break;
1114   case _int:
1115     UseCompiler              = false;
1116     UseLoopCounter           = false;
1117     AlwaysCompileLoopMethods = false;
1118     UseOnStackReplacement    = false;
1119     break;
1120   case _mixed:
1121     // same as default
1122     break;
1123   case _comp:
1124     UseInterpreter           = false;
1125     BackgroundCompilation    = false;
1126     ClipInlining             = false;
1127     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1128     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1129     // compile a level 4 (C2) and then continue executing it.
1130     if (TieredCompilation) {
1131       Tier3InvokeNotifyFreqLog = 0;
1132       Tier4InvocationThreshold = 0;
1133     }
1134     break;
1135   }
1136 }
1137 
1138 #if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
1139 // Conflict: required to use shared spaces (-Xshare:on), but
1140 // incompatible command line options were chosen.
1141 
no_shared_spaces(const char * message)1142 static void no_shared_spaces(const char* message) {
1143   if (RequireSharedSpaces) {
1144     jio_fprintf(defaultStream::error_stream(),
1145       "Class data sharing is inconsistent with other specified options.\n");
1146     vm_exit_during_initialization("Unable to use shared archive.", message);
1147   } else {
1148     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1149   }
1150 }
1151 #endif
1152 
set_tiered_flags()1153 void Arguments::set_tiered_flags() {
1154   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1155   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1156     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1157   }
1158   if (CompilationPolicyChoice < 2) {
1159     vm_exit_during_initialization(
1160       "Incompatible compilation policy selected", NULL);
1161   }
1162   // Increase the code cache size - tiered compiles a lot more.
1163   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1164 #ifndef AARCH64
1165     FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);
1166 #else
1167     FLAG_SET_DEFAULT(ReservedCodeCacheSize,
1168                      MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1169 #endif
1170   }
1171   if (!UseInterpreter) { // -Xcomp
1172     Tier3InvokeNotifyFreqLog = 0;
1173     Tier4InvocationThreshold = 0;
1174   }
1175 }
1176 
1177 /**
1178  * Returns the minimum number of compiler threads needed to run the JVM. The following
1179  * configurations are possible.
1180  *
1181  * 1) The JVM is build using an interpreter only. As a result, the minimum number of
1182  *    compiler threads is 0.
1183  * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
1184  *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
1185  * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
1186  *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
1187  *    C1 can be used, so the minimum number of compiler threads is 1.
1188  * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
1189  *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
1190  *    the minimum number of compiler threads is 2.
1191  */
get_min_number_of_compiler_threads()1192 int Arguments::get_min_number_of_compiler_threads() {
1193 #if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
1194   return 0;   // case 1
1195 #else
1196   if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
1197     return 1; // case 2 or case 3
1198   }
1199   return 2;   // case 4 (tiered)
1200 #endif
1201 }
1202 
1203 #if INCLUDE_ALL_GCS
disable_adaptive_size_policy(const char * collector_name)1204 static void disable_adaptive_size_policy(const char* collector_name) {
1205   if (UseAdaptiveSizePolicy) {
1206     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
1207       warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
1208               collector_name);
1209     }
1210     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
1211   }
1212 }
1213 
set_parnew_gc_flags()1214 void Arguments::set_parnew_gc_flags() {
1215   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
1216          "control point invariant");
1217   assert(UseParNewGC, "Error");
1218 
1219   // Turn off AdaptiveSizePolicy for parnew until it is complete.
1220   disable_adaptive_size_policy("UseParNewGC");
1221 
1222   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
1223     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
1224     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
1225   } else if (ParallelGCThreads == 0) {
1226     jio_fprintf(defaultStream::error_stream(),
1227         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
1228     vm_exit(1);
1229   }
1230 
1231   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
1232   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
1233   // we set them to 1024 and 1024.
1234   // See CR 6362902.
1235   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
1236     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
1237   }
1238   if (FLAG_IS_DEFAULT(OldPLABSize)) {
1239     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
1240   }
1241 
1242   // AlwaysTenure flag should make ParNew promote all at first collection.
1243   // See CR 6362902.
1244   if (AlwaysTenure) {
1245     FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
1246   }
1247   // When using compressed oops, we use local overflow stacks,
1248   // rather than using a global overflow list chained through
1249   // the klass word of the object's pre-image.
1250   if (UseCompressedOops && !ParGCUseLocalOverflow) {
1251     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
1252       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
1253     }
1254     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
1255   }
1256   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
1257 }
1258 
1259 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
1260 // sparc/solaris for certain applications, but would gain from
1261 // further optimization and tuning efforts, and would almost
1262 // certainly gain from analysis of platform and environment.
set_cms_and_parnew_gc_flags()1263 void Arguments::set_cms_and_parnew_gc_flags() {
1264   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
1265   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
1266 
1267   // If we are using CMS, we prefer to UseParNewGC,
1268   // unless explicitly forbidden.
1269   if (FLAG_IS_DEFAULT(UseParNewGC)) {
1270     FLAG_SET_ERGO(bool, UseParNewGC, true);
1271   }
1272 
1273   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
1274   disable_adaptive_size_policy("UseConcMarkSweepGC");
1275 
1276   // In either case, adjust ParallelGCThreads and/or UseParNewGC
1277   // as needed.
1278   if (UseParNewGC) {
1279     set_parnew_gc_flags();
1280   }
1281 
1282   size_t max_heap = align_size_down(MaxHeapSize,
1283                                     CardTableRS::ct_max_alignment_constraint());
1284 
1285   // Now make adjustments for CMS
1286   intx   tenuring_default = (intx)6;
1287   size_t young_gen_per_worker = CMSYoungGenPerWorker;
1288 
1289   // Preferred young gen size for "short" pauses:
1290   // upper bound depends on # of threads and NewRatio.
1291   const uintx parallel_gc_threads =
1292     (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
1293   const size_t preferred_max_new_size_unaligned =
1294     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
1295   size_t preferred_max_new_size =
1296     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
1297 
1298   // Unless explicitly requested otherwise, size young gen
1299   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
1300 
1301   // If either MaxNewSize or NewRatio is set on the command line,
1302   // assume the user is trying to set the size of the young gen.
1303   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
1304 
1305     // Set MaxNewSize to our calculated preferred_max_new_size unless
1306     // NewSize was set on the command line and it is larger than
1307     // preferred_max_new_size.
1308     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
1309       FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
1310     } else {
1311       FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
1312     }
1313     if (PrintGCDetails && Verbose) {
1314       // Too early to use gclog_or_tty
1315       tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
1316     }
1317 
1318     // Code along this path potentially sets NewSize and OldSize
1319     if (PrintGCDetails && Verbose) {
1320       // Too early to use gclog_or_tty
1321       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
1322            " initial_heap_size:  " SIZE_FORMAT
1323            " max_heap: " SIZE_FORMAT,
1324            min_heap_size(), InitialHeapSize, max_heap);
1325     }
1326     size_t min_new = preferred_max_new_size;
1327     if (FLAG_IS_CMDLINE(NewSize)) {
1328       min_new = NewSize;
1329     }
1330     if (max_heap > min_new && min_heap_size() > min_new) {
1331       // Unless explicitly requested otherwise, make young gen
1332       // at least min_new, and at most preferred_max_new_size.
1333       if (FLAG_IS_DEFAULT(NewSize)) {
1334         FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
1335         FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
1336         if (PrintGCDetails && Verbose) {
1337           // Too early to use gclog_or_tty
1338           tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
1339         }
1340       }
1341       // Unless explicitly requested otherwise, size old gen
1342       // so it's NewRatio x of NewSize.
1343       if (FLAG_IS_DEFAULT(OldSize)) {
1344         if (max_heap > NewSize) {
1345           FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
1346           if (PrintGCDetails && Verbose) {
1347             // Too early to use gclog_or_tty
1348             tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
1349           }
1350         }
1351       }
1352     }
1353   }
1354   // Unless explicitly requested otherwise, definitely
1355   // promote all objects surviving "tenuring_default" scavenges.
1356   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
1357       FLAG_IS_DEFAULT(SurvivorRatio)) {
1358     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
1359   }
1360   // If we decided above (or user explicitly requested)
1361   // `promote all' (via MaxTenuringThreshold := 0),
1362   // prefer minuscule survivor spaces so as not to waste
1363   // space for (non-existent) survivors
1364   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
1365     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
1366   }
1367   // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
1368   // set CMSParPromoteBlocksToClaim equal to OldPLABSize.
1369   // This is done in order to make ParNew+CMS configuration to work
1370   // with YoungPLABSize and OldPLABSize options.
1371   // See CR 6362902.
1372   if (!FLAG_IS_DEFAULT(OldPLABSize)) {
1373     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
1374       // OldPLABSize is not the default value but CMSParPromoteBlocksToClaim
1375       // is.  In this situtation let CMSParPromoteBlocksToClaim follow
1376       // the value (either from the command line or ergonomics) of
1377       // OldPLABSize.  Following OldPLABSize is an ergonomics decision.
1378       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);
1379     } else {
1380       // OldPLABSize and CMSParPromoteBlocksToClaim are both set.
1381       // CMSParPromoteBlocksToClaim is a collector-specific flag, so
1382       // we'll let it to take precedence.
1383       jio_fprintf(defaultStream::error_stream(),
1384                   "Both OldPLABSize and CMSParPromoteBlocksToClaim"
1385                   " options are specified for the CMS collector."
1386                   " CMSParPromoteBlocksToClaim will take precedence.\n");
1387     }
1388   }
1389   if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
1390     // OldPLAB sizing manually turned off: Use a larger default setting,
1391     // unless it was manually specified. This is because a too-low value
1392     // will slow down scavenges.
1393     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
1394       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 6631166
1395     }
1396   }
1397   // Overwrite OldPLABSize which is the variable we will internally use everywhere.
1398   FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);
1399   // If either of the static initialization defaults have changed, note this
1400   // modification.
1401   if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
1402     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
1403   }
1404 
1405   if (PrintGCDetails && Verbose) {
1406     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1407       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1408     tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1409   }
1410 }
1411 #endif // INCLUDE_ALL_GCS
1412 
set_object_alignment()1413 void set_object_alignment() {
1414   // Object alignment.
1415   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1416   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1417   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1418   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1419   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1420   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1421 
1422   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1423   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1424 
1425   // Oop encoding heap max
1426   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1427 
1428 #if INCLUDE_ALL_GCS
1429   // Set CMS global values
1430   CompactibleFreeListSpace::set_cms_values();
1431 #endif // INCLUDE_ALL_GCS
1432 }
1433 
verify_object_alignment()1434 bool verify_object_alignment() {
1435   // Object alignment.
1436   if (!is_power_of_2(ObjectAlignmentInBytes)) {
1437     jio_fprintf(defaultStream::error_stream(),
1438                 "error: ObjectAlignmentInBytes=%d must be power of 2\n",
1439                 (int)ObjectAlignmentInBytes);
1440     return false;
1441   }
1442   if ((int)ObjectAlignmentInBytes < BytesPerLong) {
1443     jio_fprintf(defaultStream::error_stream(),
1444                 "error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
1445                 (int)ObjectAlignmentInBytes, BytesPerLong);
1446     return false;
1447   }
1448   // It does not make sense to have big object alignment
1449   // since a space lost due to alignment will be greater
1450   // then a saved space from compressed oops.
1451   if ((int)ObjectAlignmentInBytes > 256) {
1452     jio_fprintf(defaultStream::error_stream(),
1453                 "error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
1454                 (int)ObjectAlignmentInBytes);
1455     return false;
1456   }
1457   // In case page size is very small.
1458   if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
1459     jio_fprintf(defaultStream::error_stream(),
1460                 "error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
1461                 (int)ObjectAlignmentInBytes, os::vm_page_size());
1462     return false;
1463   }
1464   if(SurvivorAlignmentInBytes == 0) {
1465     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1466   } else {
1467     if (!is_power_of_2(SurvivorAlignmentInBytes)) {
1468       jio_fprintf(defaultStream::error_stream(),
1469             "error: SurvivorAlignmentInBytes=%d must be power of 2\n",
1470             (int)SurvivorAlignmentInBytes);
1471       return false;
1472     }
1473     if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {
1474       jio_fprintf(defaultStream::error_stream(),
1475           "error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",
1476           (int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);
1477       return false;
1478     }
1479   }
1480   return true;
1481 }
1482 
max_heap_for_compressed_oops()1483 size_t Arguments::max_heap_for_compressed_oops() {
1484   // Avoid sign flip.
1485   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1486   // We need to fit both the NULL page and the heap into the memory budget, while
1487   // keeping alignment constraints of the heap. To guarantee the latter, as the
1488   // NULL page is located before the heap, we pad the NULL page to the conservative
1489   // maximum alignment that the GC may ever impose upon the heap.
1490   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
1491                                                         _conservative_max_heap_alignment);
1492 
1493   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1494   NOT_LP64(ShouldNotReachHere(); return 0);
1495 }
1496 
should_auto_select_low_pause_collector()1497 bool Arguments::should_auto_select_low_pause_collector() {
1498   if (UseAutoGCSelectPolicy &&
1499       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
1500       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
1501     if (PrintGCDetails) {
1502       // Cannot use gclog_or_tty yet.
1503       tty->print_cr("Automatic selection of the low pause collector"
1504        " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
1505     }
1506     return true;
1507   }
1508   return false;
1509 }
1510 
set_use_compressed_oops()1511 void Arguments::set_use_compressed_oops() {
1512 #ifndef ZERO
1513 #ifdef _LP64
1514   // MaxHeapSize is not set up properly at this point, but
1515   // the only value that can override MaxHeapSize if we are
1516   // to use UseCompressedOops is InitialHeapSize.
1517   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1518 
1519   if (max_heap_size <= max_heap_for_compressed_oops()) {
1520 #if !defined(COMPILER1) || defined(TIERED)
1521     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1522       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1523     }
1524 #endif
1525 #ifdef _WIN64
1526     if (UseLargePages && UseCompressedOops) {
1527       // Cannot allocate guard pages for implicit checks in indexed addressing
1528       // mode, when large pages are specified on windows.
1529       // This flag could be switched ON if narrow oop base address is set to 0,
1530       // see code in Universe::initialize_heap().
1531       Universe::set_narrow_oop_use_implicit_null_checks(false);
1532     }
1533 #endif //  _WIN64
1534   } else {
1535     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1536       warning("Max heap size too large for Compressed Oops");
1537       FLAG_SET_DEFAULT(UseCompressedOops, false);
1538       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1539     }
1540   }
1541 #endif // _LP64
1542 #endif // ZERO
1543 }
1544 
1545 
1546 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1547 // set_use_compressed_oops().
set_use_compressed_klass_ptrs()1548 void Arguments::set_use_compressed_klass_ptrs() {
1549 #ifndef ZERO
1550 #ifdef _LP64
1551   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1552   if (!UseCompressedOops) {
1553     if (UseCompressedClassPointers) {
1554       warning("UseCompressedClassPointers requires UseCompressedOops");
1555     }
1556     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1557   } else {
1558     // Turn on UseCompressedClassPointers too
1559     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1560       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1561     }
1562     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1563     if (UseCompressedClassPointers) {
1564       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1565         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1566         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1567       }
1568     }
1569   }
1570 #endif // _LP64
1571 #endif // !ZERO
1572 }
1573 
set_conservative_max_heap_alignment()1574 void Arguments::set_conservative_max_heap_alignment() {
1575   // The conservative maximum required alignment for the heap is the maximum of
1576   // the alignments imposed by several sources: any requirements from the heap
1577   // itself, the collector policy and the maximum page size we may run the VM
1578   // with.
1579   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
1580 #if INCLUDE_ALL_GCS
1581   if (UseParallelGC) {
1582     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
1583   } else if (UseG1GC) {
1584     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
1585   }
1586 #endif // INCLUDE_ALL_GCS
1587   _conservative_max_heap_alignment = MAX4(heap_alignment,
1588                                           (size_t)os::vm_allocation_granularity(),
1589                                           os::max_page_size(),
1590                                           CollectorPolicy::compute_heap_alignment());
1591 }
1592 
select_gc_ergonomically()1593 void Arguments::select_gc_ergonomically() {
1594   if (os::is_server_class_machine()) {
1595     if (should_auto_select_low_pause_collector()) {
1596       FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
1597     } else {
1598       FLAG_SET_ERGO(bool, UseParallelGC, true);
1599     }
1600   }
1601 }
1602 
select_gc()1603 void Arguments::select_gc() {
1604   if (!gc_selected()) {
1605     select_gc_ergonomically();
1606   }
1607 }
1608 
set_ergonomics_flags()1609 void Arguments::set_ergonomics_flags() {
1610   select_gc();
1611 
1612 #ifdef COMPILER2
1613   // Shared spaces work fine with other GCs but causes bytecode rewriting
1614   // to be disabled, which hurts interpreter performance and decreases
1615   // server performance.  When -server is specified, keep the default off
1616   // unless it is asked for.  Future work: either add bytecode rewriting
1617   // at link time, or rewrite bytecodes in non-shared methods.
1618   if (!DumpSharedSpaces && !RequireSharedSpaces &&
1619       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1620     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1621   }
1622 #endif
1623 
1624   set_conservative_max_heap_alignment();
1625 
1626 #ifndef ZERO
1627 #ifdef _LP64
1628   set_use_compressed_oops();
1629 
1630   // set_use_compressed_klass_ptrs() must be called after calling
1631   // set_use_compressed_oops().
1632   set_use_compressed_klass_ptrs();
1633 
1634   // Also checks that certain machines are slower with compressed oops
1635   // in vm_version initialization code.
1636 #endif // _LP64
1637 #endif // !ZERO
1638 }
1639 
set_parallel_gc_flags()1640 void Arguments::set_parallel_gc_flags() {
1641   assert(UseParallelGC || UseParallelOldGC, "Error");
1642   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
1643   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
1644     FLAG_SET_DEFAULT(UseParallelOldGC, true);
1645   }
1646   FLAG_SET_DEFAULT(UseParallelGC, true);
1647 
1648   // If no heap maximum was requested explicitly, use some reasonable fraction
1649   // of the physical memory, up to a maximum of 1GB.
1650   FLAG_SET_DEFAULT(ParallelGCThreads,
1651                    Abstract_VM_Version::parallel_worker_threads());
1652   if (ParallelGCThreads == 0) {
1653     jio_fprintf(defaultStream::error_stream(),
1654         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
1655     vm_exit(1);
1656   }
1657 
1658   if (UseAdaptiveSizePolicy) {
1659     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
1660     // unless the user actually sets these flags.
1661     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
1662       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
1663       _min_heap_free_ratio = MinHeapFreeRatio;
1664     }
1665     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
1666       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
1667       _max_heap_free_ratio = MaxHeapFreeRatio;
1668     }
1669   }
1670 
1671   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
1672   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
1673   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
1674   // See CR 6362902 for details.
1675   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
1676     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
1677        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
1678     }
1679     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
1680       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
1681     }
1682   }
1683 
1684   if (UseParallelOldGC) {
1685     // Par compact uses lower default values since they are treated as
1686     // minimums.  These are different defaults because of the different
1687     // interpretation and are not ergonomically set.
1688     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
1689       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
1690     }
1691   }
1692 }
1693 
set_g1_gc_flags()1694 void Arguments::set_g1_gc_flags() {
1695   assert(UseG1GC, "Error");
1696 #ifdef COMPILER1
1697   FastTLABRefill = false;
1698 #endif
1699   FLAG_SET_DEFAULT(ParallelGCThreads,
1700                      Abstract_VM_Version::parallel_worker_threads());
1701   if (ParallelGCThreads == 0) {
1702     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
1703     }
1704 
1705 #if INCLUDE_ALL_GCS
1706   if (G1ConcRefinementThreads == 0) {
1707     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
1708   }
1709 #endif
1710 
1711   // MarkStackSize will be set (if it hasn't been set by the user)
1712   // when concurrent marking is initialized.
1713   // Its value will be based upon the number of parallel marking threads.
1714   // But we do set the maximum mark stack size here.
1715   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
1716     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
1717   }
1718 
1719   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
1720     // In G1, we want the default GC overhead goal to be higher than
1721     // say in PS. So we set it here to 10%. Otherwise the heap might
1722     // be expanded more aggressively than we would like it to. In
1723     // fact, even 10% seems to not be high enough in some cases
1724     // (especially small GC stress tests that the main thing they do
1725     // is allocation). We might consider increase it further.
1726     FLAG_SET_DEFAULT(GCTimeRatio, 9);
1727   }
1728 
1729   if (PrintGCDetails && Verbose) {
1730     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
1731       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
1732     tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
1733   }
1734 }
1735 
1736 #if !INCLUDE_ALL_GCS
1737 #ifdef ASSERT
verify_serial_gc_flags()1738 static bool verify_serial_gc_flags() {
1739   return (UseSerialGC &&
1740         !(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||
1741           UseParallelGC || UseParallelOldGC));
1742 }
1743 #endif // ASSERT
1744 #endif // INCLUDE_ALL_GCS
1745 
set_gc_specific_flags()1746 void Arguments::set_gc_specific_flags() {
1747 #if INCLUDE_ALL_GCS
1748   // Set per-collector flags
1749   if (UseParallelGC || UseParallelOldGC) {
1750     set_parallel_gc_flags();
1751   } else if (UseConcMarkSweepGC) { // Should be done before ParNew check below
1752     set_cms_and_parnew_gc_flags();
1753   } else if (UseParNewGC) {  // Skipped if CMS is set above
1754     set_parnew_gc_flags();
1755   } else if (UseG1GC) {
1756     set_g1_gc_flags();
1757   }
1758   check_deprecated_gcs();
1759   check_deprecated_gc_flags();
1760   if (AssumeMP && !UseSerialGC) {
1761     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
1762       warning("If the number of processors is expected to increase from one, then"
1763               " you should configure the number of parallel GC threads appropriately"
1764               " using -XX:ParallelGCThreads=N");
1765     }
1766   }
1767   if (MinHeapFreeRatio == 100) {
1768     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
1769     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
1770   }
1771 
1772   // If class unloading is disabled, also disable concurrent class unloading.
1773   if (!ClassUnloading) {
1774     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
1775     FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
1776     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
1777   }
1778 #else // INCLUDE_ALL_GCS
1779   assert(verify_serial_gc_flags(), "SerialGC unset");
1780 #endif // INCLUDE_ALL_GCS
1781 }
1782 
limit_by_allocatable_memory(julong limit)1783 julong Arguments::limit_by_allocatable_memory(julong limit) {
1784   julong max_allocatable;
1785   julong result = limit;
1786   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1787     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1788   }
1789   return result;
1790 }
1791 
set_heap_size()1792 void Arguments::set_heap_size() {
1793   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
1794     // Deprecated flag
1795     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
1796   }
1797 
1798   julong phys_mem =
1799     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1800                             : (julong)MaxRAM;
1801 
1802   // Experimental support for CGroup memory limits
1803   if (UseCGroupMemoryLimitForHeap) {
1804     // This is a rough indicator that a CGroup limit may be in force
1805     // for this process
1806     const char* lim_file = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
1807     FILE *fp = fopen(lim_file, "r");
1808     if (fp != NULL) {
1809       julong cgroup_max = 0;
1810       int ret = fscanf(fp, JULONG_FORMAT, &cgroup_max);
1811       if (ret == 1 && cgroup_max > 0) {
1812         // If unlimited, cgroup_max will be a very large, but unspecified
1813         // value, so use initial phys_mem as a limit
1814         if (PrintGCDetails && Verbose) {
1815           // Cannot use gclog_or_tty yet.
1816           tty->print_cr("Setting phys_mem to the min of cgroup limit ("
1817                         JULONG_FORMAT "MB) and initial phys_mem ("
1818                         JULONG_FORMAT "MB)", cgroup_max/M, phys_mem/M);
1819         }
1820         phys_mem = MIN2(cgroup_max, phys_mem);
1821       } else {
1822         warning("Unable to read/parse cgroup memory limit from %s: %s",
1823                 lim_file, errno != 0 ? strerror(errno) : "unknown error");
1824       }
1825       fclose(fp);
1826     } else {
1827       warning("Unable to open cgroup memory limit file %s (%s)", lim_file, strerror(errno));
1828     }
1829   }
1830 
1831   // Convert Fraction to Precentage values
1832   if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
1833       !FLAG_IS_DEFAULT(MaxRAMFraction))
1834     MaxRAMPercentage = 100.0 / MaxRAMFraction;
1835 
1836    if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
1837        !FLAG_IS_DEFAULT(MinRAMFraction))
1838      MinRAMPercentage = 100.0 / MinRAMFraction;
1839 
1840    if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
1841        !FLAG_IS_DEFAULT(InitialRAMFraction))
1842      InitialRAMPercentage = 100.0 / InitialRAMFraction;
1843 
1844   // If the maximum heap size has not been set with -Xmx,
1845   // then set it as fraction of the size of physical memory,
1846   // respecting the maximum and minimum sizes of the heap.
1847   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1848     julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
1849     const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
1850     if (reasonable_min < MaxHeapSize) {
1851       // Small physical memory, so use a minimum fraction of it for the heap
1852       reasonable_max = reasonable_min;
1853     } else {
1854       // Not-small physical memory, so require a heap at least
1855       // as large as MaxHeapSize
1856       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1857     }
1858 
1859     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1860       // Limit the heap size to ErgoHeapSizeLimit
1861       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1862     }
1863     if (UseCompressedOops) {
1864       // Limit the heap size to the maximum possible when using compressed oops
1865       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1866       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1867         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1868         // but it should be not less than default MaxHeapSize.
1869         max_coop_heap -= HeapBaseMinAddress;
1870       }
1871       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1872     }
1873     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1874 
1875     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1876       // An initial heap size was specified on the command line,
1877       // so be sure that the maximum size is consistent.  Done
1878       // after call to limit_by_allocatable_memory because that
1879       // method might reduce the allocation size.
1880       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1881     }
1882 
1883     if (PrintGCDetails && Verbose) {
1884       // Cannot use gclog_or_tty yet.
1885       tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1886     }
1887     FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
1888   }
1889 
1890   // If the minimum or initial heap_size have not been set or requested to be set
1891   // ergonomically, set them accordingly.
1892   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1893     julong reasonable_minimum = (julong)(OldSize + NewSize);
1894 
1895     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1896 
1897     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1898 
1899     if (InitialHeapSize == 0) {
1900       julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
1901 
1902       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1903       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1904 
1905       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1906 
1907       if (PrintGCDetails && Verbose) {
1908         // Cannot use gclog_or_tty yet.
1909         tty->print_cr("  Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
1910       }
1911       FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
1912     }
1913     // If the minimum heap size has not been set (via -Xms),
1914     // synchronize with InitialHeapSize to avoid errors with the default value.
1915     if (min_heap_size() == 0) {
1916       set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));
1917       if (PrintGCDetails && Verbose) {
1918         // Cannot use gclog_or_tty yet.
1919         tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1920       }
1921     }
1922   }
1923 }
1924 
1925 // This option inspects the machine and attempts to set various
1926 // parameters to be optimal for long-running, memory allocation
1927 // intensive jobs.  It is intended for machines with large
1928 // amounts of cpu and memory.
set_aggressive_heap_flags()1929 jint Arguments::set_aggressive_heap_flags() {
1930   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1931   // VM, but we may not be able to represent the total physical memory
1932   // available (like having 8gb of memory on a box but using a 32bit VM).
1933   // Thus, we need to make sure we're using a julong for intermediate
1934   // calculations.
1935   julong initHeapSize;
1936   julong total_memory = os::physical_memory();
1937 
1938   if (total_memory < (julong) 256 * M) {
1939     jio_fprintf(defaultStream::error_stream(),
1940             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
1941     vm_exit(1);
1942   }
1943 
1944   // The heap size is half of available memory, or (at most)
1945   // all of possible memory less 160mb (leaving room for the OS
1946   // when using ISM).  This is the maximum; because adaptive sizing
1947   // is turned on below, the actual space used may be smaller.
1948 
1949   initHeapSize = MIN2(total_memory / (julong) 2,
1950                       total_memory - (julong) 160 * M);
1951 
1952   initHeapSize = limit_by_allocatable_memory(initHeapSize);
1953 
1954   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1955     FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
1956     FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
1957     // Currently the minimum size and the initial heap sizes are the same.
1958     set_min_heap_size(initHeapSize);
1959   }
1960   if (FLAG_IS_DEFAULT(NewSize)) {
1961     // Make the young generation 3/8ths of the total heap.
1962     FLAG_SET_CMDLINE(uintx, NewSize,
1963             ((julong) MaxHeapSize / (julong) 8) * (julong) 3);
1964     FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
1965   }
1966 
1967 #if defined(_ALLBSD_SOURCE) && !defined(__FreeBSD__) && !defined(__DragonFly__)
1968   // UseLargePages is not yet supported on all BSD.
1969   FLAG_SET_DEFAULT(UseLargePages, true);
1970 #endif
1971 
1972   // Increase some data structure sizes for efficiency
1973   FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
1974   FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
1975   FLAG_SET_CMDLINE(uintx, TLABSize, 256 * K);
1976 
1977   // See the OldPLABSize comment below, but replace 'after promotion'
1978   // with 'after copying'.  YoungPLABSize is the size of the survivor
1979   // space per-gc-thread buffers.  The default is 4kw.
1980   FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256 * K);     // Note: this is in words
1981 
1982   // OldPLABSize is the size of the buffers in the old gen that
1983   // UseParallelGC uses to promote live data that doesn't fit in the
1984   // survivor spaces.  At any given time, there's one for each gc thread.
1985   // The default size is 1kw. These buffers are rarely used, since the
1986   // survivor spaces are usually big enough.  For specjbb, however, there
1987   // are occasions when there's lots of live data in the young gen
1988   // and we end up promoting some of it.  We don't have a definite
1989   // explanation for why bumping OldPLABSize helps, but the theory
1990   // is that a bigger PLAB results in retaining something like the
1991   // original allocation order after promotion, which improves mutator
1992   // locality.  A minor effect may be that larger PLABs reduce the
1993   // number of PLAB allocation events during gc.  The value of 8kw
1994   // was arrived at by experimenting with specjbb.
1995   FLAG_SET_CMDLINE(uintx, OldPLABSize, 8 * K);      // Note: this is in words
1996 
1997   // Enable parallel GC and adaptive generation sizing
1998   FLAG_SET_CMDLINE(bool, UseParallelGC, true);
1999 
2000   // Encourage steady state memory management
2001   FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
2002 
2003   // This appears to improve mutator locality
2004   FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
2005 
2006   // Get around early Solaris scheduling bug
2007   // (affinity vs other jobs on system)
2008   // but disallow DR and offlining (5008695).
2009   FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
2010 
2011   return JNI_OK;
2012 }
2013 
2014 // This must be called after ergonomics because we want bytecode rewriting
2015 // if the server compiler is used, or if UseSharedSpaces is disabled.
set_bytecode_flags()2016 void Arguments::set_bytecode_flags() {
2017   // Better not attempt to store into a read-only space.
2018   if (UseSharedSpaces) {
2019     FLAG_SET_DEFAULT(RewriteBytecodes, false);
2020     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2021   }
2022 
2023   if (!RewriteBytecodes) {
2024     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2025   }
2026 }
2027 
2028 // Aggressive optimization flags  -XX:+AggressiveOpts
set_aggressive_opts_flags()2029 void Arguments::set_aggressive_opts_flags() {
2030 #ifdef COMPILER2
2031   if (AggressiveUnboxing) {
2032     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2033       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2034     } else if (!EliminateAutoBox) {
2035       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2036       AggressiveUnboxing = false;
2037     }
2038     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2039       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2040     } else if (!DoEscapeAnalysis) {
2041       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2042       AggressiveUnboxing = false;
2043     }
2044   }
2045   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2046     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2047       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2048     }
2049     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2050       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2051     }
2052 
2053     // Feed the cache size setting into the JDK
2054     char buffer[1024];
2055     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2056     add_property(buffer);
2057   }
2058   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2059     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2060   }
2061 #endif
2062 
2063   if (AggressiveOpts) {
2064 // Sample flag setting code
2065 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2066 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2067 //    }
2068   }
2069 }
2070 
2071 //===========================================================================================================
2072 // Parsing of java.compiler property
2073 
process_java_compiler_argument(char * arg)2074 void Arguments::process_java_compiler_argument(char* arg) {
2075   // For backwards compatibility, Djava.compiler=NONE or ""
2076   // causes us to switch to -Xint mode UNLESS -Xdebug
2077   // is also specified.
2078   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2079     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2080   }
2081 }
2082 
process_java_launcher_argument(const char * launcher,void * extra_info)2083 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2084   _sun_java_launcher = strdup(launcher);
2085   if (strcmp("gamma", _sun_java_launcher) == 0) {
2086     _created_by_gamma_launcher = true;
2087   }
2088 }
2089 
created_by_java_launcher()2090 bool Arguments::created_by_java_launcher() {
2091   assert(_sun_java_launcher != NULL, "property must have value");
2092   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2093 }
2094 
created_by_gamma_launcher()2095 bool Arguments::created_by_gamma_launcher() {
2096   return _created_by_gamma_launcher;
2097 }
2098 
2099 //===========================================================================================================
2100 // Parsing of main arguments
2101 
verify_interval(uintx val,uintx min,uintx max,const char * name)2102 bool Arguments::verify_interval(uintx val, uintx min,
2103                                 uintx max, const char* name) {
2104   // Returns true iff value is in the inclusive interval [min..max]
2105   // false, otherwise.
2106   if (val >= min && val <= max) {
2107     return true;
2108   }
2109   jio_fprintf(defaultStream::error_stream(),
2110               "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
2111               " and " UINTX_FORMAT "\n",
2112               name, val, min, max);
2113   return false;
2114 }
2115 
verify_min_value(intx val,intx min,const char * name)2116 bool Arguments::verify_min_value(intx val, intx min, const char* name) {
2117   // Returns true if given value is at least specified min threshold
2118   // false, otherwise.
2119   if (val >= min ) {
2120       return true;
2121   }
2122   jio_fprintf(defaultStream::error_stream(),
2123               "%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
2124               name, val, min);
2125   return false;
2126 }
2127 
verify_percentage(uintx value,const char * name)2128 bool Arguments::verify_percentage(uintx value, const char* name) {
2129   if (is_percentage(value)) {
2130     return true;
2131   }
2132   jio_fprintf(defaultStream::error_stream(),
2133               "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
2134               name, value);
2135   return false;
2136 }
2137 
2138 // check if do gclog rotation
2139 // +UseGCLogFileRotation is a must,
2140 // no gc log rotation when log file not supplied or
2141 // NumberOfGCLogFiles is 0
check_gclog_consistency()2142 void check_gclog_consistency() {
2143   if (UseGCLogFileRotation) {
2144     if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
2145       jio_fprintf(defaultStream::output_stream(),
2146                   "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
2147                   "where num_of_file > 0\n"
2148                   "GC log rotation is turned off\n");
2149       UseGCLogFileRotation = false;
2150     }
2151   }
2152 
2153   if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
2154     FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);
2155     jio_fprintf(defaultStream::output_stream(),
2156                 "GCLogFileSize changed to minimum 8K\n");
2157   }
2158 }
2159 
2160 // This function is called for -Xloggc:<filename>, it can be used
2161 // to check if a given file name(or string) conforms to the following
2162 // specification:
2163 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
2164 // %p and %t only allowed once. We only limit usage of filename not path
is_filename_valid(const char * file_name)2165 bool is_filename_valid(const char *file_name) {
2166   const char* p = file_name;
2167   char file_sep = os::file_separator()[0];
2168   const char* cp;
2169   // skip prefix path
2170   for (cp = file_name; *cp != '\0'; cp++) {
2171     if (*cp == '/' || *cp == file_sep) {
2172       p = cp + 1;
2173     }
2174   }
2175 
2176   int count_p = 0;
2177   int count_t = 0;
2178   while (*p != '\0') {
2179     if ((*p >= '0' && *p <= '9') ||
2180         (*p >= 'A' && *p <= 'Z') ||
2181         (*p >= 'a' && *p <= 'z') ||
2182          *p == '-'               ||
2183          *p == '_'               ||
2184          *p == '.') {
2185        p++;
2186        continue;
2187     }
2188     if (*p == '%') {
2189       if(*(p + 1) == 'p') {
2190         p += 2;
2191         count_p ++;
2192         continue;
2193       }
2194       if (*(p + 1) == 't') {
2195         p += 2;
2196         count_t ++;
2197         continue;
2198       }
2199     }
2200     return false;
2201   }
2202   return count_p < 2 && count_t < 2;
2203 }
2204 
verify_MinHeapFreeRatio(FormatBuffer<80> & err_msg,uintx min_heap_free_ratio)2205 bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {
2206   if (!is_percentage(min_heap_free_ratio)) {
2207     err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");
2208     return false;
2209   }
2210   if (min_heap_free_ratio > MaxHeapFreeRatio) {
2211     err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
2212                   "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,
2213                   MaxHeapFreeRatio);
2214     return false;
2215   }
2216   // This does not set the flag itself, but stores the value in a safe place for later usage.
2217   _min_heap_free_ratio = min_heap_free_ratio;
2218   return true;
2219 }
2220 
verify_MaxHeapFreeRatio(FormatBuffer<80> & err_msg,uintx max_heap_free_ratio)2221 bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {
2222   if (!is_percentage(max_heap_free_ratio)) {
2223     err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");
2224     return false;
2225   }
2226   if (max_heap_free_ratio < MinHeapFreeRatio) {
2227     err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "
2228                   "equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,
2229                   MinHeapFreeRatio);
2230     return false;
2231   }
2232   // This does not set the flag itself, but stores the value in a safe place for later usage.
2233   _max_heap_free_ratio = max_heap_free_ratio;
2234   return true;
2235 }
2236 
2237 // Check consistency of GC selection
check_gc_consistency()2238 bool Arguments::check_gc_consistency() {
2239   check_gclog_consistency();
2240   bool status = true;
2241   // Ensure that the user has not selected conflicting sets
2242   // of collectors. [Note: this check is merely a user convenience;
2243   // collectors over-ride each other so that only a non-conflicting
2244   // set is selected; however what the user gets is not what they
2245   // may have expected from the combination they asked for. It's
2246   // better to reduce user confusion by not allowing them to
2247   // select conflicting combinations.
2248   uint i = 0;
2249   if (UseSerialGC)                       i++;
2250   if (UseConcMarkSweepGC || UseParNewGC) i++;
2251   if (UseParallelGC || UseParallelOldGC) i++;
2252   if (UseG1GC)                           i++;
2253   if (i > 1) {
2254     jio_fprintf(defaultStream::error_stream(),
2255                 "Conflicting collector combinations in option list; "
2256                 "please refer to the release notes for the combinations "
2257                 "allowed\n");
2258     status = false;
2259   }
2260   return status;
2261 }
2262 
check_deprecated_gcs()2263 void Arguments::check_deprecated_gcs() {
2264   if (UseConcMarkSweepGC && !UseParNewGC) {
2265     warning("Using the DefNew young collector with the CMS collector is deprecated "
2266         "and will likely be removed in a future release");
2267   }
2268 
2269   if (UseParNewGC && !UseConcMarkSweepGC) {
2270     // !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't
2271     // set up UseSerialGC properly, so that can't be used in the check here.
2272     warning("Using the ParNew young collector with the Serial old collector is deprecated "
2273         "and will likely be removed in a future release");
2274   }
2275 
2276   if (CMSIncrementalMode) {
2277     warning("Using incremental CMS is deprecated and will likely be removed in a future release");
2278   }
2279 }
2280 
check_deprecated_gc_flags()2281 void Arguments::check_deprecated_gc_flags() {
2282   if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
2283     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
2284             "and will likely be removed in future release");
2285   }
2286   if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
2287     warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
2288         "Use MaxRAMFraction instead.");
2289   }
2290   if (FLAG_IS_CMDLINE(UseCMSCompactAtFullCollection)) {
2291     warning("UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.");
2292   }
2293   if (FLAG_IS_CMDLINE(CMSFullGCsBeforeCompaction)) {
2294     warning("CMSFullGCsBeforeCompaction is deprecated and will likely be removed in a future release.");
2295   }
2296   if (FLAG_IS_CMDLINE(UseCMSCollectionPassing)) {
2297     warning("UseCMSCollectionPassing is deprecated and will likely be removed in a future release.");
2298   }
2299 }
2300 
2301 // Check stack pages settings
check_stack_pages()2302 bool Arguments::check_stack_pages()
2303 {
2304   bool status = true;
2305   status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");
2306   status = status && verify_min_value(StackRedPages, 1, "StackRedPages");
2307   // greater stack shadow pages can't generate instruction to bang stack
2308   status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");
2309   return status;
2310 }
2311 
2312 // Check the consistency of vm_init_args
check_vm_args_consistency()2313 bool Arguments::check_vm_args_consistency() {
2314   // Method for adding checks for flag consistency.
2315   // The intent is to warn the user of all possible conflicts,
2316   // before returning an error.
2317   // Note: Needs platform-dependent factoring.
2318   bool status = true;
2319 
2320   // Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product
2321   // builds so the cost of stack banging can be measured.
2322 #if (defined(PRODUCT) && defined(SOLARIS))
2323   if (!UseBoundThreads && !UseStackBanging) {
2324     jio_fprintf(defaultStream::error_stream(),
2325                 "-UseStackBanging conflicts with -UseBoundThreads\n");
2326 
2327      status = false;
2328   }
2329 #endif
2330 
2331   if (TLABRefillWasteFraction == 0) {
2332     jio_fprintf(defaultStream::error_stream(),
2333                 "TLABRefillWasteFraction should be a denominator, "
2334                 "not " SIZE_FORMAT "\n",
2335                 TLABRefillWasteFraction);
2336     status = false;
2337   }
2338 
2339   status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,
2340                               "AdaptiveSizePolicyWeight");
2341   status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
2342 
2343   // Divide by bucket size to prevent a large size from causing rollover when
2344   // calculating amount of memory needed to be allocated for the String table.
2345   status = status && verify_interval(StringTableSize, minimumStringTableSize,
2346     (max_uintx / StringTable::bucket_size()), "StringTable size");
2347 
2348   status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,
2349     (max_uintx / SymbolTable::bucket_size()), "SymbolTable size");
2350 
2351   {
2352     // Using "else if" below to avoid printing two error messages if min > max.
2353     // This will also prevent us from reporting both min>100 and max>100 at the
2354     // same time, but that is less annoying than printing two identical errors IMHO.
2355     FormatBuffer<80> err_msg("%s","");
2356     if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {
2357       jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
2358       status = false;
2359     } else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {
2360       jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
2361       status = false;
2362     }
2363   }
2364 
2365   // Min/MaxMetaspaceFreeRatio
2366   status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");
2367   status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");
2368 
2369   if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {
2370     jio_fprintf(defaultStream::error_stream(),
2371                 "MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "
2372                 "equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",
2373                 FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",
2374                 MinMetaspaceFreeRatio,
2375                 FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",
2376                 MaxMetaspaceFreeRatio);
2377     status = false;
2378   }
2379 
2380   // Trying to keep 100% free is not practical
2381   MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);
2382 
2383   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2384     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2385   }
2386 
2387   if (UseParallelOldGC && ParallelOldGCSplitALot) {
2388     // Settings to encourage splitting.
2389     if (!FLAG_IS_CMDLINE(NewRatio)) {
2390       FLAG_SET_CMDLINE(uintx, NewRatio, 2);
2391     }
2392     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
2393       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
2394     }
2395   }
2396 
2397   status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
2398   status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
2399   if (GCTimeLimit == 100) {
2400     // Turn off gc-overhead-limit-exceeded checks
2401     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2402   }
2403 
2404   status = status && check_gc_consistency();
2405   status = status && check_stack_pages();
2406 
2407   if (CMSIncrementalMode) {
2408     if (!UseConcMarkSweepGC) {
2409       jio_fprintf(defaultStream::error_stream(),
2410                   "error:  invalid argument combination.\n"
2411                   "The CMS collector (-XX:+UseConcMarkSweepGC) must be "
2412                   "selected in order\nto use CMSIncrementalMode.\n");
2413       status = false;
2414     } else {
2415       status = status && verify_percentage(CMSIncrementalDutyCycle,
2416                                   "CMSIncrementalDutyCycle");
2417       status = status && verify_percentage(CMSIncrementalDutyCycleMin,
2418                                   "CMSIncrementalDutyCycleMin");
2419       status = status && verify_percentage(CMSIncrementalSafetyFactor,
2420                                   "CMSIncrementalSafetyFactor");
2421       status = status && verify_percentage(CMSIncrementalOffset,
2422                                   "CMSIncrementalOffset");
2423       status = status && verify_percentage(CMSExpAvgFactor,
2424                                   "CMSExpAvgFactor");
2425       // If it was not set on the command line, set
2426       // CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.
2427       if (CMSInitiatingOccupancyFraction < 0) {
2428         FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);
2429       }
2430     }
2431   }
2432 
2433   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2434   // insists that we hold the requisite locks so that the iteration is
2435   // MT-safe. For the verification at start-up and shut-down, we don't
2436   // yet have a good way of acquiring and releasing these locks,
2437   // which are not visible at the CollectedHeap level. We want to
2438   // be able to acquire these locks and then do the iteration rather
2439   // than just disable the lock verification. This will be fixed under
2440   // bug 4788986.
2441   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2442     if (VerifyDuringStartup) {
2443       warning("Heap verification at start-up disabled "
2444               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2445       VerifyDuringStartup = false; // Disable verification at start-up
2446     }
2447 
2448     if (VerifyBeforeExit) {
2449       warning("Heap verification at shutdown disabled "
2450               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2451       VerifyBeforeExit = false; // Disable verification at shutdown
2452     }
2453   }
2454 
2455   // Note: only executed in non-PRODUCT mode
2456   if (!UseAsyncConcMarkSweepGC &&
2457       (ExplicitGCInvokesConcurrent ||
2458        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
2459     jio_fprintf(defaultStream::error_stream(),
2460                 "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
2461                 " with -UseAsyncConcMarkSweepGC");
2462     status = false;
2463   }
2464 
2465   status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");
2466 
2467 #if INCLUDE_ALL_GCS
2468   if (UseG1GC) {
2469     status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");
2470     status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");
2471     status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");
2472 
2473     status = status && verify_percentage(InitiatingHeapOccupancyPercent,
2474                                          "InitiatingHeapOccupancyPercent");
2475     status = status && verify_min_value(G1RefProcDrainInterval, 1,
2476                                         "G1RefProcDrainInterval");
2477     status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,
2478                                         "G1ConcMarkStepDurationMillis");
2479     status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,
2480                                        "G1ConcRSHotCardLimit");
2481     status = status && verify_interval(G1ConcRSLogCacheSize, 0, 27,
2482                                        "G1ConcRSLogCacheSize");
2483     status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,
2484                                        "StringDeduplicationAgeThreshold");
2485   }
2486   if (UseConcMarkSweepGC) {
2487     status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");
2488     status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");
2489     status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");
2490     status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");
2491 
2492     status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");
2493 
2494     status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");
2495     status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");
2496     status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");
2497 
2498     status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");
2499 
2500     status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");
2501     status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");
2502 
2503     status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");
2504     status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");
2505     status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");
2506 
2507     status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");
2508 
2509     status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");
2510 
2511     status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");
2512     status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");
2513     status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");
2514     status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");
2515     status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");
2516   }
2517 
2518   if (UseParallelGC || UseParallelOldGC) {
2519     status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");
2520     status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");
2521 
2522     status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");
2523     status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");
2524 
2525     status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");
2526     status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");
2527 
2528     status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");
2529 
2530     status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");
2531   }
2532 #endif // INCLUDE_ALL_GCS
2533 
2534   status = status && verify_interval(RefDiscoveryPolicy,
2535                                      ReferenceProcessor::DiscoveryPolicyMin,
2536                                      ReferenceProcessor::DiscoveryPolicyMax,
2537                                      "RefDiscoveryPolicy");
2538 
2539   // Limit the lower bound of this flag to 1 as it is used in a division
2540   // expression.
2541   status = status && verify_interval(TLABWasteTargetPercent,
2542                                      1, 100, "TLABWasteTargetPercent");
2543 
2544   status = status && verify_object_alignment();
2545 
2546   status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,
2547                                       "CompressedClassSpaceSize");
2548 
2549   status = status && verify_interval(MarkStackSizeMax,
2550                                   1, (max_jint - 1), "MarkStackSizeMax");
2551   status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");
2552 
2553   status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");
2554 
2555   status = status && verify_min_value(HeapSizePerGCThread, (uintx) os::vm_page_size(), "HeapSizePerGCThread");
2556 
2557   status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");
2558 
2559   status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");
2560   status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");
2561 
2562   status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");
2563 
2564   status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");
2565   status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");
2566   status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");
2567   status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");
2568 
2569   status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");
2570   status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");
2571 
2572   status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");
2573   status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");
2574   status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");
2575 
2576   status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");
2577   status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");
2578 
2579   // the "age" field in the oop header is 4 bits; do not want to pull in markOop.hpp
2580   // just for that, so hardcode here.
2581   status = status && verify_interval(MaxTenuringThreshold, 0, 15, "MaxTenuringThreshold");
2582   status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "MaxTenuringThreshold");
2583   status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");
2584   status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");
2585 
2586   status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");
2587 #ifdef COMPILER1
2588   status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");
2589 #endif
2590 
2591   if (PrintNMTStatistics) {
2592 #if INCLUDE_NMT
2593     if (MemTracker::tracking_level() == NMT_off) {
2594 #endif // INCLUDE_NMT
2595       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2596       PrintNMTStatistics = false;
2597 #if INCLUDE_NMT
2598     }
2599 #endif
2600   }
2601 
2602   // Need to limit the extent of the padding to reasonable size.
2603   // 8K is well beyond the reasonable HW cache line size, even with the
2604   // aggressive prefetching, while still leaving the room for segregating
2605   // among the distinct pages.
2606   if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {
2607     jio_fprintf(defaultStream::error_stream(),
2608                 "ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",
2609                 ContendedPaddingWidth, 0, 8192);
2610     status = false;
2611   }
2612 
2613   // Need to enforce the padding not to break the existing field alignments.
2614   // It is sufficient to check against the largest type size.
2615   if ((ContendedPaddingWidth % BytesPerLong) != 0) {
2616     jio_fprintf(defaultStream::error_stream(),
2617                 "ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",
2618                 ContendedPaddingWidth, BytesPerLong);
2619     status = false;
2620   }
2621 
2622   // Check lower bounds of the code cache
2623   // Template Interpreter code is approximately 3X larger in debug builds.
2624   uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;
2625   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
2626     jio_fprintf(defaultStream::error_stream(),
2627                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
2628                 os::vm_page_size()/K);
2629     status = false;
2630   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2631     jio_fprintf(defaultStream::error_stream(),
2632                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2633                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2634     status = false;
2635   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2636     jio_fprintf(defaultStream::error_stream(),
2637                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2638                 min_code_cache_size/K);
2639     status = false;
2640   } else if (ReservedCodeCacheSize > 2*G) {
2641     // Code cache size larger than MAXINT is not supported.
2642     jio_fprintf(defaultStream::error_stream(),
2643                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2644                 (2*G)/M);
2645     status = false;
2646   }
2647 
2648   status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");
2649   status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");
2650 
2651   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2652     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2653   }
2654 
2655 #ifdef COMPILER1
2656   status &= verify_interval(SafepointPollOffset, 0, os::vm_page_size() - BytesPerWord, "SafepointPollOffset");
2657 #endif
2658 
2659   int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
2660   // The default CICompilerCount's value is CI_COMPILER_COUNT.
2661   assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
2662   // Check the minimum number of compiler threads
2663   status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");
2664 
2665   return status;
2666 }
2667 
is_bad_option(const JavaVMOption * option,jboolean ignore,const char * option_type)2668 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2669   const char* option_type) {
2670   if (ignore) return false;
2671 
2672   const char* spacer = " ";
2673   if (option_type == NULL) {
2674     option_type = ++spacer; // Set both to the empty string.
2675   }
2676 
2677   if (os::obsolete_option(option)) {
2678     jio_fprintf(defaultStream::error_stream(),
2679                 "Obsolete %s%soption: %s\n", option_type, spacer,
2680       option->optionString);
2681     return false;
2682   } else {
2683     jio_fprintf(defaultStream::error_stream(),
2684                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2685       option->optionString);
2686     return true;
2687   }
2688 }
2689 
2690 static const char* user_assertion_options[] = {
2691   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2692 };
2693 
2694 static const char* system_assertion_options[] = {
2695   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2696 };
2697 
2698 // Return true if any of the strings in null-terminated array 'names' matches.
2699 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
2700 // the option must match exactly.
match_option(const JavaVMOption * option,const char ** names,const char ** tail,bool tail_allowed)2701 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
2702   bool tail_allowed) {
2703   for (/* empty */; *names != NULL; ++names) {
2704     if (match_option(option, *names, tail)) {
2705       if (**tail == '\0' || tail_allowed && **tail == ':') {
2706         return true;
2707       }
2708     }
2709   }
2710   return false;
2711 }
2712 
parse_uintx(const char * value,uintx * uintx_arg,uintx min_size)2713 bool Arguments::parse_uintx(const char* value,
2714                             uintx* uintx_arg,
2715                             uintx min_size) {
2716 
2717   // Check the sign first since atomull() parses only unsigned values.
2718   bool value_is_positive = !(*value == '-');
2719 
2720   if (value_is_positive) {
2721     julong n;
2722     bool good_return = atomull(value, &n);
2723     if (good_return) {
2724       bool above_minimum = n >= min_size;
2725       bool value_is_too_large = n > max_uintx;
2726 
2727       if (above_minimum && !value_is_too_large) {
2728         *uintx_arg = n;
2729         return true;
2730       }
2731     }
2732   }
2733   return false;
2734 }
2735 
parse_memory_size(const char * s,julong * long_arg,julong min_size)2736 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2737                                                   julong* long_arg,
2738                                                   julong min_size) {
2739   if (!atomull(s, long_arg)) return arg_unreadable;
2740   return check_memory_size(*long_arg, min_size);
2741 }
2742 
2743 // Parse JavaVMInitArgs structure
2744 
parse_vm_init_args(const JavaVMInitArgs * args)2745 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
2746   // For components of the system classpath.
2747   SysClassPath scp(Arguments::get_sysclasspath());
2748   bool scp_assembly_required = false;
2749 
2750   // Save default settings for some mode flags
2751   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2752   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2753   Arguments::_ClipInlining             = ClipInlining;
2754   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2755 
2756   // Setup flags for mixed which is the default
2757   set_mode_flags(_mixed);
2758 
2759   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
2760   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
2761   if (result != JNI_OK) {
2762     return result;
2763   }
2764 
2765   // Parse JavaVMInitArgs structure passed in
2766   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
2767   if (result != JNI_OK) {
2768     return result;
2769   }
2770 
2771   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
2772   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
2773   if (result != JNI_OK) {
2774     return result;
2775   }
2776 
2777   // We need to ensure processor and memory resources have been properly
2778   // configured - which may rely on arguments we just processed - before
2779   // doing the final argument processing. Any argument processing that
2780   // needs to know about processor and memory resources must occur after
2781   // this point.
2782 
2783   os::init_container_support();
2784 
2785   // Do final processing now that all arguments have been parsed
2786   result = finalize_vm_init_args(&scp, scp_assembly_required);
2787   if (result != JNI_OK) {
2788     return result;
2789   }
2790 
2791   return JNI_OK;
2792 }
2793 
2794 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2795 // represents a valid HPROF of JDWP agent.  is_path==true denotes that we
2796 // are dealing with -agentpath (case where name is a path), otherwise with
2797 // -agentlib
valid_hprof_or_jdwp_agent(char * name,bool is_path)2798 bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
2799   char *_name;
2800   const char *_hprof = "hprof", *_jdwp = "jdwp";
2801   size_t _len_hprof, _len_jdwp, _len_prefix;
2802 
2803   if (is_path) {
2804     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2805       return false;
2806     }
2807 
2808     _name++;  // skip past last path separator
2809     _len_prefix = strlen(JNI_LIB_PREFIX);
2810 
2811     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2812       return false;
2813     }
2814 
2815     _name += _len_prefix;
2816     _len_hprof = strlen(_hprof);
2817     _len_jdwp = strlen(_jdwp);
2818 
2819     if (strncmp(_name, _hprof, _len_hprof) == 0) {
2820       _name += _len_hprof;
2821     }
2822     else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2823       _name += _len_jdwp;
2824     }
2825     else {
2826       return false;
2827     }
2828 
2829     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2830       return false;
2831     }
2832 
2833     return true;
2834   }
2835 
2836   if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
2837     return true;
2838   }
2839 
2840   return false;
2841 }
2842 
parse_each_vm_init_arg(const JavaVMInitArgs * args,SysClassPath * scp_p,bool * scp_assembly_required_p,Flag::Flags origin)2843 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
2844                                        SysClassPath* scp_p,
2845                                        bool* scp_assembly_required_p,
2846                                        Flag::Flags origin) {
2847   // Remaining part of option string
2848   const char* tail;
2849 
2850   // iterate over arguments
2851   for (int index = 0; index < args->nOptions; index++) {
2852     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2853 
2854     const JavaVMOption* option = args->options + index;
2855 
2856     if (!match_option(option, "-Djava.class.path", &tail) &&
2857         !match_option(option, "-Dsun.java.command", &tail) &&
2858         !match_option(option, "-Dsun.java.launcher", &tail)) {
2859 
2860         // add all jvm options to the jvm_args string. This string
2861         // is used later to set the java.vm.args PerfData string constant.
2862         // the -Djava.class.path and the -Dsun.java.command options are
2863         // omitted from jvm_args string as each have their own PerfData
2864         // string constant object.
2865         build_jvm_args(option->optionString);
2866     }
2867 
2868     // -verbose:[class/gc/jni]
2869     if (match_option(option, "-verbose", &tail)) {
2870       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2871         FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
2872         FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
2873       } else if (!strcmp(tail, ":gc")) {
2874         FLAG_SET_CMDLINE(bool, PrintGC, true);
2875       } else if (!strcmp(tail, ":jni")) {
2876         FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
2877       }
2878     // -da / -ea / -disableassertions / -enableassertions
2879     // These accept an optional class/package name separated by a colon, e.g.,
2880     // -da:java.lang.Thread.
2881     } else if (match_option(option, user_assertion_options, &tail, true)) {
2882       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2883       if (*tail == '\0') {
2884         JavaAssertions::setUserClassDefault(enable);
2885       } else {
2886         assert(*tail == ':', "bogus match by match_option()");
2887         JavaAssertions::addOption(tail + 1, enable);
2888       }
2889     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2890     } else if (match_option(option, system_assertion_options, &tail, false)) {
2891       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2892       JavaAssertions::setSystemClassDefault(enable);
2893     // -bootclasspath:
2894     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2895       scp_p->reset_path(tail);
2896       *scp_assembly_required_p = true;
2897     // -bootclasspath/a:
2898     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2899       scp_p->add_suffix(tail);
2900       *scp_assembly_required_p = true;
2901     // -bootclasspath/p:
2902     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2903       scp_p->add_prefix(tail);
2904       *scp_assembly_required_p = true;
2905     // -Xrun
2906     } else if (match_option(option, "-Xrun", &tail)) {
2907       if (tail != NULL) {
2908         const char* pos = strchr(tail, ':');
2909         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2910         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2911         name[len] = '\0';
2912 
2913         char *options = NULL;
2914         if(pos != NULL) {
2915           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2916           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
2917         }
2918 #if !INCLUDE_JVMTI
2919         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
2920           jio_fprintf(defaultStream::error_stream(),
2921             "Profiling and debugging agents are not supported in this VM\n");
2922           return JNI_ERR;
2923         }
2924 #endif // !INCLUDE_JVMTI
2925         add_init_library(name, options);
2926       }
2927     // -agentlib and -agentpath
2928     } else if (match_option(option, "-agentlib:", &tail) ||
2929           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2930       if(tail != NULL) {
2931         const char* pos = strchr(tail, '=');
2932         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2933         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
2934         name[len] = '\0';
2935 
2936         char *options = NULL;
2937         if(pos != NULL) {
2938           size_t length = strlen(pos + 1) + 1;
2939           options = NEW_C_HEAP_ARRAY(char, length, mtInternal);
2940           jio_snprintf(options, length, "%s", pos + 1);
2941         }
2942 #if !INCLUDE_JVMTI
2943         if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
2944           jio_fprintf(defaultStream::error_stream(),
2945             "Profiling and debugging agents are not supported in this VM\n");
2946           return JNI_ERR;
2947         }
2948 #endif // !INCLUDE_JVMTI
2949         add_init_agent(name, options, is_absolute_path);
2950       }
2951     // -javaagent
2952     } else if (match_option(option, "-javaagent:", &tail)) {
2953 #if !INCLUDE_JVMTI
2954       jio_fprintf(defaultStream::error_stream(),
2955         "Instrumentation agents are not supported in this VM\n");
2956       return JNI_ERR;
2957 #else
2958       if(tail != NULL) {
2959         size_t length = strlen(tail) + 1;
2960         char *options = NEW_C_HEAP_ARRAY(char, length, mtInternal);
2961         jio_snprintf(options, length, "%s", tail);
2962         add_init_agent("instrument", options, false);
2963       }
2964 #endif // !INCLUDE_JVMTI
2965     // -Xnoclassgc
2966     } else if (match_option(option, "-Xnoclassgc", &tail)) {
2967       FLAG_SET_CMDLINE(bool, ClassUnloading, false);
2968     // -Xincgc: i-CMS
2969     } else if (match_option(option, "-Xincgc", &tail)) {
2970       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2971       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);
2972     // -Xnoincgc: no i-CMS
2973     } else if (match_option(option, "-Xnoincgc", &tail)) {
2974       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2975       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);
2976     // -Xconcgc
2977     } else if (match_option(option, "-Xconcgc", &tail)) {
2978       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
2979     // -Xnoconcgc
2980     } else if (match_option(option, "-Xnoconcgc", &tail)) {
2981       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
2982     // -Xbatch
2983     } else if (match_option(option, "-Xbatch", &tail)) {
2984       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2985     // -Xmn for compatibility with other JVM vendors
2986     } else if (match_option(option, "-Xmn", &tail)) {
2987       julong long_initial_young_size = 0;
2988       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2989       if (errcode != arg_in_range) {
2990         jio_fprintf(defaultStream::error_stream(),
2991                     "Invalid initial young generation size: %s\n", option->optionString);
2992         describe_range_error(errcode);
2993         return JNI_EINVAL;
2994       }
2995       FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);
2996       FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);
2997     // -Xms
2998     } else if (match_option(option, "-Xms", &tail)) {
2999       julong long_initial_heap_size = 0;
3000       // an initial heap size of 0 means automatically determine
3001       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
3002       if (errcode != arg_in_range) {
3003         jio_fprintf(defaultStream::error_stream(),
3004                     "Invalid initial heap size: %s\n", option->optionString);
3005         describe_range_error(errcode);
3006         return JNI_EINVAL;
3007       }
3008       set_min_heap_size((uintx)long_initial_heap_size);
3009       // Currently the minimum size and the initial heap sizes are the same.
3010       // Can be overridden with -XX:InitialHeapSize.
3011       FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);
3012     // -Xmx
3013     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
3014       julong long_max_heap_size = 0;
3015       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
3016       if (errcode != arg_in_range) {
3017         jio_fprintf(defaultStream::error_stream(),
3018                     "Invalid maximum heap size: %s\n", option->optionString);
3019         describe_range_error(errcode);
3020         return JNI_EINVAL;
3021       }
3022       FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);
3023     // Xmaxf
3024     } else if (match_option(option, "-Xmaxf", &tail)) {
3025       char* err;
3026       int maxf = (int)(strtod(tail, &err) * 100);
3027       if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {
3028         jio_fprintf(defaultStream::error_stream(),
3029                     "Bad max heap free percentage size: %s\n",
3030                     option->optionString);
3031         return JNI_EINVAL;
3032       } else {
3033         FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
3034       }
3035     // Xminf
3036     } else if (match_option(option, "-Xminf", &tail)) {
3037       char* err;
3038       int minf = (int)(strtod(tail, &err) * 100);
3039       if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {
3040         jio_fprintf(defaultStream::error_stream(),
3041                     "Bad min heap free percentage size: %s\n",
3042                     option->optionString);
3043         return JNI_EINVAL;
3044       } else {
3045         FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
3046       }
3047     // -Xss
3048     } else if (match_option(option, "-Xss", &tail)) {
3049       julong long_ThreadStackSize = 0;
3050       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
3051       if (errcode != arg_in_range) {
3052         jio_fprintf(defaultStream::error_stream(),
3053                     "Invalid thread stack size: %s\n", option->optionString);
3054         describe_range_error(errcode);
3055         return JNI_EINVAL;
3056       }
3057       // Internally track ThreadStackSize in units of 1024 bytes.
3058       FLAG_SET_CMDLINE(intx, ThreadStackSize,
3059                               round_to((int)long_ThreadStackSize, K) / K);
3060     // -Xoss
3061     } else if (match_option(option, "-Xoss", &tail)) {
3062           // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
3063     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
3064       julong long_CodeCacheExpansionSize = 0;
3065       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
3066       if (errcode != arg_in_range) {
3067         jio_fprintf(defaultStream::error_stream(),
3068                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
3069                    os::vm_page_size()/K);
3070         return JNI_EINVAL;
3071       }
3072       FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);
3073     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
3074                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
3075       julong long_ReservedCodeCacheSize = 0;
3076 
3077       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
3078       if (errcode != arg_in_range) {
3079         jio_fprintf(defaultStream::error_stream(),
3080                     "Invalid maximum code cache size: %s.\n", option->optionString);
3081         return JNI_EINVAL;
3082       }
3083       FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
3084       //-XX:IncreaseFirstTierCompileThresholdAt=
3085       } else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {
3086         uintx uint_IncreaseFirstTierCompileThresholdAt = 0;
3087         if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {
3088           jio_fprintf(defaultStream::error_stream(),
3089                       "Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",
3090                       option->optionString);
3091           return JNI_EINVAL;
3092         }
3093         FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);
3094     // -green
3095     } else if (match_option(option, "-green", &tail)) {
3096       jio_fprintf(defaultStream::error_stream(),
3097                   "Green threads support not available\n");
3098           return JNI_EINVAL;
3099     // -native
3100     } else if (match_option(option, "-native", &tail)) {
3101           // HotSpot always uses native threads, ignore silently for compatibility
3102     // -Xsqnopause
3103     } else if (match_option(option, "-Xsqnopause", &tail)) {
3104           // EVM option, ignore silently for compatibility
3105     // -Xrs
3106     } else if (match_option(option, "-Xrs", &tail)) {
3107           // Classic/EVM option, new functionality
3108       FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
3109     } else if (match_option(option, "-Xusealtsigs", &tail)) {
3110           // change default internal VM signals used - lower case for back compat
3111       FLAG_SET_CMDLINE(bool, UseAltSigs, true);
3112     // -Xoptimize
3113     } else if (match_option(option, "-Xoptimize", &tail)) {
3114           // EVM option, ignore silently for compatibility
3115     // -Xprof
3116     } else if (match_option(option, "-Xprof", &tail)) {
3117 #if INCLUDE_FPROF
3118       _has_profile = true;
3119 #else // INCLUDE_FPROF
3120       jio_fprintf(defaultStream::error_stream(),
3121         "Flat profiling is not supported in this VM.\n");
3122       return JNI_ERR;
3123 #endif // INCLUDE_FPROF
3124     // -Xconcurrentio
3125     } else if (match_option(option, "-Xconcurrentio", &tail)) {
3126       FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
3127       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
3128       FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
3129       FLAG_SET_CMDLINE(bool, UseTLAB, false);
3130       FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation
3131 
3132       // -Xinternalversion
3133     } else if (match_option(option, "-Xinternalversion", &tail)) {
3134       jio_fprintf(defaultStream::output_stream(), "%s\n",
3135                   VM_Version::internal_vm_info_string());
3136       vm_exit(0);
3137 #ifndef PRODUCT
3138     // -Xprintflags
3139     } else if (match_option(option, "-Xprintflags", &tail)) {
3140       CommandLineFlags::printFlags(tty, false);
3141       vm_exit(0);
3142 #endif
3143     // -D
3144     } else if (match_option(option, "-D", &tail)) {
3145       if (CheckEndorsedAndExtDirs) {
3146         if (match_option(option, "-Djava.endorsed.dirs=", &tail)) {
3147           // abort if -Djava.endorsed.dirs is set
3148           jio_fprintf(defaultStream::output_stream(),
3149             "-Djava.endorsed.dirs will not be supported in a future release.\n"
3150             "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
3151           return JNI_EINVAL;
3152         }
3153         if (match_option(option, "-Djava.ext.dirs=", &tail)) {
3154           // abort if -Djava.ext.dirs is set
3155           jio_fprintf(defaultStream::output_stream(),
3156             "-Djava.ext.dirs will not be supported in a future release.\n"
3157             "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
3158           return JNI_EINVAL;
3159         }
3160       }
3161 
3162       if (!add_property(tail)) {
3163         return JNI_ENOMEM;
3164       }
3165       // Out of the box management support
3166       if (match_option(option, "-Dcom.sun.management", &tail)) {
3167 #if INCLUDE_MANAGEMENT
3168         FLAG_SET_CMDLINE(bool, ManagementServer, true);
3169 #else
3170         jio_fprintf(defaultStream::output_stream(),
3171           "-Dcom.sun.management is not supported in this VM.\n");
3172         return JNI_ERR;
3173 #endif
3174       }
3175     // -Xint
3176     } else if (match_option(option, "-Xint", &tail)) {
3177           set_mode_flags(_int);
3178     // -Xmixed
3179     } else if (match_option(option, "-Xmixed", &tail)) {
3180           set_mode_flags(_mixed);
3181     // -Xcomp
3182     } else if (match_option(option, "-Xcomp", &tail)) {
3183       // for testing the compiler; turn off all flags that inhibit compilation
3184           set_mode_flags(_comp);
3185     // -Xshare:dump
3186     } else if (match_option(option, "-Xshare:dump", &tail)) {
3187       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
3188       set_mode_flags(_int);     // Prevent compilation, which creates objects
3189     // -Xshare:on
3190     } else if (match_option(option, "-Xshare:on", &tail)) {
3191       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3192       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
3193     // -Xshare:auto
3194     } else if (match_option(option, "-Xshare:auto", &tail)) {
3195       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3196       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
3197     // -Xshare:off
3198     } else if (match_option(option, "-Xshare:off", &tail)) {
3199       FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
3200       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
3201     // -Xverify
3202     } else if (match_option(option, "-Xverify", &tail)) {
3203       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3204         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
3205         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3206       } else if (strcmp(tail, ":remote") == 0) {
3207         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3208         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
3209       } else if (strcmp(tail, ":none") == 0) {
3210         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
3211         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
3212       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3213         return JNI_EINVAL;
3214       }
3215     // -Xdebug
3216     } else if (match_option(option, "-Xdebug", &tail)) {
3217       // note this flag has been used, then ignore
3218       set_xdebug_mode(true);
3219     // -Xnoagent
3220     } else if (match_option(option, "-Xnoagent", &tail)) {
3221       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3222     } else if (match_option(option, "-Xboundthreads", &tail)) {
3223       // Bind user level threads to kernel threads (Solaris only)
3224       FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
3225     } else if (match_option(option, "-Xloggc:", &tail)) {
3226       // Redirect GC output to the file. -Xloggc:<filename>
3227       // ostream_init_log(), when called will use this filename
3228       // to initialize a fileStream.
3229       _gc_log_filename = strdup(tail);
3230      if (!is_filename_valid(_gc_log_filename)) {
3231        jio_fprintf(defaultStream::output_stream(),
3232                   "Invalid file name for use with -Xloggc: Filename can only contain the "
3233                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
3234                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
3235         return JNI_EINVAL;
3236       }
3237       FLAG_SET_CMDLINE(bool, PrintGC, true);
3238       FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
3239 
3240     // JNI hooks
3241     } else if (match_option(option, "-Xcheck", &tail)) {
3242       if (!strcmp(tail, ":jni")) {
3243 #if !INCLUDE_JNI_CHECK
3244         warning("JNI CHECKING is not supported in this VM");
3245 #else
3246         CheckJNICalls = true;
3247 #endif // INCLUDE_JNI_CHECK
3248       } else if (is_bad_option(option, args->ignoreUnrecognized,
3249                                      "check")) {
3250         return JNI_EINVAL;
3251       }
3252     } else if (match_option(option, "vfprintf", &tail)) {
3253       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3254     } else if (match_option(option, "exit", &tail)) {
3255       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3256     } else if (match_option(option, "abort", &tail)) {
3257       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3258     } else if (match_option(option, "-XX:+NeverTenure", &tail)) {
3259       // The last option must always win.
3260       FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
3261       FLAG_SET_CMDLINE(bool, NeverTenure, true);
3262     } else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {
3263       // The last option must always win.
3264       FLAG_SET_CMDLINE(bool, NeverTenure, false);
3265       FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
3266     } else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||
3267                match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {
3268       jio_fprintf(defaultStream::error_stream(),
3269         "Please use CMSClassUnloadingEnabled in place of "
3270         "CMSPermGenSweepingEnabled in the future\n");
3271     } else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {
3272       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);
3273       jio_fprintf(defaultStream::error_stream(),
3274         "Please use -XX:+UseGCOverheadLimit in place of "
3275         "-XX:+UseGCTimeLimit in the future\n");
3276     } else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {
3277       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);
3278       jio_fprintf(defaultStream::error_stream(),
3279         "Please use -XX:-UseGCOverheadLimit in place of "
3280         "-XX:-UseGCTimeLimit in the future\n");
3281     // The TLE options are for compatibility with 1.3 and will be
3282     // removed without notice in a future release.  These options
3283     // are not to be documented.
3284     } else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {
3285       // No longer used.
3286     } else if (match_option(option, "-XX:+ResizeTLE", &tail)) {
3287       FLAG_SET_CMDLINE(bool, ResizeTLAB, true);
3288     } else if (match_option(option, "-XX:-ResizeTLE", &tail)) {
3289       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
3290     } else if (match_option(option, "-XX:+PrintTLE", &tail)) {
3291       FLAG_SET_CMDLINE(bool, PrintTLAB, true);
3292     } else if (match_option(option, "-XX:-PrintTLE", &tail)) {
3293       FLAG_SET_CMDLINE(bool, PrintTLAB, false);
3294     } else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {
3295       // No longer used.
3296     } else if (match_option(option, "-XX:TLESize=", &tail)) {
3297       julong long_tlab_size = 0;
3298       ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);
3299       if (errcode != arg_in_range) {
3300         jio_fprintf(defaultStream::error_stream(),
3301                     "Invalid TLAB size: %s\n", option->optionString);
3302         describe_range_error(errcode);
3303         return JNI_EINVAL;
3304       }
3305       FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);
3306     } else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {
3307       // No longer used.
3308     } else if (match_option(option, "-XX:+UseTLE", &tail)) {
3309       FLAG_SET_CMDLINE(bool, UseTLAB, true);
3310     } else if (match_option(option, "-XX:-UseTLE", &tail)) {
3311       FLAG_SET_CMDLINE(bool, UseTLAB, false);
3312     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {
3313       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
3314       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
3315     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {
3316       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
3317       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
3318     } else if (match_option(option, "-XX:+ErrorFileToStderr", &tail)) {
3319       FLAG_SET_CMDLINE(bool, ErrorFileToStdout, false);
3320       FLAG_SET_CMDLINE(bool, ErrorFileToStderr, true);
3321     } else if (match_option(option, "-XX:+ErrorFileToStdout", &tail)) {
3322       FLAG_SET_CMDLINE(bool, ErrorFileToStderr, false);
3323       FLAG_SET_CMDLINE(bool, ErrorFileToStdout, true);
3324     } else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {
3325 #if defined(DTRACE_ENABLED)
3326       FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
3327       FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
3328       FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
3329       FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
3330 #else // defined(DTRACE_ENABLED)
3331       jio_fprintf(defaultStream::error_stream(),
3332                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3333       return JNI_EINVAL;
3334 #endif // defined(DTRACE_ENABLED)
3335 #ifdef ASSERT
3336     } else if (match_option(option, "-XX:+FullGCALot", &tail)) {
3337       FLAG_SET_CMDLINE(bool, FullGCALot, true);
3338       // disable scavenge before parallel mark-compact
3339       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
3340 #endif
3341     } else if (match_option(option, "-XX:CMSParPromoteBlocksToClaim=", &tail)) {
3342       julong cms_blocks_to_claim = (julong)atol(tail);
3343       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
3344       jio_fprintf(defaultStream::error_stream(),
3345         "Please use -XX:OldPLABSize in place of "
3346         "-XX:CMSParPromoteBlocksToClaim in the future\n");
3347     } else if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {
3348       julong cms_blocks_to_claim = (julong)atol(tail);
3349       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
3350       jio_fprintf(defaultStream::error_stream(),
3351         "Please use -XX:OldPLABSize in place of "
3352         "-XX:ParCMSPromoteBlocksToClaim in the future\n");
3353     } else if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {
3354       julong old_plab_size = 0;
3355       ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);
3356       if (errcode != arg_in_range) {
3357         jio_fprintf(defaultStream::error_stream(),
3358                     "Invalid old PLAB size: %s\n", option->optionString);
3359         describe_range_error(errcode);
3360         return JNI_EINVAL;
3361       }
3362       FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);
3363       jio_fprintf(defaultStream::error_stream(),
3364                   "Please use -XX:OldPLABSize in place of "
3365                   "-XX:ParallelGCOldGenAllocBufferSize in the future\n");
3366     } else if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {
3367       julong young_plab_size = 0;
3368       ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);
3369       if (errcode != arg_in_range) {
3370         jio_fprintf(defaultStream::error_stream(),
3371                     "Invalid young PLAB size: %s\n", option->optionString);
3372         describe_range_error(errcode);
3373         return JNI_EINVAL;
3374       }
3375       FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);
3376       jio_fprintf(defaultStream::error_stream(),
3377                   "Please use -XX:YoungPLABSize in place of "
3378                   "-XX:ParallelGCToSpaceAllocBufferSize in the future\n");
3379     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
3380                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
3381       julong stack_size = 0;
3382       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
3383       if (errcode != arg_in_range) {
3384         jio_fprintf(defaultStream::error_stream(),
3385                     "Invalid mark stack size: %s\n", option->optionString);
3386         describe_range_error(errcode);
3387         return JNI_EINVAL;
3388       }
3389       FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);
3390     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
3391       julong max_stack_size = 0;
3392       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
3393       if (errcode != arg_in_range) {
3394         jio_fprintf(defaultStream::error_stream(),
3395                     "Invalid maximum mark stack size: %s\n",
3396                     option->optionString);
3397         describe_range_error(errcode);
3398         return JNI_EINVAL;
3399       }
3400       FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);
3401     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
3402                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
3403       uintx conc_threads = 0;
3404       if (!parse_uintx(tail, &conc_threads, 1)) {
3405         jio_fprintf(defaultStream::error_stream(),
3406                     "Invalid concurrent threads: %s\n", option->optionString);
3407         return JNI_EINVAL;
3408       }
3409       FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
3410     } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
3411       julong max_direct_memory_size = 0;
3412       ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
3413       if (errcode != arg_in_range) {
3414         jio_fprintf(defaultStream::error_stream(),
3415                     "Invalid maximum direct memory size: %s\n",
3416                     option->optionString);
3417         describe_range_error(errcode);
3418         return JNI_EINVAL;
3419       }
3420       FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);
3421     } else if (match_option(option, "-XX:+UseVMInterruptibleIO", &tail)) {
3422       // NOTE! In JDK 9, the UseVMInterruptibleIO flag will completely go
3423       //       away and will cause VM initialization failures!
3424       warning("-XX:+UseVMInterruptibleIO is obsolete and will be removed in a future release.");
3425       FLAG_SET_CMDLINE(bool, UseVMInterruptibleIO, true);
3426 #if !INCLUDE_MANAGEMENT
3427     } else if (match_option(option, "-XX:+ManagementServer", &tail)) {
3428         jio_fprintf(defaultStream::error_stream(),
3429           "ManagementServer is not supported in this VM.\n");
3430         return JNI_ERR;
3431 #endif // INCLUDE_MANAGEMENT
3432 #if INCLUDE_JFR
3433     } else if (match_jfr_option(&option)) {
3434       return JNI_EINVAL;
3435 #endif
3436     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3437       // Skip -XX:Flags= since that case has already been handled
3438       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
3439         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3440           return JNI_EINVAL;
3441         }
3442       }
3443     // Unknown option
3444     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3445       return JNI_ERR;
3446     }
3447   }
3448 
3449   // PrintSharedArchiveAndExit will turn on
3450   //   -Xshare:on
3451   //   -XX:+TraceClassPaths
3452   if (PrintSharedArchiveAndExit) {
3453     FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
3454     FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
3455     FLAG_SET_CMDLINE(bool, TraceClassPaths, true);
3456   }
3457 
3458   // Change the default value for flags  which have different default values
3459   // when working with older JDKs.
3460 #ifdef LINUX
3461  if (JDK_Version::current().compare_major(6) <= 0 &&
3462       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3463     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3464   }
3465 #endif // LINUX
3466   fix_appclasspath();
3467   return JNI_OK;
3468 }
3469 
3470 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3471 //
3472 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3473 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3474 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3475 // path is treated as the current directory.
3476 //
3477 // This causes problems with CDS, which requires that all directories specified in the classpath
3478 // must be empty. In most cases, applications do NOT want to load classes from the current
3479 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3480 // scripts compatible with CDS.
fix_appclasspath()3481 void Arguments::fix_appclasspath() {
3482   if (IgnoreEmptyClassPaths) {
3483     const char separator = *os::path_separator();
3484     const char* src = _java_class_path->value();
3485 
3486     // skip over all the leading empty paths
3487     while (*src == separator) {
3488       src ++;
3489     }
3490 
3491     char* copy = os::strdup(src, mtInternal);
3492 
3493     // trim all trailing empty paths
3494     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3495       *tail = '\0';
3496     }
3497 
3498     char from[3] = {separator, separator, '\0'};
3499     char to  [2] = {separator, '\0'};
3500     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3501       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3502       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3503     }
3504 
3505     _java_class_path->set_value(copy);
3506     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3507   }
3508 
3509   if (!PrintSharedArchiveAndExit) {
3510     ClassLoader::trace_class_path(tty, "[classpath: ", _java_class_path->value());
3511   }
3512 }
3513 
has_jar_files(const char * directory)3514 static bool has_jar_files(const char* directory) {
3515   DIR* dir = os::opendir(directory);
3516   if (dir == NULL) return false;
3517 
3518   struct dirent *entry;
3519   bool hasJarFile = false;
3520   while (!hasJarFile && (entry = os::readdir(dir)) != NULL) {
3521     const char* name = entry->d_name;
3522     const char* ext = name + strlen(name) - 4;
3523     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3524   }
3525   os::closedir(dir);
3526   return hasJarFile ;
3527 }
3528 
3529 // returns the number of directories in the given path containing JAR files
3530 // If the skip argument is not NULL, it will skip that directory
check_non_empty_dirs(const char * path,const char * type,const char * skip)3531 static int check_non_empty_dirs(const char* path, const char* type, const char* skip) {
3532   const char separator = *os::path_separator();
3533   const char* const end = path + strlen(path);
3534   int nonEmptyDirs = 0;
3535   while (path < end) {
3536     const char* tmp_end = strchr(path, separator);
3537     if (tmp_end == NULL) {
3538       if ((skip == NULL || strcmp(path, skip) != 0) && has_jar_files(path)) {
3539         nonEmptyDirs++;
3540         jio_fprintf(defaultStream::output_stream(),
3541           "Non-empty %s directory: %s\n", type, path);
3542       }
3543       path = end;
3544     } else {
3545       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
3546       memcpy(dirpath, path, tmp_end - path);
3547       dirpath[tmp_end - path] = '\0';
3548       if ((skip == NULL || strcmp(dirpath, skip) != 0) && has_jar_files(dirpath)) {
3549         nonEmptyDirs++;
3550         jio_fprintf(defaultStream::output_stream(),
3551           "Non-empty %s directory: %s\n", type, dirpath);
3552       }
3553       FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);
3554       path = tmp_end + 1;
3555     }
3556   }
3557   return nonEmptyDirs;
3558 }
3559 
3560 // Returns true if endorsed standards override mechanism and extension mechanism
3561 // are not used.
check_endorsed_and_ext_dirs()3562 static bool check_endorsed_and_ext_dirs() {
3563   if (!CheckEndorsedAndExtDirs)
3564     return true;
3565 
3566   char endorsedDir[JVM_MAXPATHLEN];
3567   char extDir[JVM_MAXPATHLEN];
3568   const char* fileSep = os::file_separator();
3569   jio_snprintf(endorsedDir, sizeof(endorsedDir), "%s%slib%sendorsed",
3570                Arguments::get_java_home(), fileSep, fileSep);
3571   jio_snprintf(extDir, sizeof(extDir), "%s%slib%sext",
3572                Arguments::get_java_home(), fileSep, fileSep);
3573 
3574   // check endorsed directory
3575   int nonEmptyDirs = check_non_empty_dirs(Arguments::get_endorsed_dir(), "endorsed", NULL);
3576 
3577   // check the extension directories but skip the default lib/ext directory
3578   nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs(), "extension", extDir);
3579 
3580   // List of JAR files installed in the default lib/ext directory.
3581   // -XX:+CheckEndorsedAndExtDirs checks if any non-JDK file installed
3582   static const char* jdk_ext_jars[] = {
3583       "access-bridge-32.jar",
3584       "access-bridge-64.jar",
3585       "access-bridge.jar",
3586       "cldrdata.jar",
3587       "dnsns.jar",
3588       "jaccess.jar",
3589       "jfxrt.jar",
3590       "localedata.jar",
3591       "nashorn.jar",
3592       "sunec.jar",
3593       "sunjce_provider.jar",
3594       "sunmscapi.jar",
3595       "sunpkcs11.jar",
3596       "ucrypto.jar",
3597       "zipfs.jar",
3598       NULL
3599   };
3600 
3601   // check if the default lib/ext directory has any non-JDK jar files; if so, error
3602   DIR* dir = os::opendir(extDir);
3603   if (dir != NULL) {
3604     int num_ext_jars = 0;
3605     struct dirent *entry;
3606     while ((entry = os::readdir(dir)) != NULL) {
3607       const char* name = entry->d_name;
3608       const char* ext = name + strlen(name) - 4;
3609       if (ext > name && (os::file_name_strcmp(ext, ".jar") == 0)) {
3610         bool is_jdk_jar = false;
3611         const char* jarfile = NULL;
3612         for (int i=0; (jarfile = jdk_ext_jars[i]) != NULL; i++) {
3613           if (os::file_name_strcmp(name, jarfile) == 0) {
3614             is_jdk_jar = true;
3615             break;
3616           }
3617         }
3618         if (!is_jdk_jar) {
3619           jio_fprintf(defaultStream::output_stream(),
3620             "%s installed in <JAVA_HOME>/lib/ext\n", name);
3621           num_ext_jars++;
3622         }
3623       }
3624     }
3625     os::closedir(dir);
3626     if (num_ext_jars > 0) {
3627       nonEmptyDirs += 1;
3628     }
3629   }
3630 
3631   // check if the default lib/endorsed directory exists; if so, error
3632   dir = os::opendir(endorsedDir);
3633   if (dir != NULL) {
3634     jio_fprintf(defaultStream::output_stream(), "<JAVA_HOME>/lib/endorsed exists\n");
3635     os::closedir(dir);
3636     nonEmptyDirs += 1;
3637   }
3638 
3639   if (nonEmptyDirs > 0) {
3640     jio_fprintf(defaultStream::output_stream(),
3641       "Endorsed standards override mechanism and extension mechanism "
3642       "will not be supported in a future release.\n"
3643       "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
3644     return false;
3645   }
3646 
3647   return true;
3648 }
3649 
finalize_vm_init_args(SysClassPath * scp_p,bool scp_assembly_required)3650 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
3651   // This must be done after all -D arguments have been processed.
3652   scp_p->expand_endorsed();
3653 
3654   if (scp_assembly_required || scp_p->get_endorsed() != NULL) {
3655     // Assemble the bootclasspath elements into the final path.
3656     Arguments::set_sysclasspath(scp_p->combined_path());
3657   }
3658 
3659   if (!check_endorsed_and_ext_dirs()) {
3660     return JNI_ERR;
3661   }
3662 
3663   // This must be done after all arguments have been processed
3664   // and the container support has been initialized since AggressiveHeap
3665   // relies on the amount of total memory available.
3666   if (AggressiveHeap) {
3667     jint result = set_aggressive_heap_flags();
3668     if (result != JNI_OK) {
3669       return result;
3670     }
3671   }
3672   // This must be done after all arguments have been processed.
3673   // java_compiler() true means set to "NONE" or empty.
3674   if (java_compiler() && !xdebug_mode()) {
3675     // For backwards compatibility, we switch to interpreted mode if
3676     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3677     // not specified.
3678     set_mode_flags(_int);
3679   }
3680   if (CompileThreshold == 0) {
3681     set_mode_flags(_int);
3682   }
3683 
3684   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3685   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3686     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3687   }
3688 
3689 #ifndef COMPILER2
3690   // Don't degrade server performance for footprint
3691   if (FLAG_IS_DEFAULT(UseLargePages) &&
3692       MaxHeapSize < LargePageHeapSizeThreshold) {
3693     // No need for large granularity pages w/small heaps.
3694     // Note that large pages are enabled/disabled for both the
3695     // Java heap and the code cache.
3696     FLAG_SET_DEFAULT(UseLargePages, false);
3697   }
3698 
3699 #else
3700   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3701     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3702   }
3703 #endif
3704 
3705 #ifndef TIERED
3706   // Tiered compilation is undefined.
3707   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
3708 #endif
3709 
3710   // If we are running in a headless jre, force java.awt.headless property
3711   // to be true unless the property has already been set.
3712   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3713   if (os::is_headless_jre()) {
3714     const char* headless = Arguments::get_property("java.awt.headless");
3715     if (headless == NULL) {
3716       char envbuffer[128];
3717       if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {
3718         if (!add_property("java.awt.headless=true")) {
3719           return JNI_ENOMEM;
3720         }
3721       } else {
3722         char buffer[256];
3723         jio_snprintf(buffer, 256, "java.awt.headless=%s", envbuffer);
3724         if (!add_property(buffer)) {
3725           return JNI_ENOMEM;
3726         }
3727       }
3728     }
3729   }
3730 
3731   if (!check_vm_args_consistency()) {
3732     return JNI_ERR;
3733   }
3734 
3735   return JNI_OK;
3736 }
3737 
parse_java_options_environment_variable(SysClassPath * scp_p,bool * scp_assembly_required_p)3738 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3739   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
3740                                             scp_assembly_required_p);
3741 }
3742 
parse_java_tool_options_environment_variable(SysClassPath * scp_p,bool * scp_assembly_required_p)3743 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
3744   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
3745                                             scp_assembly_required_p);
3746 }
3747 
parse_options_environment_variable(const char * name,SysClassPath * scp_p,bool * scp_assembly_required_p)3748 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
3749   const int N_MAX_OPTIONS = 64;
3750   const int OPTION_BUFFER_SIZE = 1024;
3751   char buffer[OPTION_BUFFER_SIZE];
3752 
3753   // The variable will be ignored if it exceeds the length of the buffer.
3754   // Don't check this variable if user has special privileges
3755   // (e.g. unix su command).
3756   if (os::getenv(name, buffer, sizeof(buffer)) &&
3757       !os::have_special_privileges()) {
3758     JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
3759     jio_fprintf(defaultStream::error_stream(),
3760                 "Picked up %s: %s\n", name, buffer);
3761     char* rd = buffer;                        // pointer to the input string (rd)
3762     int i;
3763     for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
3764       while (isspace(*rd)) rd++;              // skip whitespace
3765       if (*rd == 0) break;                    // we re done when the input string is read completely
3766 
3767       // The output, option string, overwrites the input string.
3768       // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
3769       // input string (rd).
3770       char* wrt = rd;
3771 
3772       options[i++].optionString = wrt;        // Fill in option
3773       while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
3774         if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3775           int quote = *rd;                    // matching quote to look for
3776           rd++;                               // don't copy open quote
3777           while (*rd != quote) {              // include everything (even spaces) up until quote
3778             if (*rd == 0) {                   // string termination means unmatched string
3779               jio_fprintf(defaultStream::error_stream(),
3780                           "Unmatched quote in %s\n", name);
3781               return JNI_ERR;
3782             }
3783             *wrt++ = *rd++;                   // copy to option string
3784           }
3785           rd++;                               // don't copy close quote
3786         } else {
3787           *wrt++ = *rd++;                     // copy to option string
3788         }
3789       }
3790       // Need to check if we're done before writing a NULL,
3791       // because the write could be to the byte that rd is pointing to.
3792       if (*rd++ == 0) {
3793         *wrt = 0;
3794         break;
3795       }
3796       *wrt = 0;                               // Zero terminate option
3797     }
3798     // Construct JavaVMInitArgs structure and parse as if it was part of the command line
3799     JavaVMInitArgs vm_args;
3800     vm_args.version = JNI_VERSION_1_2;
3801     vm_args.options = options;
3802     vm_args.nOptions = i;
3803     vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3804 
3805     if (PrintVMOptions) {
3806       const char* tail;
3807       for (int i = 0; i < vm_args.nOptions; i++) {
3808         const JavaVMOption *option = vm_args.options + i;
3809         if (match_option(option, "-XX:", &tail)) {
3810           logOption(tail);
3811         }
3812       }
3813     }
3814 
3815     return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));
3816   }
3817   return JNI_OK;
3818 }
3819 
set_shared_spaces_flags()3820 void Arguments::set_shared_spaces_flags() {
3821   if (DumpSharedSpaces) {
3822     if (FailOverToOldVerifier) {
3823       // Don't fall back to the old verifier on verification failure. If a
3824       // class fails verification with the split verifier, it might fail the
3825       // CDS runtime verifier constraint check. In that case, we don't want
3826       // to share the class. We only archive classes that pass the split verifier.
3827       FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
3828     }
3829 
3830     if (RequireSharedSpaces) {
3831       warning("cannot dump shared archive while using shared archive");
3832     }
3833     UseSharedSpaces = false;
3834 #ifdef _LP64
3835     if (!UseCompressedOops || !UseCompressedClassPointers) {
3836       vm_exit_during_initialization(
3837         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3838     }
3839   } else {
3840     if (!UseCompressedOops || !UseCompressedClassPointers) {
3841       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3842     }
3843 #endif
3844   }
3845 }
3846 
3847 #if !INCLUDE_ALL_GCS
force_serial_gc()3848 static void force_serial_gc() {
3849   FLAG_SET_DEFAULT(UseSerialGC, true);
3850   FLAG_SET_DEFAULT(CMSIncrementalMode, false);  // special CMS suboption
3851   UNSUPPORTED_GC_OPTION(UseG1GC);
3852   UNSUPPORTED_GC_OPTION(UseParallelGC);
3853   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
3854   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
3855   UNSUPPORTED_GC_OPTION(UseParNewGC);
3856 }
3857 #endif // INCLUDE_ALL_GCS
3858 
3859 // Sharing support
3860 // Construct the path to the archive
get_shared_archive_path()3861 static char* get_shared_archive_path() {
3862   char *shared_archive_path;
3863   if (SharedArchiveFile == NULL) {
3864     char jvm_path[JVM_MAXPATHLEN];
3865     os::jvm_path(jvm_path, sizeof(jvm_path));
3866     char *end = strrchr(jvm_path, *os::file_separator());
3867     if (end != NULL) *end = '\0';
3868     size_t jvm_path_len = strlen(jvm_path);
3869     size_t file_sep_len = strlen(os::file_separator());
3870     const size_t len = jvm_path_len + file_sep_len + 20;
3871     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtInternal);
3872     if (shared_archive_path != NULL) {
3873       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3874         jvm_path, os::file_separator());
3875     }
3876   } else {
3877     shared_archive_path = os::strdup(SharedArchiveFile, mtInternal);
3878   }
3879   return shared_archive_path;
3880 }
3881 
3882 #ifndef PRODUCT
3883 // Determine whether LogVMOutput should be implicitly turned on.
use_vm_log()3884 static bool use_vm_log() {
3885   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3886       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3887       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3888       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3889       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3890     return true;
3891   }
3892 
3893 #ifdef COMPILER1
3894   if (PrintC1Statistics) {
3895     return true;
3896   }
3897 #endif // COMPILER1
3898 
3899 #ifdef COMPILER2
3900   if (PrintOptoAssembly || PrintOptoStatistics) {
3901     return true;
3902   }
3903 #endif // COMPILER2
3904 
3905   return false;
3906 }
3907 #endif // PRODUCT
3908 
3909 // Parse entry point called from JNI_CreateJavaVM
3910 
parse(const JavaVMInitArgs * args)3911 jint Arguments::parse(const JavaVMInitArgs* args) {
3912 
3913   // Remaining part of option string
3914   const char* tail;
3915 
3916   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
3917   const char* hotspotrc = ".hotspotrc";
3918   bool settings_file_specified = false;
3919   bool needs_hotspotrc_warning = false;
3920 
3921   ArgumentsExt::process_options(args);
3922 
3923   const char* flags_file;
3924   int index;
3925   for (index = 0; index < args->nOptions; index++) {
3926     const JavaVMOption *option = args->options + index;
3927     if (match_option(option, "-XX:Flags=", &tail)) {
3928       flags_file = tail;
3929       settings_file_specified = true;
3930     }
3931     if (match_option(option, "-XX:+PrintVMOptions", &tail)) {
3932       PrintVMOptions = true;
3933     }
3934     if (match_option(option, "-XX:-PrintVMOptions", &tail)) {
3935       PrintVMOptions = false;
3936     }
3937     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions", &tail)) {
3938       IgnoreUnrecognizedVMOptions = true;
3939     }
3940     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions", &tail)) {
3941       IgnoreUnrecognizedVMOptions = false;
3942     }
3943     if (match_option(option, "-XX:+PrintFlagsInitial", &tail)) {
3944       CommandLineFlags::printFlags(tty, false);
3945       vm_exit(0);
3946     }
3947     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3948 #if INCLUDE_NMT
3949       // The launcher did not setup nmt environment variable properly.
3950       if (!MemTracker::check_launcher_nmt_support(tail)) {
3951         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3952       }
3953 
3954       // Verify if nmt option is valid.
3955       if (MemTracker::verify_nmt_option()) {
3956         // Late initialization, still in single-threaded mode.
3957         if (MemTracker::tracking_level() >= NMT_summary) {
3958           MemTracker::init();
3959         }
3960       } else {
3961         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3962       }
3963 #else
3964       jio_fprintf(defaultStream::error_stream(),
3965         "Native Memory Tracking is not supported in this VM\n");
3966       return JNI_ERR;
3967 #endif
3968     }
3969 
3970 
3971 #ifndef PRODUCT
3972     if (match_option(option, "-XX:+PrintFlagsWithComments", &tail)) {
3973       CommandLineFlags::printFlags(tty, true);
3974       vm_exit(0);
3975     }
3976 #endif
3977   }
3978 
3979   if (IgnoreUnrecognizedVMOptions) {
3980     // uncast const to modify the flag args->ignoreUnrecognized
3981     *(jboolean*)(&args->ignoreUnrecognized) = true;
3982   }
3983 
3984   // Parse specified settings file
3985   if (settings_file_specified) {
3986     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
3987       return JNI_EINVAL;
3988     }
3989   } else {
3990 #ifdef ASSERT
3991     // Parse default .hotspotrc settings file
3992     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
3993       return JNI_EINVAL;
3994     }
3995 #else
3996     struct stat buf;
3997     if (os::stat(hotspotrc, &buf) == 0) {
3998       needs_hotspotrc_warning = true;
3999     }
4000 #endif
4001   }
4002 
4003   if (PrintVMOptions) {
4004     for (index = 0; index < args->nOptions; index++) {
4005       const JavaVMOption *option = args->options + index;
4006       if (match_option(option, "-XX:", &tail)) {
4007         logOption(tail);
4008       }
4009     }
4010   }
4011 
4012   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4013   jint result = parse_vm_init_args(args);
4014   if (result != JNI_OK) {
4015     return result;
4016   }
4017 
4018   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4019   SharedArchivePath = get_shared_archive_path();
4020   if (SharedArchivePath == NULL) {
4021     return JNI_ENOMEM;
4022   }
4023 
4024   // Set up VerifySharedSpaces
4025   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4026     VerifySharedSpaces = true;
4027   }
4028 
4029   // Delay warning until here so that we've had a chance to process
4030   // the -XX:-PrintWarnings flag
4031   if (needs_hotspotrc_warning) {
4032     warning("%s file is present but has been ignored.  "
4033             "Run with -XX:Flags=%s to load the file.",
4034             hotspotrc, hotspotrc);
4035   }
4036 
4037 #if defined(_ALLBSD_SOURCE) && !defined(__FreeBSD__) && !defined(__DragonFly__)
4038   // UseLargePages is not yet supported on all BSD.
4039   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
4040 #endif
4041 
4042 #if INCLUDE_ALL_GCS
4043   #if (defined JAVASE_EMBEDDED || defined ARM)
4044     UNSUPPORTED_OPTION(UseG1GC, "G1 GC");
4045   #endif
4046 #endif
4047 
4048 #ifndef PRODUCT
4049   if (TraceBytecodesAt != 0) {
4050     TraceBytecodes = true;
4051   }
4052   if (CountCompiledCalls) {
4053     if (UseCounterDecay) {
4054       warning("UseCounterDecay disabled because CountCalls is set");
4055       UseCounterDecay = false;
4056     }
4057   }
4058 #endif // PRODUCT
4059 
4060   // JSR 292 is not supported before 1.7
4061   if (!JDK_Version::is_gte_jdk17x_version()) {
4062     if (EnableInvokeDynamic) {
4063       if (!FLAG_IS_DEFAULT(EnableInvokeDynamic)) {
4064         warning("JSR 292 is not supported before 1.7.  Disabling support.");
4065       }
4066       EnableInvokeDynamic = false;
4067     }
4068   }
4069 
4070   if (EnableInvokeDynamic && ScavengeRootsInCode == 0) {
4071     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4072       warning("forcing ScavengeRootsInCode non-zero because EnableInvokeDynamic is true");
4073     }
4074     ScavengeRootsInCode = 1;
4075   }
4076 
4077   if (PrintGCDetails) {
4078     // Turn on -verbose:gc options as well
4079     PrintGC = true;
4080   }
4081 
4082   if (!JDK_Version::is_gte_jdk18x_version()) {
4083     // To avoid changing the log format for 7 updates this flag is only
4084     // true by default in JDK8 and above.
4085     if (FLAG_IS_DEFAULT(PrintGCCause)) {
4086       FLAG_SET_DEFAULT(PrintGCCause, false);
4087     }
4088   }
4089 
4090   // Set object alignment values.
4091   set_object_alignment();
4092 
4093 #if !INCLUDE_ALL_GCS
4094   force_serial_gc();
4095 #endif // INCLUDE_ALL_GCS
4096 #if !INCLUDE_CDS
4097   if (DumpSharedSpaces || RequireSharedSpaces) {
4098     jio_fprintf(defaultStream::error_stream(),
4099       "Shared spaces are not supported in this VM\n");
4100     return JNI_ERR;
4101   }
4102   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
4103     warning("Shared spaces are not supported in this VM");
4104     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4105     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
4106   }
4107   no_shared_spaces("CDS Disabled");
4108 #endif // INCLUDE_CDS
4109 
4110   return JNI_OK;
4111 }
4112 
apply_ergo()4113 jint Arguments::apply_ergo() {
4114 
4115   // Set flags based on ergonomics.
4116   set_ergonomics_flags();
4117 
4118   set_shared_spaces_flags();
4119 
4120 #if defined(SPARC)
4121   // BIS instructions require 'membar' instruction regardless of the number
4122   // of CPUs because in virtualized/container environments which might use only 1
4123   // CPU, BIS instructions may produce incorrect results.
4124 
4125   if (FLAG_IS_DEFAULT(AssumeMP)) {
4126     FLAG_SET_DEFAULT(AssumeMP, true);
4127   }
4128 #endif
4129 
4130   // Check the GC selections again.
4131   if (!check_gc_consistency()) {
4132     return JNI_EINVAL;
4133   }
4134 
4135   if (TieredCompilation) {
4136     set_tiered_flags();
4137   } else {
4138     // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
4139     if (CompilationPolicyChoice >= 2) {
4140       vm_exit_during_initialization(
4141         "Incompatible compilation policy selected", NULL);
4142     }
4143   }
4144   // Set NmethodSweepFraction after the size of the code cache is adapted (in case of tiered)
4145   if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
4146     FLAG_SET_DEFAULT(NmethodSweepFraction, 1 + ReservedCodeCacheSize / (16 * M));
4147   }
4148 
4149 
4150   // Set heap size based on available physical memory
4151   set_heap_size();
4152 
4153   ArgumentsExt::set_gc_specific_flags();
4154 
4155   // Initialize Metaspace flags and alignments.
4156   Metaspace::ergo_initialize();
4157 
4158   // Set bytecode rewriting flags
4159   set_bytecode_flags();
4160 
4161   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.
4162   set_aggressive_opts_flags();
4163 
4164   // Turn off biased locking for locking debug mode flags,
4165   // which are subtlely different from each other but neither works with
4166   // biased locking.
4167   if (UseHeavyMonitors
4168 #ifdef COMPILER1
4169       || !UseFastLocking
4170 #endif // COMPILER1
4171     ) {
4172     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4173       // flag set to true on command line; warn the user that they
4174       // can't enable biased locking here
4175       warning("Biased Locking is not supported with locking debug flags"
4176               "; ignoring UseBiasedLocking flag." );
4177     }
4178     UseBiasedLocking = false;
4179   }
4180 
4181 #ifdef ZERO
4182   // Clear flags not supported on zero.
4183   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4184   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4185   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4186   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4187 #endif // CC_INTERP
4188 
4189 #ifdef COMPILER2
4190   if (!EliminateLocks) {
4191     EliminateNestedLocks = false;
4192   }
4193   if (!Inline) {
4194     IncrementalInline = false;
4195   }
4196 #ifndef PRODUCT
4197   if (!IncrementalInline) {
4198     AlwaysIncrementalInline = false;
4199   }
4200 #endif
4201   if (IncrementalInline && FLAG_IS_DEFAULT(MaxNodeLimit)) {
4202     // incremental inlining: bump MaxNodeLimit
4203     FLAG_SET_DEFAULT(MaxNodeLimit, (intx)75000);
4204   }
4205   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4206     // nothing to use the profiling, turn if off
4207     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4208   }
4209 #endif
4210 
4211   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4212     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4213     DebugNonSafepoints = true;
4214   }
4215 
4216   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4217     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4218   }
4219 
4220   if (UseOnStackReplacement && !UseLoopCounter) {
4221     warning("On-stack-replacement requires loop counters; enabling loop counters");
4222     FLAG_SET_DEFAULT(UseLoopCounter, true);
4223   }
4224 
4225 #ifndef PRODUCT
4226   if (CompileTheWorld) {
4227     // Force NmethodSweeper to sweep whole CodeCache each time.
4228     if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
4229       NmethodSweepFraction = 1;
4230     }
4231   }
4232 
4233   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4234     if (use_vm_log()) {
4235       LogVMOutput = true;
4236     }
4237   }
4238 #endif // PRODUCT
4239 
4240   if (PrintCommandLineFlags) {
4241     CommandLineFlags::printSetFlags(tty);
4242   }
4243 
4244   // Apply CPU specific policy for the BiasedLocking
4245   if (UseBiasedLocking) {
4246     if (!VM_Version::use_biased_locking() &&
4247         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4248       UseBiasedLocking = false;
4249     }
4250   }
4251 #ifdef COMPILER2
4252   if (!UseBiasedLocking || EmitSync != 0) {
4253     UseOptoBiasInlining = false;
4254   }
4255 #endif
4256 
4257   // set PauseAtExit if the gamma launcher was used and a debugger is attached
4258   // but only if not already set on the commandline
4259   if (Arguments::created_by_gamma_launcher() && os::is_debugger_attached()) {
4260     bool set = false;
4261     CommandLineFlags::wasSetOnCmdline("PauseAtExit", &set);
4262     if (!set) {
4263       FLAG_SET_DEFAULT(PauseAtExit, true);
4264     }
4265   }
4266 
4267   return JNI_OK;
4268 }
4269 
adjust_after_os()4270 jint Arguments::adjust_after_os() {
4271   if (UseNUMA) {
4272     if (UseParallelGC || UseParallelOldGC) {
4273       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4274          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4275       }
4276     }
4277     // UseNUMAInterleaving is set to ON for all collectors and
4278     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4279     // such as the parallel collector for Linux and Solaris will
4280     // interleave old gen and survivor spaces on top of NUMA
4281     // allocation policy for the eden space.
4282     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4283     // all platforms and ParallelGC on Windows will interleave all
4284     // of the heap spaces across NUMA nodes.
4285     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4286       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4287     }
4288   }
4289   return JNI_OK;
4290 }
4291 
PropertyList_count(SystemProperty * pl)4292 int Arguments::PropertyList_count(SystemProperty* pl) {
4293   int count = 0;
4294   while(pl != NULL) {
4295     count++;
4296     pl = pl->next();
4297   }
4298   return count;
4299 }
4300 
PropertyList_get_value(SystemProperty * pl,const char * key)4301 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4302   assert(key != NULL, "just checking");
4303   SystemProperty* prop;
4304   for (prop = pl; prop != NULL; prop = prop->next()) {
4305     if (strcmp(key, prop->key()) == 0) return prop->value();
4306   }
4307   return NULL;
4308 }
4309 
PropertyList_get_key_at(SystemProperty * pl,int index)4310 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4311   int count = 0;
4312   const char* ret_val = NULL;
4313 
4314   while(pl != NULL) {
4315     if(count >= index) {
4316       ret_val = pl->key();
4317       break;
4318     }
4319     count++;
4320     pl = pl->next();
4321   }
4322 
4323   return ret_val;
4324 }
4325 
PropertyList_get_value_at(SystemProperty * pl,int index)4326 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4327   int count = 0;
4328   char* ret_val = NULL;
4329 
4330   while(pl != NULL) {
4331     if(count >= index) {
4332       ret_val = pl->value();
4333       break;
4334     }
4335     count++;
4336     pl = pl->next();
4337   }
4338 
4339   return ret_val;
4340 }
4341 
PropertyList_add(SystemProperty ** plist,SystemProperty * new_p)4342 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4343   SystemProperty* p = *plist;
4344   if (p == NULL) {
4345     *plist = new_p;
4346   } else {
4347     while (p->next() != NULL) {
4348       p = p->next();
4349     }
4350     p->set_next(new_p);
4351   }
4352 }
4353 
PropertyList_add(SystemProperty ** plist,const char * k,char * v)4354 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
4355   if (plist == NULL)
4356     return;
4357 
4358   SystemProperty* new_p = new SystemProperty(k, v, true);
4359   PropertyList_add(plist, new_p);
4360 }
4361 
4362 // This add maintains unique property key in the list.
PropertyList_unique_add(SystemProperty ** plist,const char * k,char * v,jboolean append)4363 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
4364   if (plist == NULL)
4365     return;
4366 
4367   // If property key exist then update with new value.
4368   SystemProperty* prop;
4369   for (prop = *plist; prop != NULL; prop = prop->next()) {
4370     if (strcmp(k, prop->key()) == 0) {
4371       if (append) {
4372         prop->append_value(v);
4373       } else {
4374         prop->set_value(v);
4375       }
4376       return;
4377     }
4378   }
4379 
4380   PropertyList_add(plist, k, v);
4381 }
4382 
4383 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4384 // Returns true if all of the source pointed by src has been copied over to
4385 // the destination buffer pointed by buf. Otherwise, returns false.
4386 // Notes:
4387 // 1. If the length (buflen) of the destination buffer excluding the
4388 // NULL terminator character is not long enough for holding the expanded
4389 // pid characters, it also returns false instead of returning the partially
4390 // expanded one.
4391 // 2. The passed in "buflen" should be large enough to hold the null terminator.
copy_expand_pid(const char * src,size_t srclen,char * buf,size_t buflen)4392 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4393                                 char* buf, size_t buflen) {
4394   const char* p = src;
4395   char* b = buf;
4396   const char* src_end = &src[srclen];
4397   char* buf_end = &buf[buflen - 1];
4398 
4399   while (p < src_end && b < buf_end) {
4400     if (*p == '%') {
4401       switch (*(++p)) {
4402       case '%':         // "%%" ==> "%"
4403         *b++ = *p++;
4404         break;
4405       case 'p':  {       //  "%p" ==> current process id
4406         // buf_end points to the character before the last character so
4407         // that we could write '\0' to the end of the buffer.
4408         size_t buf_sz = buf_end - b + 1;
4409         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4410 
4411         // if jio_snprintf fails or the buffer is not long enough to hold
4412         // the expanded pid, returns false.
4413         if (ret < 0 || ret >= (int)buf_sz) {
4414           return false;
4415         } else {
4416           b += ret;
4417           assert(*b == '\0', "fail in copy_expand_pid");
4418           if (p == src_end && b == buf_end + 1) {
4419             // reach the end of the buffer.
4420             return true;
4421           }
4422         }
4423         p++;
4424         break;
4425       }
4426       default :
4427         *b++ = '%';
4428       }
4429     } else {
4430       *b++ = *p++;
4431     }
4432   }
4433   *b = '\0';
4434   return (p == src_end); // return false if not all of the source was copied
4435 }
4436