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