src/share/vm/runtime/arguments.cpp

Tue, 07 May 2019 20:38:26 +0000

author
phh
date
Tue, 07 May 2019 20:38:26 +0000
changeset 9669
32bc598624bd
parent 9634
d1520f0c3524
child 9637
eef07cd490d4
child 9711
0f2fe7d37d8c
permissions
-rw-r--r--

8176100: [REDO][REDO] G1 Needs pre barrier on dereference of weak JNI handles
Summary: Add tag bit to all JNI weak handles
Reviewed-by: kbarrett, coleenp, tschatzl

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

mercurial