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