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