src/share/vm/runtime/arguments.cpp

Wed, 14 Oct 2020 17:44:48 +0800

author
aoqi
date
Wed, 14 Oct 2020 17:44:48 +0800
changeset 9931
fd44df5e3bc3
parent 9852
70aa912cebe5
parent 9920
3a3803a0c789
permissions
-rw-r--r--

Merge

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

mercurial