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