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