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