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