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