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