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