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