src/share/vm/runtime/arguments.cpp

Thu, 16 Jan 2020 10:47:16 +0800

author
ddong
date
Thu, 16 Jan 2020 10:47:16 +0800
changeset 9817
8c3a44b7ecfc
parent 9711
0f2fe7d37d8c
child 9820
a67e9c6edcdd
permissions
-rw-r--r--

8232355: Two obsolete flags have the wrong obsolete version in 8u
Summary: Correct the obsolete version of UseOldInlining and AutoShutdownNMT, and delete UseOldInlining in c2_globals.hpp
Reviewed-by: phh

     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_update(8, 20), JDK_Version::jdk(10) },
   306   { "AutoShutdownNMT",               JDK_Version::jdk_update(8, 40), 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   while ((entry = os::readdir(dir)) != NULL) {
   560     const char* name = entry->d_name;
   561     const char* ext = name + strlen(name) - 4;
   562     bool isJarOrZip = ext > name &&
   563       (os::file_name_strcmp(ext, ".jar") == 0 ||
   564        os::file_name_strcmp(ext, ".zip") == 0);
   565     if (isJarOrZip) {
   566       size_t length = directory_len + 2 + strlen(name);
   567       char* jarpath = NEW_C_HEAP_ARRAY(char, length, mtInternal);
   568       jio_snprintf(jarpath, length, "%s%s%s", directory, dir_sep, name);
   569       path = add_to_path(path, jarpath, false);
   570       FREE_C_HEAP_ARRAY(char, jarpath, mtInternal);
   571     }
   572   }
   573   os::closedir(dir);
   574   return path;
   575 }
   577 // Parses a memory size specification string.
   578 static bool atomull(const char *s, julong* result) {
   579   julong n = 0;
   580   int args_read = sscanf(s, JULONG_FORMAT, &n);
   581   if (args_read != 1) {
   582     return false;
   583   }
   584   while (*s != '\0' && isdigit(*s)) {
   585     s++;
   586   }
   587   // 4705540: illegal if more characters are found after the first non-digit
   588   if (strlen(s) > 1) {
   589     return false;
   590   }
   591   switch (*s) {
   592     case 'T': case 't':
   593       *result = n * G * K;
   594       // Check for overflow.
   595       if (*result/((julong)G * K) != n) return false;
   596       return true;
   597     case 'G': case 'g':
   598       *result = n * G;
   599       if (*result/G != n) return false;
   600       return true;
   601     case 'M': case 'm':
   602       *result = n * M;
   603       if (*result/M != n) return false;
   604       return true;
   605     case 'K': case 'k':
   606       *result = n * K;
   607       if (*result/K != n) return false;
   608       return true;
   609     case '\0':
   610       *result = n;
   611       return true;
   612     default:
   613       return false;
   614   }
   615 }
   617 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size) {
   618   if (size < min_size) return arg_too_small;
   619   // Check that size will fit in a size_t (only relevant on 32-bit)
   620   if (size > max_uintx) return arg_too_big;
   621   return arg_in_range;
   622 }
   624 // Describe an argument out of range error
   625 void Arguments::describe_range_error(ArgsRange errcode) {
   626   switch(errcode) {
   627   case arg_too_big:
   628     jio_fprintf(defaultStream::error_stream(),
   629                 "The specified size exceeds the maximum "
   630                 "representable size.\n");
   631     break;
   632   case arg_too_small:
   633   case arg_unreadable:
   634   case arg_in_range:
   635     // do nothing for now
   636     break;
   637   default:
   638     ShouldNotReachHere();
   639   }
   640 }
   642 static bool set_bool_flag(char* name, bool value, Flag::Flags origin) {
   643   return CommandLineFlags::boolAtPut(name, &value, origin);
   644 }
   646 static bool set_fp_numeric_flag(char* name, char* value, Flag::Flags origin) {
   647   double v;
   648   if (sscanf(value, "%lf", &v) != 1) {
   649     return false;
   650   }
   652   if (CommandLineFlags::doubleAtPut(name, &v, origin)) {
   653     return true;
   654   }
   655   return false;
   656 }
   658 static bool set_numeric_flag(char* name, char* value, Flag::Flags origin) {
   659   julong v;
   660   intx intx_v;
   661   bool is_neg = false;
   662   // Check the sign first since atomull() parses only unsigned values.
   663   if (*value == '-') {
   664     if (!CommandLineFlags::intxAt(name, &intx_v)) {
   665       return false;
   666     }
   667     value++;
   668     is_neg = true;
   669   }
   670   if (!atomull(value, &v)) {
   671     return false;
   672   }
   673   intx_v = (intx) v;
   674   if (is_neg) {
   675     intx_v = -intx_v;
   676   }
   677   if (CommandLineFlags::intxAtPut(name, &intx_v, origin)) {
   678     return true;
   679   }
   680   uintx uintx_v = (uintx) v;
   681   if (!is_neg && CommandLineFlags::uintxAtPut(name, &uintx_v, origin)) {
   682     return true;
   683   }
   684   uint64_t uint64_t_v = (uint64_t) v;
   685   if (!is_neg && CommandLineFlags::uint64_tAtPut(name, &uint64_t_v, origin)) {
   686     return true;
   687   }
   688   return false;
   689 }
   691 static bool set_string_flag(char* name, const char* value, Flag::Flags origin) {
   692   if (!CommandLineFlags::ccstrAtPut(name, &value, origin))  return false;
   693   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
   694   FREE_C_HEAP_ARRAY(char, value, mtInternal);
   695   return true;
   696 }
   698 static bool append_to_string_flag(char* name, const char* new_value, Flag::Flags origin) {
   699   const char* old_value = "";
   700   if (!CommandLineFlags::ccstrAt(name, &old_value))  return false;
   701   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
   702   size_t new_len = strlen(new_value);
   703   const char* value;
   704   char* free_this_too = NULL;
   705   if (old_len == 0) {
   706     value = new_value;
   707   } else if (new_len == 0) {
   708     value = old_value;
   709   } else {
   710     size_t length = old_len + 1 + new_len + 1;
   711     char* buf = NEW_C_HEAP_ARRAY(char, length, mtInternal);
   712     // each new setting adds another LINE to the switch:
   713     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
   714     value = buf;
   715     free_this_too = buf;
   716   }
   717   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
   718   // CommandLineFlags always returns a pointer that needs freeing.
   719   FREE_C_HEAP_ARRAY(char, value, mtInternal);
   720   if (free_this_too != NULL) {
   721     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
   722     FREE_C_HEAP_ARRAY(char, free_this_too, mtInternal);
   723   }
   724   return true;
   725 }
   727 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
   729   // range of acceptable characters spelled out for portability reasons
   730 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
   731 #define BUFLEN 255
   732   char name[BUFLEN+1];
   733   char dummy;
   735   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
   736     return set_bool_flag(name, false, origin);
   737   }
   738   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
   739     return set_bool_flag(name, true, origin);
   740   }
   742   char punct;
   743   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
   744     const char* value = strchr(arg, '=') + 1;
   745     Flag* flag = Flag::find_flag(name, strlen(name));
   746     if (flag != NULL && flag->is_ccstr()) {
   747       if (flag->ccstr_accumulates()) {
   748         return append_to_string_flag(name, value, origin);
   749       } else {
   750         if (value[0] == '\0') {
   751           value = NULL;
   752         }
   753         return set_string_flag(name, value, origin);
   754       }
   755     }
   756   }
   758   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
   759     const char* value = strchr(arg, '=') + 1;
   760     // -XX:Foo:=xxx will reset the string flag to the given value.
   761     if (value[0] == '\0') {
   762       value = NULL;
   763     }
   764     return set_string_flag(name, value, origin);
   765   }
   767 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.]"
   768 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
   769 #define        NUMBER_RANGE    "[0123456789]"
   770   char value[BUFLEN + 1];
   771   char value2[BUFLEN + 1];
   772   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
   773     // Looks like a floating-point number -- try again with more lenient format string
   774     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
   775       return set_fp_numeric_flag(name, value, origin);
   776     }
   777   }
   779 #define VALUE_RANGE "[-kmgtKMGT0123456789]"
   780   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
   781     return set_numeric_flag(name, value, origin);
   782   }
   784   return false;
   785 }
   787 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
   788   assert(bldarray != NULL, "illegal argument");
   790   if (arg == NULL) {
   791     return;
   792   }
   794   int new_count = *count + 1;
   796   // expand the array and add arg to the last element
   797   if (*bldarray == NULL) {
   798     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtInternal);
   799   } else {
   800     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtInternal);
   801   }
   802   (*bldarray)[*count] = strdup(arg);
   803   *count = new_count;
   804 }
   806 void Arguments::build_jvm_args(const char* arg) {
   807   add_string(&_jvm_args_array, &_num_jvm_args, arg);
   808 }
   810 void Arguments::build_jvm_flags(const char* arg) {
   811   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
   812 }
   814 // utility function to return a string that concatenates all
   815 // strings in a given char** array
   816 const char* Arguments::build_resource_string(char** args, int count) {
   817   if (args == NULL || count == 0) {
   818     return NULL;
   819   }
   820   size_t length = 0;
   821   for (int i = 0; i < count; i++) {
   822     length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
   823   }
   824   char* s = NEW_RESOURCE_ARRAY(char, length);
   825   char* dst = s;
   826   for (int j = 0; j < count; j++) {
   827     size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
   828     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
   829     dst += offset;
   830     length -= offset;
   831   }
   832   return (const char*) s;
   833 }
   835 void Arguments::print_on(outputStream* st) {
   836   st->print_cr("VM Arguments:");
   837   if (num_jvm_flags() > 0) {
   838     st->print("jvm_flags: "); print_jvm_flags_on(st);
   839   }
   840   if (num_jvm_args() > 0) {
   841     st->print("jvm_args: "); print_jvm_args_on(st);
   842   }
   843   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
   844   if (_java_class_path != NULL) {
   845     char* path = _java_class_path->value();
   846     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
   847   }
   848   st->print_cr("Launcher Type: %s", _sun_java_launcher);
   849 }
   851 void Arguments::print_jvm_flags_on(outputStream* st) {
   852   if (_num_jvm_flags > 0) {
   853     for (int i=0; i < _num_jvm_flags; i++) {
   854       st->print("%s ", _jvm_flags_array[i]);
   855     }
   856     st->cr();
   857   }
   858 }
   860 void Arguments::print_jvm_args_on(outputStream* st) {
   861   if (_num_jvm_args > 0) {
   862     for (int i=0; i < _num_jvm_args; i++) {
   863       st->print("%s ", _jvm_args_array[i]);
   864     }
   865     st->cr();
   866   }
   867 }
   869 bool Arguments::process_argument(const char* arg,
   870     jboolean ignore_unrecognized, Flag::Flags origin) {
   872   JDK_Version since = JDK_Version();
   874   if (parse_argument(arg, origin) || ignore_unrecognized) {
   875     return true;
   876   }
   878   bool has_plus_minus = (*arg == '+' || *arg == '-');
   879   const char* const argname = has_plus_minus ? arg + 1 : arg;
   880   if (is_newly_obsolete(arg, &since)) {
   881     char version[256];
   882     since.to_string(version, sizeof(version));
   883     warning("ignoring option %s; support was removed in %s", argname, version);
   884     return true;
   885   }
   887   // For locked flags, report a custom error message if available.
   888   // Otherwise, report the standard unrecognized VM option.
   890   size_t arg_len;
   891   const char* equal_sign = strchr(argname, '=');
   892   if (equal_sign == NULL) {
   893     arg_len = strlen(argname);
   894   } else {
   895     arg_len = equal_sign - argname;
   896   }
   898   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
   899   if (found_flag != NULL) {
   900     char locked_message_buf[BUFLEN];
   901     found_flag->get_locked_message(locked_message_buf, BUFLEN);
   902     if (strlen(locked_message_buf) == 0) {
   903       if (found_flag->is_bool() && !has_plus_minus) {
   904         jio_fprintf(defaultStream::error_stream(),
   905           "Missing +/- setting for VM option '%s'\n", argname);
   906       } else if (!found_flag->is_bool() && has_plus_minus) {
   907         jio_fprintf(defaultStream::error_stream(),
   908           "Unexpected +/- setting in VM option '%s'\n", argname);
   909       } else {
   910         jio_fprintf(defaultStream::error_stream(),
   911           "Improperly specified VM option '%s'\n", argname);
   912       }
   913     } else {
   914       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
   915     }
   916   } else {
   917     jio_fprintf(defaultStream::error_stream(),
   918                 "Unrecognized VM option '%s'\n", argname);
   919     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
   920     if (fuzzy_matched != NULL) {
   921       jio_fprintf(defaultStream::error_stream(),
   922                   "Did you mean '%s%s%s'?\n",
   923                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
   924                   fuzzy_matched->_name,
   925                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
   926     }
   927   }
   929   // allow for commandline "commenting out" options like -XX:#+Verbose
   930   return arg[0] == '#';
   931 }
   933 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
   934   FILE* stream = fopen(file_name, "rb");
   935   if (stream == NULL) {
   936     if (should_exist) {
   937       jio_fprintf(defaultStream::error_stream(),
   938                   "Could not open settings file %s\n", file_name);
   939       return false;
   940     } else {
   941       return true;
   942     }
   943   }
   945   char token[1024];
   946   int  pos = 0;
   948   bool in_white_space = true;
   949   bool in_comment     = false;
   950   bool in_quote       = false;
   951   char quote_c        = 0;
   952   bool result         = true;
   954   int c = getc(stream);
   955   while(c != EOF && pos < (int)(sizeof(token)-1)) {
   956     if (in_white_space) {
   957       if (in_comment) {
   958         if (c == '\n') in_comment = false;
   959       } else {
   960         if (c == '#') in_comment = true;
   961         else if (!isspace(c)) {
   962           in_white_space = false;
   963           token[pos++] = c;
   964         }
   965       }
   966     } else {
   967       if (c == '\n' || (!in_quote && isspace(c))) {
   968         // token ends at newline, or at unquoted whitespace
   969         // this allows a way to include spaces in string-valued options
   970         token[pos] = '\0';
   971         logOption(token);
   972         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
   973         build_jvm_flags(token);
   974         pos = 0;
   975         in_white_space = true;
   976         in_quote = false;
   977       } else if (!in_quote && (c == '\'' || c == '"')) {
   978         in_quote = true;
   979         quote_c = c;
   980       } else if (in_quote && (c == quote_c)) {
   981         in_quote = false;
   982       } else {
   983         token[pos++] = c;
   984       }
   985     }
   986     c = getc(stream);
   987   }
   988   if (pos > 0) {
   989     token[pos] = '\0';
   990     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
   991     build_jvm_flags(token);
   992   }
   993   fclose(stream);
   994   return result;
   995 }
   997 //=============================================================================================================
   998 // Parsing of properties (-D)
  1000 const char* Arguments::get_property(const char* key) {
  1001   return PropertyList_get_value(system_properties(), key);
  1004 bool Arguments::add_property(const char* prop) {
  1005   const char* eq = strchr(prop, '=');
  1006   char* key;
  1007   // ns must be static--its address may be stored in a SystemProperty object.
  1008   const static char ns[1] = {0};
  1009   char* value = (char *)ns;
  1011   size_t key_len = (eq == NULL) ? strlen(prop) : (eq - prop);
  1012   key = AllocateHeap(key_len + 1, mtInternal);
  1013   strncpy(key, prop, key_len);
  1014   key[key_len] = '\0';
  1016   if (eq != NULL) {
  1017     size_t value_len = strlen(prop) - key_len - 1;
  1018     value = AllocateHeap(value_len + 1, mtInternal);
  1019     strncpy(value, &prop[key_len + 1], value_len + 1);
  1022   if (strcmp(key, "java.compiler") == 0) {
  1023     process_java_compiler_argument(value);
  1024     FreeHeap(key);
  1025     if (eq != NULL) {
  1026       FreeHeap(value);
  1028     return true;
  1029   } else if (strcmp(key, "sun.java.command") == 0) {
  1030     _java_command = value;
  1032     // Record value in Arguments, but let it get passed to Java.
  1033   } else if (strcmp(key, "sun.java.launcher.pid") == 0) {
  1034     // launcher.pid property is private and is processed
  1035     // in process_sun_java_launcher_properties();
  1036     // the sun.java.launcher property is passed on to the java application
  1037     FreeHeap(key);
  1038     if (eq != NULL) {
  1039       FreeHeap(value);
  1041     return true;
  1042   } else if (strcmp(key, "java.vendor.url.bug") == 0) {
  1043     // save it in _java_vendor_url_bug, so JVM fatal error handler can access
  1044     // its value without going through the property list or making a Java call.
  1045     _java_vendor_url_bug = value;
  1046   } else if (strcmp(key, "sun.boot.library.path") == 0) {
  1047     PropertyList_unique_add(&_system_properties, key, value, true);
  1048     return true;
  1050   // Create new property and add at the end of the list
  1051   PropertyList_unique_add(&_system_properties, key, value);
  1052   return true;
  1055 //===========================================================================================================
  1056 // Setting int/mixed/comp mode flags
  1058 void Arguments::set_mode_flags(Mode mode) {
  1059   // Set up default values for all flags.
  1060   // If you add a flag to any of the branches below,
  1061   // add a default value for it here.
  1062   set_java_compiler(false);
  1063   _mode                      = mode;
  1065   // Ensure Agent_OnLoad has the correct initial values.
  1066   // This may not be the final mode; mode may change later in onload phase.
  1067   PropertyList_unique_add(&_system_properties, "java.vm.info",
  1068                           (char*)VM_Version::vm_info_string(), false);
  1070   UseInterpreter             = true;
  1071   UseCompiler                = true;
  1072   UseLoopCounter             = true;
  1074 #ifndef ZERO
  1075   // Turn these off for mixed and comp.  Leave them on for Zero.
  1076   if (FLAG_IS_DEFAULT(UseFastAccessorMethods)) {
  1077     UseFastAccessorMethods = (mode == _int);
  1079   if (FLAG_IS_DEFAULT(UseFastEmptyMethods)) {
  1080     UseFastEmptyMethods = (mode == _int);
  1082 #endif
  1084   // Default values may be platform/compiler dependent -
  1085   // use the saved values
  1086   ClipInlining               = Arguments::_ClipInlining;
  1087   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
  1088   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
  1089   BackgroundCompilation      = Arguments::_BackgroundCompilation;
  1091   // Change from defaults based on mode
  1092   switch (mode) {
  1093   default:
  1094     ShouldNotReachHere();
  1095     break;
  1096   case _int:
  1097     UseCompiler              = false;
  1098     UseLoopCounter           = false;
  1099     AlwaysCompileLoopMethods = false;
  1100     UseOnStackReplacement    = false;
  1101     break;
  1102   case _mixed:
  1103     // same as default
  1104     break;
  1105   case _comp:
  1106     UseInterpreter           = false;
  1107     BackgroundCompilation    = false;
  1108     ClipInlining             = false;
  1109     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
  1110     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
  1111     // compile a level 4 (C2) and then continue executing it.
  1112     if (TieredCompilation) {
  1113       Tier3InvokeNotifyFreqLog = 0;
  1114       Tier4InvocationThreshold = 0;
  1116     break;
  1120 #if defined(COMPILER2) || defined(_LP64) || !INCLUDE_CDS
  1121 // Conflict: required to use shared spaces (-Xshare:on), but
  1122 // incompatible command line options were chosen.
  1124 static void no_shared_spaces(const char* message) {
  1125   if (RequireSharedSpaces) {
  1126     jio_fprintf(defaultStream::error_stream(),
  1127       "Class data sharing is inconsistent with other specified options.\n");
  1128     vm_exit_during_initialization("Unable to use shared archive.", message);
  1129   } else {
  1130     FLAG_SET_DEFAULT(UseSharedSpaces, false);
  1133 #endif
  1135 void Arguments::set_tiered_flags() {
  1136   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
  1137   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
  1138     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
  1140   if (CompilationPolicyChoice < 2) {
  1141     vm_exit_during_initialization(
  1142       "Incompatible compilation policy selected", NULL);
  1144   // Increase the code cache size - tiered compiles a lot more.
  1145   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
  1146     FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);
  1148   if (!UseInterpreter) { // -Xcomp
  1149     Tier3InvokeNotifyFreqLog = 0;
  1150     Tier4InvocationThreshold = 0;
  1154 /**
  1155  * Returns the minimum number of compiler threads needed to run the JVM. The following
  1156  * configurations are possible.
  1158  * 1) The JVM is build using an interpreter only. As a result, the minimum number of
  1159  *    compiler threads is 0.
  1160  * 2) The JVM is build using the compiler(s) and tiered compilation is disabled. As
  1161  *    a result, either C1 or C2 is used, so the minimum number of compiler threads is 1.
  1162  * 3) The JVM is build using the compiler(s) and tiered compilation is enabled. However,
  1163  *    the option "TieredStopAtLevel < CompLevel_full_optimization". As a result, only
  1164  *    C1 can be used, so the minimum number of compiler threads is 1.
  1165  * 4) The JVM is build using the compilers and tiered compilation is enabled. The option
  1166  *    'TieredStopAtLevel = CompLevel_full_optimization' (the default value). As a result,
  1167  *    the minimum number of compiler threads is 2.
  1168  */
  1169 int Arguments::get_min_number_of_compiler_threads() {
  1170 #if !defined(COMPILER1) && !defined(COMPILER2) && !defined(SHARK)
  1171   return 0;   // case 1
  1172 #else
  1173   if (!TieredCompilation || (TieredStopAtLevel < CompLevel_full_optimization)) {
  1174     return 1; // case 2 or case 3
  1176   return 2;   // case 4 (tiered)
  1177 #endif
  1180 #if INCLUDE_ALL_GCS
  1181 static void disable_adaptive_size_policy(const char* collector_name) {
  1182   if (UseAdaptiveSizePolicy) {
  1183     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
  1184       warning("disabling UseAdaptiveSizePolicy; it is incompatible with %s.",
  1185               collector_name);
  1187     FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false);
  1191 void Arguments::set_parnew_gc_flags() {
  1192   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
  1193          "control point invariant");
  1194   assert(UseParNewGC, "Error");
  1196   // Turn off AdaptiveSizePolicy for parnew until it is complete.
  1197   disable_adaptive_size_policy("UseParNewGC");
  1199   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
  1200     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
  1201     assert(ParallelGCThreads > 0, "We should always have at least one thread by default");
  1202   } else if (ParallelGCThreads == 0) {
  1203     jio_fprintf(defaultStream::error_stream(),
  1204         "The ParNew GC can not be combined with -XX:ParallelGCThreads=0\n");
  1205     vm_exit(1);
  1208   // By default YoungPLABSize and OldPLABSize are set to 4096 and 1024 respectively,
  1209   // these settings are default for Parallel Scavenger. For ParNew+Tenured configuration
  1210   // we set them to 1024 and 1024.
  1211   // See CR 6362902.
  1212   if (FLAG_IS_DEFAULT(YoungPLABSize)) {
  1213     FLAG_SET_DEFAULT(YoungPLABSize, (intx)1024);
  1215   if (FLAG_IS_DEFAULT(OldPLABSize)) {
  1216     FLAG_SET_DEFAULT(OldPLABSize, (intx)1024);
  1219   // AlwaysTenure flag should make ParNew promote all at first collection.
  1220   // See CR 6362902.
  1221   if (AlwaysTenure) {
  1222     FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0);
  1224   // When using compressed oops, we use local overflow stacks,
  1225   // rather than using a global overflow list chained through
  1226   // the klass word of the object's pre-image.
  1227   if (UseCompressedOops && !ParGCUseLocalOverflow) {
  1228     if (!FLAG_IS_DEFAULT(ParGCUseLocalOverflow)) {
  1229       warning("Forcing +ParGCUseLocalOverflow: needed if using compressed references");
  1231     FLAG_SET_DEFAULT(ParGCUseLocalOverflow, true);
  1233   assert(ParGCUseLocalOverflow || !UseCompressedOops, "Error");
  1236 // Adjust some sizes to suit CMS and/or ParNew needs; these work well on
  1237 // sparc/solaris for certain applications, but would gain from
  1238 // further optimization and tuning efforts, and would almost
  1239 // certainly gain from analysis of platform and environment.
  1240 void Arguments::set_cms_and_parnew_gc_flags() {
  1241   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
  1242   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
  1244   // If we are using CMS, we prefer to UseParNewGC,
  1245   // unless explicitly forbidden.
  1246   if (FLAG_IS_DEFAULT(UseParNewGC)) {
  1247     FLAG_SET_ERGO(bool, UseParNewGC, true);
  1250   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
  1251   disable_adaptive_size_policy("UseConcMarkSweepGC");
  1253   // In either case, adjust ParallelGCThreads and/or UseParNewGC
  1254   // as needed.
  1255   if (UseParNewGC) {
  1256     set_parnew_gc_flags();
  1259   size_t max_heap = align_size_down(MaxHeapSize,
  1260                                     CardTableRS::ct_max_alignment_constraint());
  1262   // Now make adjustments for CMS
  1263   intx   tenuring_default = (intx)6;
  1264   size_t young_gen_per_worker = CMSYoungGenPerWorker;
  1266   // Preferred young gen size for "short" pauses:
  1267   // upper bound depends on # of threads and NewRatio.
  1268   const uintx parallel_gc_threads =
  1269     (ParallelGCThreads == 0 ? 1 : ParallelGCThreads);
  1270   const size_t preferred_max_new_size_unaligned =
  1271     MIN2(max_heap/(NewRatio+1), ScaleForWordSize(young_gen_per_worker * parallel_gc_threads));
  1272   size_t preferred_max_new_size =
  1273     align_size_up(preferred_max_new_size_unaligned, os::vm_page_size());
  1275   // Unless explicitly requested otherwise, size young gen
  1276   // for "short" pauses ~ CMSYoungGenPerWorker*ParallelGCThreads
  1278   // If either MaxNewSize or NewRatio is set on the command line,
  1279   // assume the user is trying to set the size of the young gen.
  1280   if (FLAG_IS_DEFAULT(MaxNewSize) && FLAG_IS_DEFAULT(NewRatio)) {
  1282     // Set MaxNewSize to our calculated preferred_max_new_size unless
  1283     // NewSize was set on the command line and it is larger than
  1284     // preferred_max_new_size.
  1285     if (!FLAG_IS_DEFAULT(NewSize)) {   // NewSize explicitly set at command-line
  1286       FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size));
  1287     } else {
  1288       FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size);
  1290     if (PrintGCDetails && Verbose) {
  1291       // Too early to use gclog_or_tty
  1292       tty->print_cr("CMS ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize);
  1295     // Code along this path potentially sets NewSize and OldSize
  1296     if (PrintGCDetails && Verbose) {
  1297       // Too early to use gclog_or_tty
  1298       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
  1299            " initial_heap_size:  " SIZE_FORMAT
  1300            " max_heap: " SIZE_FORMAT,
  1301            min_heap_size(), InitialHeapSize, max_heap);
  1303     size_t min_new = preferred_max_new_size;
  1304     if (FLAG_IS_CMDLINE(NewSize)) {
  1305       min_new = NewSize;
  1307     if (max_heap > min_new && min_heap_size() > min_new) {
  1308       // Unless explicitly requested otherwise, make young gen
  1309       // at least min_new, and at most preferred_max_new_size.
  1310       if (FLAG_IS_DEFAULT(NewSize)) {
  1311         FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new));
  1312         FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize));
  1313         if (PrintGCDetails && Verbose) {
  1314           // Too early to use gclog_or_tty
  1315           tty->print_cr("CMS ergo set NewSize: " SIZE_FORMAT, NewSize);
  1318       // Unless explicitly requested otherwise, size old gen
  1319       // so it's NewRatio x of NewSize.
  1320       if (FLAG_IS_DEFAULT(OldSize)) {
  1321         if (max_heap > NewSize) {
  1322           FLAG_SET_ERGO(uintx, OldSize, MIN2(NewRatio*NewSize, max_heap - NewSize));
  1323           if (PrintGCDetails && Verbose) {
  1324             // Too early to use gclog_or_tty
  1325             tty->print_cr("CMS ergo set OldSize: " SIZE_FORMAT, OldSize);
  1331   // Unless explicitly requested otherwise, definitely
  1332   // promote all objects surviving "tenuring_default" scavenges.
  1333   if (FLAG_IS_DEFAULT(MaxTenuringThreshold) &&
  1334       FLAG_IS_DEFAULT(SurvivorRatio)) {
  1335     FLAG_SET_ERGO(uintx, MaxTenuringThreshold, tenuring_default);
  1337   // If we decided above (or user explicitly requested)
  1338   // `promote all' (via MaxTenuringThreshold := 0),
  1339   // prefer minuscule survivor spaces so as not to waste
  1340   // space for (non-existent) survivors
  1341   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
  1342     FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
  1344   // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
  1345   // set CMSParPromoteBlocksToClaim equal to OldPLABSize.
  1346   // This is done in order to make ParNew+CMS configuration to work
  1347   // with YoungPLABSize and OldPLABSize options.
  1348   // See CR 6362902.
  1349   if (!FLAG_IS_DEFAULT(OldPLABSize)) {
  1350     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
  1351       // OldPLABSize is not the default value but CMSParPromoteBlocksToClaim
  1352       // is.  In this situtation let CMSParPromoteBlocksToClaim follow
  1353       // the value (either from the command line or ergonomics) of
  1354       // OldPLABSize.  Following OldPLABSize is an ergonomics decision.
  1355       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize);
  1356     } else {
  1357       // OldPLABSize and CMSParPromoteBlocksToClaim are both set.
  1358       // CMSParPromoteBlocksToClaim is a collector-specific flag, so
  1359       // we'll let it to take precedence.
  1360       jio_fprintf(defaultStream::error_stream(),
  1361                   "Both OldPLABSize and CMSParPromoteBlocksToClaim"
  1362                   " options are specified for the CMS collector."
  1363                   " CMSParPromoteBlocksToClaim will take precedence.\n");
  1366   if (!FLAG_IS_DEFAULT(ResizeOldPLAB) && !ResizeOldPLAB) {
  1367     // OldPLAB sizing manually turned off: Use a larger default setting,
  1368     // unless it was manually specified. This is because a too-low value
  1369     // will slow down scavenges.
  1370     if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) {
  1371       FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, 50); // default value before 6631166
  1374   // Overwrite OldPLABSize which is the variable we will internally use everywhere.
  1375   FLAG_SET_ERGO(uintx, OldPLABSize, CMSParPromoteBlocksToClaim);
  1376   // If either of the static initialization defaults have changed, note this
  1377   // modification.
  1378   if (!FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim) || !FLAG_IS_DEFAULT(OldPLABWeight)) {
  1379     CFLS_LAB::modify_initialization(OldPLABSize, OldPLABWeight);
  1382   if (PrintGCDetails && Verbose) {
  1383     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
  1384       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
  1385     tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
  1388 #endif // INCLUDE_ALL_GCS
  1390 void set_object_alignment() {
  1391   // Object alignment.
  1392   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
  1393   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
  1394   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
  1395   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
  1396   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
  1397   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
  1399   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
  1400   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
  1402   // Oop encoding heap max
  1403   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
  1405 #if INCLUDE_ALL_GCS
  1406   // Set CMS global values
  1407   CompactibleFreeListSpace::set_cms_values();
  1408 #endif // INCLUDE_ALL_GCS
  1411 bool verify_object_alignment() {
  1412   // Object alignment.
  1413   if (!is_power_of_2(ObjectAlignmentInBytes)) {
  1414     jio_fprintf(defaultStream::error_stream(),
  1415                 "error: ObjectAlignmentInBytes=%d must be power of 2\n",
  1416                 (int)ObjectAlignmentInBytes);
  1417     return false;
  1419   if ((int)ObjectAlignmentInBytes < BytesPerLong) {
  1420     jio_fprintf(defaultStream::error_stream(),
  1421                 "error: ObjectAlignmentInBytes=%d must be greater or equal %d\n",
  1422                 (int)ObjectAlignmentInBytes, BytesPerLong);
  1423     return false;
  1425   // It does not make sense to have big object alignment
  1426   // since a space lost due to alignment will be greater
  1427   // then a saved space from compressed oops.
  1428   if ((int)ObjectAlignmentInBytes > 256) {
  1429     jio_fprintf(defaultStream::error_stream(),
  1430                 "error: ObjectAlignmentInBytes=%d must not be greater than 256\n",
  1431                 (int)ObjectAlignmentInBytes);
  1432     return false;
  1434   // In case page size is very small.
  1435   if ((int)ObjectAlignmentInBytes >= os::vm_page_size()) {
  1436     jio_fprintf(defaultStream::error_stream(),
  1437                 "error: ObjectAlignmentInBytes=%d must be less than page size %d\n",
  1438                 (int)ObjectAlignmentInBytes, os::vm_page_size());
  1439     return false;
  1441   if(SurvivorAlignmentInBytes == 0) {
  1442     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
  1443   } else {
  1444     if (!is_power_of_2(SurvivorAlignmentInBytes)) {
  1445       jio_fprintf(defaultStream::error_stream(),
  1446             "error: SurvivorAlignmentInBytes=%d must be power of 2\n",
  1447             (int)SurvivorAlignmentInBytes);
  1448       return false;
  1450     if (SurvivorAlignmentInBytes < ObjectAlignmentInBytes) {
  1451       jio_fprintf(defaultStream::error_stream(),
  1452           "error: SurvivorAlignmentInBytes=%d must be greater than ObjectAlignmentInBytes=%d \n",
  1453           (int)SurvivorAlignmentInBytes, (int)ObjectAlignmentInBytes);
  1454       return false;
  1457   return true;
  1460 size_t Arguments::max_heap_for_compressed_oops() {
  1461   // Avoid sign flip.
  1462   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
  1463   // We need to fit both the NULL page and the heap into the memory budget, while
  1464   // keeping alignment constraints of the heap. To guarantee the latter, as the
  1465   // NULL page is located before the heap, we pad the NULL page to the conservative
  1466   // maximum alignment that the GC may ever impose upon the heap.
  1467   size_t displacement_due_to_null_page = align_size_up_(os::vm_page_size(),
  1468                                                         _conservative_max_heap_alignment);
  1470   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
  1471   NOT_LP64(ShouldNotReachHere(); return 0);
  1474 bool Arguments::should_auto_select_low_pause_collector() {
  1475   if (UseAutoGCSelectPolicy &&
  1476       !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
  1477       (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
  1478     if (PrintGCDetails) {
  1479       // Cannot use gclog_or_tty yet.
  1480       tty->print_cr("Automatic selection of the low pause collector"
  1481        " based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
  1483     return true;
  1485   return false;
  1488 void Arguments::set_use_compressed_oops() {
  1489 #ifndef ZERO
  1490 #ifdef _LP64
  1491   // MaxHeapSize is not set up properly at this point, but
  1492   // the only value that can override MaxHeapSize if we are
  1493   // to use UseCompressedOops is InitialHeapSize.
  1494   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
  1496   if (max_heap_size <= max_heap_for_compressed_oops()) {
  1497 #if !defined(COMPILER1) || defined(TIERED)
  1498     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
  1499       FLAG_SET_ERGO(bool, UseCompressedOops, true);
  1501 #endif
  1502 #ifdef _WIN64
  1503     if (UseLargePages && UseCompressedOops) {
  1504       // Cannot allocate guard pages for implicit checks in indexed addressing
  1505       // mode, when large pages are specified on windows.
  1506       // This flag could be switched ON if narrow oop base address is set to 0,
  1507       // see code in Universe::initialize_heap().
  1508       Universe::set_narrow_oop_use_implicit_null_checks(false);
  1510 #endif //  _WIN64
  1511   } else {
  1512     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
  1513       warning("Max heap size too large for Compressed Oops");
  1514       FLAG_SET_DEFAULT(UseCompressedOops, false);
  1515       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
  1518 #endif // _LP64
  1519 #endif // ZERO
  1523 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
  1524 // set_use_compressed_oops().
  1525 void Arguments::set_use_compressed_klass_ptrs() {
  1526 #ifndef ZERO
  1527 #ifdef _LP64
  1528   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
  1529   if (!UseCompressedOops) {
  1530     if (UseCompressedClassPointers) {
  1531       warning("UseCompressedClassPointers requires UseCompressedOops");
  1533     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
  1534   } else {
  1535     // Turn on UseCompressedClassPointers too
  1536     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
  1537       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
  1539     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
  1540     if (UseCompressedClassPointers) {
  1541       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
  1542         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
  1543         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
  1547 #endif // _LP64
  1548 #endif // !ZERO
  1551 void Arguments::set_conservative_max_heap_alignment() {
  1552   // The conservative maximum required alignment for the heap is the maximum of
  1553   // the alignments imposed by several sources: any requirements from the heap
  1554   // itself, the collector policy and the maximum page size we may run the VM
  1555   // with.
  1556   size_t heap_alignment = GenCollectedHeap::conservative_max_heap_alignment();
  1557 #if INCLUDE_ALL_GCS
  1558   if (UseParallelGC) {
  1559     heap_alignment = ParallelScavengeHeap::conservative_max_heap_alignment();
  1560   } else if (UseG1GC) {
  1561     heap_alignment = G1CollectedHeap::conservative_max_heap_alignment();
  1563 #endif // INCLUDE_ALL_GCS
  1564   _conservative_max_heap_alignment = MAX4(heap_alignment,
  1565                                           (size_t)os::vm_allocation_granularity(),
  1566                                           os::max_page_size(),
  1567                                           CollectorPolicy::compute_heap_alignment());
  1570 void Arguments::select_gc_ergonomically() {
  1571   if (os::is_server_class_machine()) {
  1572     if (should_auto_select_low_pause_collector()) {
  1573       FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true);
  1574     } else {
  1575       FLAG_SET_ERGO(bool, UseParallelGC, true);
  1580 void Arguments::select_gc() {
  1581   if (!gc_selected()) {
  1582     select_gc_ergonomically();
  1586 void Arguments::set_ergonomics_flags() {
  1587   select_gc();
  1589 #ifdef COMPILER2
  1590   // Shared spaces work fine with other GCs but causes bytecode rewriting
  1591   // to be disabled, which hurts interpreter performance and decreases
  1592   // server performance.  When -server is specified, keep the default off
  1593   // unless it is asked for.  Future work: either add bytecode rewriting
  1594   // at link time, or rewrite bytecodes in non-shared methods.
  1595   if (!DumpSharedSpaces && !RequireSharedSpaces &&
  1596       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
  1597     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
  1599 #endif
  1601   set_conservative_max_heap_alignment();
  1603 #ifndef ZERO
  1604 #ifdef _LP64
  1605   set_use_compressed_oops();
  1607   // set_use_compressed_klass_ptrs() must be called after calling
  1608   // set_use_compressed_oops().
  1609   set_use_compressed_klass_ptrs();
  1611   // Also checks that certain machines are slower with compressed oops
  1612   // in vm_version initialization code.
  1613 #endif // _LP64
  1614 #endif // !ZERO
  1617 void Arguments::set_parallel_gc_flags() {
  1618   assert(UseParallelGC || UseParallelOldGC, "Error");
  1619   // Enable ParallelOld unless it was explicitly disabled (cmd line or rc file).
  1620   if (FLAG_IS_DEFAULT(UseParallelOldGC)) {
  1621     FLAG_SET_DEFAULT(UseParallelOldGC, true);
  1623   FLAG_SET_DEFAULT(UseParallelGC, true);
  1625   // If no heap maximum was requested explicitly, use some reasonable fraction
  1626   // of the physical memory, up to a maximum of 1GB.
  1627   FLAG_SET_DEFAULT(ParallelGCThreads,
  1628                    Abstract_VM_Version::parallel_worker_threads());
  1629   if (ParallelGCThreads == 0) {
  1630     jio_fprintf(defaultStream::error_stream(),
  1631         "The Parallel GC can not be combined with -XX:ParallelGCThreads=0\n");
  1632     vm_exit(1);
  1635   if (UseAdaptiveSizePolicy) {
  1636     // We don't want to limit adaptive heap sizing's freedom to adjust the heap
  1637     // unless the user actually sets these flags.
  1638     if (FLAG_IS_DEFAULT(MinHeapFreeRatio)) {
  1639       FLAG_SET_DEFAULT(MinHeapFreeRatio, 0);
  1640       _min_heap_free_ratio = MinHeapFreeRatio;
  1642     if (FLAG_IS_DEFAULT(MaxHeapFreeRatio)) {
  1643       FLAG_SET_DEFAULT(MaxHeapFreeRatio, 100);
  1644       _max_heap_free_ratio = MaxHeapFreeRatio;
  1648   // If InitialSurvivorRatio or MinSurvivorRatio were not specified, but the
  1649   // SurvivorRatio has been set, reset their default values to SurvivorRatio +
  1650   // 2.  By doing this we make SurvivorRatio also work for Parallel Scavenger.
  1651   // See CR 6362902 for details.
  1652   if (!FLAG_IS_DEFAULT(SurvivorRatio)) {
  1653     if (FLAG_IS_DEFAULT(InitialSurvivorRatio)) {
  1654        FLAG_SET_DEFAULT(InitialSurvivorRatio, SurvivorRatio + 2);
  1656     if (FLAG_IS_DEFAULT(MinSurvivorRatio)) {
  1657       FLAG_SET_DEFAULT(MinSurvivorRatio, SurvivorRatio + 2);
  1661   if (UseParallelOldGC) {
  1662     // Par compact uses lower default values since they are treated as
  1663     // minimums.  These are different defaults because of the different
  1664     // interpretation and are not ergonomically set.
  1665     if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) {
  1666       FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1);
  1671 void Arguments::set_g1_gc_flags() {
  1672   assert(UseG1GC, "Error");
  1673 #ifdef COMPILER1
  1674   FastTLABRefill = false;
  1675 #endif
  1676   FLAG_SET_DEFAULT(ParallelGCThreads,
  1677                      Abstract_VM_Version::parallel_worker_threads());
  1678   if (ParallelGCThreads == 0) {
  1679     vm_exit_during_initialization("The flag -XX:+UseG1GC can not be combined with -XX:ParallelGCThreads=0", NULL);
  1682 #if INCLUDE_ALL_GCS
  1683   if (G1ConcRefinementThreads == 0) {
  1684     FLAG_SET_DEFAULT(G1ConcRefinementThreads, ParallelGCThreads);
  1686 #endif
  1688   // MarkStackSize will be set (if it hasn't been set by the user)
  1689   // when concurrent marking is initialized.
  1690   // Its value will be based upon the number of parallel marking threads.
  1691   // But we do set the maximum mark stack size here.
  1692   if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
  1693     FLAG_SET_DEFAULT(MarkStackSizeMax, 128 * TASKQUEUE_SIZE);
  1696   if (FLAG_IS_DEFAULT(GCTimeRatio) || GCTimeRatio == 0) {
  1697     // In G1, we want the default GC overhead goal to be higher than
  1698     // say in PS. So we set it here to 10%. Otherwise the heap might
  1699     // be expanded more aggressively than we would like it to. In
  1700     // fact, even 10% seems to not be high enough in some cases
  1701     // (especially small GC stress tests that the main thing they do
  1702     // is allocation). We might consider increase it further.
  1703     FLAG_SET_DEFAULT(GCTimeRatio, 9);
  1706   if (PrintGCDetails && Verbose) {
  1707     tty->print_cr("MarkStackSize: %uk  MarkStackSizeMax: %uk",
  1708       (unsigned int) (MarkStackSize / K), (uint) (MarkStackSizeMax / K));
  1709     tty->print_cr("ConcGCThreads: %u", (uint) ConcGCThreads);
  1713 #if !INCLUDE_ALL_GCS
  1714 #ifdef ASSERT
  1715 static bool verify_serial_gc_flags() {
  1716   return (UseSerialGC &&
  1717         !(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||
  1718           UseParallelGC || UseParallelOldGC));
  1720 #endif // ASSERT
  1721 #endif // INCLUDE_ALL_GCS
  1723 void Arguments::set_gc_specific_flags() {
  1724 #if INCLUDE_ALL_GCS
  1725   // Set per-collector flags
  1726   if (UseParallelGC || UseParallelOldGC) {
  1727     set_parallel_gc_flags();
  1728   } else if (UseConcMarkSweepGC) { // Should be done before ParNew check below
  1729     set_cms_and_parnew_gc_flags();
  1730   } else if (UseParNewGC) {  // Skipped if CMS is set above
  1731     set_parnew_gc_flags();
  1732   } else if (UseG1GC) {
  1733     set_g1_gc_flags();
  1735   check_deprecated_gcs();
  1736   check_deprecated_gc_flags();
  1737   if (AssumeMP && !UseSerialGC) {
  1738     if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
  1739       warning("If the number of processors is expected to increase from one, then"
  1740               " you should configure the number of parallel GC threads appropriately"
  1741               " using -XX:ParallelGCThreads=N");
  1744   if (MinHeapFreeRatio == 100) {
  1745     // Keeping the heap 100% free is hard ;-) so limit it to 99%.
  1746     FLAG_SET_ERGO(uintx, MinHeapFreeRatio, 99);
  1749   // If class unloading is disabled, also disable concurrent class unloading.
  1750   if (!ClassUnloading) {
  1751     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
  1752     FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
  1753     FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
  1755 #else // INCLUDE_ALL_GCS
  1756   assert(verify_serial_gc_flags(), "SerialGC unset");
  1757 #endif // INCLUDE_ALL_GCS
  1760 julong Arguments::limit_by_allocatable_memory(julong limit) {
  1761   julong max_allocatable;
  1762   julong result = limit;
  1763   if (os::has_allocatable_memory_limit(&max_allocatable)) {
  1764     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
  1766   return result;
  1769 void Arguments::set_heap_size() {
  1770   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
  1771     // Deprecated flag
  1772     FLAG_SET_CMDLINE(uintx, MaxRAMFraction, DefaultMaxRAMFraction);
  1775   julong phys_mem =
  1776     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
  1777                             : (julong)MaxRAM;
  1779   // Experimental support for CGroup memory limits
  1780   if (UseCGroupMemoryLimitForHeap) {
  1781     // This is a rough indicator that a CGroup limit may be in force
  1782     // for this process
  1783     const char* lim_file = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
  1784     FILE *fp = fopen(lim_file, "r");
  1785     if (fp != NULL) {
  1786       julong cgroup_max = 0;
  1787       int ret = fscanf(fp, JULONG_FORMAT, &cgroup_max);
  1788       if (ret == 1 && cgroup_max > 0) {
  1789         // If unlimited, cgroup_max will be a very large, but unspecified
  1790         // value, so use initial phys_mem as a limit
  1791         if (PrintGCDetails && Verbose) {
  1792           // Cannot use gclog_or_tty yet.
  1793           tty->print_cr("Setting phys_mem to the min of cgroup limit ("
  1794                         JULONG_FORMAT "MB) and initial phys_mem ("
  1795                         JULONG_FORMAT "MB)", cgroup_max/M, phys_mem/M);
  1797         phys_mem = MIN2(cgroup_max, phys_mem);
  1798       } else {
  1799         warning("Unable to read/parse cgroup memory limit from %s: %s",
  1800                 lim_file, errno != 0 ? strerror(errno) : "unknown error");
  1802       fclose(fp);
  1803     } else {
  1804       warning("Unable to open cgroup memory limit file %s (%s)", lim_file, strerror(errno));
  1808   // Convert Fraction to Precentage values
  1809   if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
  1810       !FLAG_IS_DEFAULT(MaxRAMFraction))
  1811     MaxRAMPercentage = 100.0 / MaxRAMFraction;
  1813    if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
  1814        !FLAG_IS_DEFAULT(MinRAMFraction))
  1815      MinRAMPercentage = 100.0 / MinRAMFraction;
  1817    if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
  1818        !FLAG_IS_DEFAULT(InitialRAMFraction))
  1819      InitialRAMPercentage = 100.0 / InitialRAMFraction;
  1821   // If the maximum heap size has not been set with -Xmx,
  1822   // then set it as fraction of the size of physical memory,
  1823   // respecting the maximum and minimum sizes of the heap.
  1824   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
  1825     julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
  1826     const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
  1827     if (reasonable_min < MaxHeapSize) {
  1828       // Small physical memory, so use a minimum fraction of it for the heap
  1829       reasonable_max = reasonable_min;
  1830     } else {
  1831       // Not-small physical memory, so require a heap at least
  1832       // as large as MaxHeapSize
  1833       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
  1836     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
  1837       // Limit the heap size to ErgoHeapSizeLimit
  1838       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
  1840     if (UseCompressedOops) {
  1841       // Limit the heap size to the maximum possible when using compressed oops
  1842       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
  1843       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
  1844         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
  1845         // but it should be not less than default MaxHeapSize.
  1846         max_coop_heap -= HeapBaseMinAddress;
  1848       reasonable_max = MIN2(reasonable_max, max_coop_heap);
  1850     reasonable_max = limit_by_allocatable_memory(reasonable_max);
  1852     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
  1853       // An initial heap size was specified on the command line,
  1854       // so be sure that the maximum size is consistent.  Done
  1855       // after call to limit_by_allocatable_memory because that
  1856       // method might reduce the allocation size.
  1857       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
  1860     if (PrintGCDetails && Verbose) {
  1861       // Cannot use gclog_or_tty yet.
  1862       tty->print_cr("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
  1864     FLAG_SET_ERGO(uintx, MaxHeapSize, (uintx)reasonable_max);
  1867   // If the minimum or initial heap_size have not been set or requested to be set
  1868   // ergonomically, set them accordingly.
  1869   if (InitialHeapSize == 0 || min_heap_size() == 0) {
  1870     julong reasonable_minimum = (julong)(OldSize + NewSize);
  1872     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
  1874     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
  1876     if (InitialHeapSize == 0) {
  1877       julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
  1879       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
  1880       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
  1882       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
  1884       if (PrintGCDetails && Verbose) {
  1885         // Cannot use gclog_or_tty yet.
  1886         tty->print_cr("  Initial heap size " SIZE_FORMAT, (uintx)reasonable_initial);
  1888       FLAG_SET_ERGO(uintx, InitialHeapSize, (uintx)reasonable_initial);
  1890     // If the minimum heap size has not been set (via -Xms),
  1891     // synchronize with InitialHeapSize to avoid errors with the default value.
  1892     if (min_heap_size() == 0) {
  1893       set_min_heap_size(MIN2((uintx)reasonable_minimum, InitialHeapSize));
  1894       if (PrintGCDetails && Verbose) {
  1895         // Cannot use gclog_or_tty yet.
  1896         tty->print_cr("  Minimum heap size " SIZE_FORMAT, min_heap_size());
  1902 // This option inspects the machine and attempts to set various
  1903 // parameters to be optimal for long-running, memory allocation
  1904 // intensive jobs.  It is intended for machines with large
  1905 // amounts of cpu and memory.
  1906 jint Arguments::set_aggressive_heap_flags() {
  1907   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
  1908   // VM, but we may not be able to represent the total physical memory
  1909   // available (like having 8gb of memory on a box but using a 32bit VM).
  1910   // Thus, we need to make sure we're using a julong for intermediate
  1911   // calculations.
  1912   julong initHeapSize;
  1913   julong total_memory = os::physical_memory();
  1915   if (total_memory < (julong) 256 * M) {
  1916     jio_fprintf(defaultStream::error_stream(),
  1917             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
  1918     vm_exit(1);
  1921   // The heap size is half of available memory, or (at most)
  1922   // all of possible memory less 160mb (leaving room for the OS
  1923   // when using ISM).  This is the maximum; because adaptive sizing
  1924   // is turned on below, the actual space used may be smaller.
  1926   initHeapSize = MIN2(total_memory / (julong) 2,
  1927                       total_memory - (julong) 160 * M);
  1929   initHeapSize = limit_by_allocatable_memory(initHeapSize);
  1931   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
  1932     FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
  1933     FLAG_SET_CMDLINE(uintx, InitialHeapSize, initHeapSize);
  1934     // Currently the minimum size and the initial heap sizes are the same.
  1935     set_min_heap_size(initHeapSize);
  1937   if (FLAG_IS_DEFAULT(NewSize)) {
  1938     // Make the young generation 3/8ths of the total heap.
  1939     FLAG_SET_CMDLINE(uintx, NewSize,
  1940             ((julong) MaxHeapSize / (julong) 8) * (julong) 3);
  1941     FLAG_SET_CMDLINE(uintx, MaxNewSize, NewSize);
  1944 #ifndef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
  1945   FLAG_SET_DEFAULT(UseLargePages, true);
  1946 #endif
  1948   // Increase some data structure sizes for efficiency
  1949   FLAG_SET_CMDLINE(uintx, BaseFootPrintEstimate, MaxHeapSize);
  1950   FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
  1951   FLAG_SET_CMDLINE(uintx, TLABSize, 256 * K);
  1953   // See the OldPLABSize comment below, but replace 'after promotion'
  1954   // with 'after copying'.  YoungPLABSize is the size of the survivor
  1955   // space per-gc-thread buffers.  The default is 4kw.
  1956   FLAG_SET_CMDLINE(uintx, YoungPLABSize, 256 * K);     // Note: this is in words
  1958   // OldPLABSize is the size of the buffers in the old gen that
  1959   // UseParallelGC uses to promote live data that doesn't fit in the
  1960   // survivor spaces.  At any given time, there's one for each gc thread.
  1961   // The default size is 1kw. These buffers are rarely used, since the
  1962   // survivor spaces are usually big enough.  For specjbb, however, there
  1963   // are occasions when there's lots of live data in the young gen
  1964   // and we end up promoting some of it.  We don't have a definite
  1965   // explanation for why bumping OldPLABSize helps, but the theory
  1966   // is that a bigger PLAB results in retaining something like the
  1967   // original allocation order after promotion, which improves mutator
  1968   // locality.  A minor effect may be that larger PLABs reduce the
  1969   // number of PLAB allocation events during gc.  The value of 8kw
  1970   // was arrived at by experimenting with specjbb.
  1971   FLAG_SET_CMDLINE(uintx, OldPLABSize, 8 * K);      // Note: this is in words
  1973   // Enable parallel GC and adaptive generation sizing
  1974   FLAG_SET_CMDLINE(bool, UseParallelGC, true);
  1976   // Encourage steady state memory management
  1977   FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100);
  1979   // This appears to improve mutator locality
  1980   FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
  1982   // Get around early Solaris scheduling bug
  1983   // (affinity vs other jobs on system)
  1984   // but disallow DR and offlining (5008695).
  1985   FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true);
  1987   return JNI_OK;
  1990 // This must be called after ergonomics because we want bytecode rewriting
  1991 // if the server compiler is used, or if UseSharedSpaces is disabled.
  1992 void Arguments::set_bytecode_flags() {
  1993   // Better not attempt to store into a read-only space.
  1994   if (UseSharedSpaces) {
  1995     FLAG_SET_DEFAULT(RewriteBytecodes, false);
  1996     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
  1999   if (!RewriteBytecodes) {
  2000     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
  2004 // Aggressive optimization flags  -XX:+AggressiveOpts
  2005 void Arguments::set_aggressive_opts_flags() {
  2006 #ifdef COMPILER2
  2007   if (AggressiveUnboxing) {
  2008     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
  2009       FLAG_SET_DEFAULT(EliminateAutoBox, true);
  2010     } else if (!EliminateAutoBox) {
  2011       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
  2012       AggressiveUnboxing = false;
  2014     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
  2015       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
  2016     } else if (!DoEscapeAnalysis) {
  2017       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
  2018       AggressiveUnboxing = false;
  2021   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
  2022     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
  2023       FLAG_SET_DEFAULT(EliminateAutoBox, true);
  2025     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
  2026       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
  2029     // Feed the cache size setting into the JDK
  2030     char buffer[1024];
  2031     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
  2032     add_property(buffer);
  2034   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
  2035     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
  2037 #endif
  2039   if (AggressiveOpts) {
  2040 // Sample flag setting code
  2041 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
  2042 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
  2043 //    }
  2047 //===========================================================================================================
  2048 // Parsing of java.compiler property
  2050 void Arguments::process_java_compiler_argument(char* arg) {
  2051   // For backwards compatibility, Djava.compiler=NONE or ""
  2052   // causes us to switch to -Xint mode UNLESS -Xdebug
  2053   // is also specified.
  2054   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
  2055     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
  2059 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
  2060   _sun_java_launcher = strdup(launcher);
  2061   if (strcmp("gamma", _sun_java_launcher) == 0) {
  2062     _created_by_gamma_launcher = true;
  2066 bool Arguments::created_by_java_launcher() {
  2067   assert(_sun_java_launcher != NULL, "property must have value");
  2068   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
  2071 bool Arguments::created_by_gamma_launcher() {
  2072   return _created_by_gamma_launcher;
  2075 //===========================================================================================================
  2076 // Parsing of main arguments
  2078 bool Arguments::verify_interval(uintx val, uintx min,
  2079                                 uintx max, const char* name) {
  2080   // Returns true iff value is in the inclusive interval [min..max]
  2081   // false, otherwise.
  2082   if (val >= min && val <= max) {
  2083     return true;
  2085   jio_fprintf(defaultStream::error_stream(),
  2086               "%s of " UINTX_FORMAT " is invalid; must be between " UINTX_FORMAT
  2087               " and " UINTX_FORMAT "\n",
  2088               name, val, min, max);
  2089   return false;
  2092 bool Arguments::verify_min_value(intx val, intx min, const char* name) {
  2093   // Returns true if given value is at least specified min threshold
  2094   // false, otherwise.
  2095   if (val >= min ) {
  2096       return true;
  2098   jio_fprintf(defaultStream::error_stream(),
  2099               "%s of " INTX_FORMAT " is invalid; must be at least " INTX_FORMAT "\n",
  2100               name, val, min);
  2101   return false;
  2104 bool Arguments::verify_percentage(uintx value, const char* name) {
  2105   if (is_percentage(value)) {
  2106     return true;
  2108   jio_fprintf(defaultStream::error_stream(),
  2109               "%s of " UINTX_FORMAT " is invalid; must be between 0 and 100\n",
  2110               name, value);
  2111   return false;
  2114 // check if do gclog rotation
  2115 // +UseGCLogFileRotation is a must,
  2116 // no gc log rotation when log file not supplied or
  2117 // NumberOfGCLogFiles is 0
  2118 void check_gclog_consistency() {
  2119   if (UseGCLogFileRotation) {
  2120     if ((Arguments::gc_log_filename() == NULL) || (NumberOfGCLogFiles == 0)) {
  2121       jio_fprintf(defaultStream::output_stream(),
  2122                   "To enable GC log rotation, use -Xloggc:<filename> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=<num_of_files>\n"
  2123                   "where num_of_file > 0\n"
  2124                   "GC log rotation is turned off\n");
  2125       UseGCLogFileRotation = false;
  2129   if (UseGCLogFileRotation && (GCLogFileSize != 0) && (GCLogFileSize < 8*K)) {
  2130     FLAG_SET_CMDLINE(uintx, GCLogFileSize, 8*K);
  2131     jio_fprintf(defaultStream::output_stream(),
  2132                 "GCLogFileSize changed to minimum 8K\n");
  2136 // This function is called for -Xloggc:<filename>, it can be used
  2137 // to check if a given file name(or string) conforms to the following
  2138 // specification:
  2139 // A valid string only contains "[A-Z][a-z][0-9].-_%[p|t]"
  2140 // %p and %t only allowed once. We only limit usage of filename not path
  2141 bool is_filename_valid(const char *file_name) {
  2142   const char* p = file_name;
  2143   char file_sep = os::file_separator()[0];
  2144   const char* cp;
  2145   // skip prefix path
  2146   for (cp = file_name; *cp != '\0'; cp++) {
  2147     if (*cp == '/' || *cp == file_sep) {
  2148       p = cp + 1;
  2152   int count_p = 0;
  2153   int count_t = 0;
  2154   while (*p != '\0') {
  2155     if ((*p >= '0' && *p <= '9') ||
  2156         (*p >= 'A' && *p <= 'Z') ||
  2157         (*p >= 'a' && *p <= 'z') ||
  2158          *p == '-'               ||
  2159          *p == '_'               ||
  2160          *p == '.') {
  2161        p++;
  2162        continue;
  2164     if (*p == '%') {
  2165       if(*(p + 1) == 'p') {
  2166         p += 2;
  2167         count_p ++;
  2168         continue;
  2170       if (*(p + 1) == 't') {
  2171         p += 2;
  2172         count_t ++;
  2173         continue;
  2176     return false;
  2178   return count_p < 2 && count_t < 2;
  2181 bool Arguments::verify_MinHeapFreeRatio(FormatBuffer<80>& err_msg, uintx min_heap_free_ratio) {
  2182   if (!is_percentage(min_heap_free_ratio)) {
  2183     err_msg.print("MinHeapFreeRatio must have a value between 0 and 100");
  2184     return false;
  2186   if (min_heap_free_ratio > MaxHeapFreeRatio) {
  2187     err_msg.print("MinHeapFreeRatio (" UINTX_FORMAT ") must be less than or "
  2188                   "equal to MaxHeapFreeRatio (" UINTX_FORMAT ")", min_heap_free_ratio,
  2189                   MaxHeapFreeRatio);
  2190     return false;
  2192   // This does not set the flag itself, but stores the value in a safe place for later usage.
  2193   _min_heap_free_ratio = min_heap_free_ratio;
  2194   return true;
  2197 bool Arguments::verify_MaxHeapFreeRatio(FormatBuffer<80>& err_msg, uintx max_heap_free_ratio) {
  2198   if (!is_percentage(max_heap_free_ratio)) {
  2199     err_msg.print("MaxHeapFreeRatio must have a value between 0 and 100");
  2200     return false;
  2202   if (max_heap_free_ratio < MinHeapFreeRatio) {
  2203     err_msg.print("MaxHeapFreeRatio (" UINTX_FORMAT ") must be greater than or "
  2204                   "equal to MinHeapFreeRatio (" UINTX_FORMAT ")", max_heap_free_ratio,
  2205                   MinHeapFreeRatio);
  2206     return false;
  2208   // This does not set the flag itself, but stores the value in a safe place for later usage.
  2209   _max_heap_free_ratio = max_heap_free_ratio;
  2210   return true;
  2213 // Check consistency of GC selection
  2214 bool Arguments::check_gc_consistency() {
  2215   check_gclog_consistency();
  2216   bool status = true;
  2217   // Ensure that the user has not selected conflicting sets
  2218   // of collectors. [Note: this check is merely a user convenience;
  2219   // collectors over-ride each other so that only a non-conflicting
  2220   // set is selected; however what the user gets is not what they
  2221   // may have expected from the combination they asked for. It's
  2222   // better to reduce user confusion by not allowing them to
  2223   // select conflicting combinations.
  2224   uint i = 0;
  2225   if (UseSerialGC)                       i++;
  2226   if (UseConcMarkSweepGC || UseParNewGC) i++;
  2227   if (UseParallelGC || UseParallelOldGC) i++;
  2228   if (UseG1GC)                           i++;
  2229   if (i > 1) {
  2230     jio_fprintf(defaultStream::error_stream(),
  2231                 "Conflicting collector combinations in option list; "
  2232                 "please refer to the release notes for the combinations "
  2233                 "allowed\n");
  2234     status = false;
  2236   return status;
  2239 void Arguments::check_deprecated_gcs() {
  2240   if (UseConcMarkSweepGC && !UseParNewGC) {
  2241     warning("Using the DefNew young collector with the CMS collector is deprecated "
  2242         "and will likely be removed in a future release");
  2245   if (UseParNewGC && !UseConcMarkSweepGC) {
  2246     // !UseConcMarkSweepGC means that we are using serial old gc. Unfortunately we don't
  2247     // set up UseSerialGC properly, so that can't be used in the check here.
  2248     warning("Using the ParNew young collector with the Serial old collector is deprecated "
  2249         "and will likely be removed in a future release");
  2252   if (CMSIncrementalMode) {
  2253     warning("Using incremental CMS is deprecated and will likely be removed in a future release");
  2257 void Arguments::check_deprecated_gc_flags() {
  2258   if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
  2259     warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
  2260             "and will likely be removed in future release");
  2262   if (FLAG_IS_CMDLINE(DefaultMaxRAMFraction)) {
  2263     warning("DefaultMaxRAMFraction is deprecated and will likely be removed in a future release. "
  2264         "Use MaxRAMFraction instead.");
  2266   if (FLAG_IS_CMDLINE(UseCMSCompactAtFullCollection)) {
  2267     warning("UseCMSCompactAtFullCollection is deprecated and will likely be removed in a future release.");
  2269   if (FLAG_IS_CMDLINE(CMSFullGCsBeforeCompaction)) {
  2270     warning("CMSFullGCsBeforeCompaction is deprecated and will likely be removed in a future release.");
  2272   if (FLAG_IS_CMDLINE(UseCMSCollectionPassing)) {
  2273     warning("UseCMSCollectionPassing is deprecated and will likely be removed in a future release.");
  2277 // Check stack pages settings
  2278 bool Arguments::check_stack_pages()
  2280   bool status = true;
  2281   status = status && verify_min_value(StackYellowPages, 1, "StackYellowPages");
  2282   status = status && verify_min_value(StackRedPages, 1, "StackRedPages");
  2283   // greater stack shadow pages can't generate instruction to bang stack
  2284   status = status && verify_interval(StackShadowPages, 1, 50, "StackShadowPages");
  2285   return status;
  2288 // Check the consistency of vm_init_args
  2289 bool Arguments::check_vm_args_consistency() {
  2290   // Method for adding checks for flag consistency.
  2291   // The intent is to warn the user of all possible conflicts,
  2292   // before returning an error.
  2293   // Note: Needs platform-dependent factoring.
  2294   bool status = true;
  2296   // Allow both -XX:-UseStackBanging and -XX:-UseBoundThreads in non-product
  2297   // builds so the cost of stack banging can be measured.
  2298 #if (defined(PRODUCT) && defined(SOLARIS))
  2299   if (!UseBoundThreads && !UseStackBanging) {
  2300     jio_fprintf(defaultStream::error_stream(),
  2301                 "-UseStackBanging conflicts with -UseBoundThreads\n");
  2303      status = false;
  2305 #endif
  2307   if (TLABRefillWasteFraction == 0) {
  2308     jio_fprintf(defaultStream::error_stream(),
  2309                 "TLABRefillWasteFraction should be a denominator, "
  2310                 "not " SIZE_FORMAT "\n",
  2311                 TLABRefillWasteFraction);
  2312     status = false;
  2315   status = status && verify_interval(AdaptiveSizePolicyWeight, 0, 100,
  2316                               "AdaptiveSizePolicyWeight");
  2317   status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance");
  2319   // Divide by bucket size to prevent a large size from causing rollover when
  2320   // calculating amount of memory needed to be allocated for the String table.
  2321   status = status && verify_interval(StringTableSize, minimumStringTableSize,
  2322     (max_uintx / StringTable::bucket_size()), "StringTable size");
  2324   status = status && verify_interval(SymbolTableSize, minimumSymbolTableSize,
  2325     (max_uintx / SymbolTable::bucket_size()), "SymbolTable size");
  2328     // Using "else if" below to avoid printing two error messages if min > max.
  2329     // This will also prevent us from reporting both min>100 and max>100 at the
  2330     // same time, but that is less annoying than printing two identical errors IMHO.
  2331     FormatBuffer<80> err_msg("%s","");
  2332     if (!verify_MinHeapFreeRatio(err_msg, MinHeapFreeRatio)) {
  2333       jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
  2334       status = false;
  2335     } else if (!verify_MaxHeapFreeRatio(err_msg, MaxHeapFreeRatio)) {
  2336       jio_fprintf(defaultStream::error_stream(), "%s\n", err_msg.buffer());
  2337       status = false;
  2341   // Min/MaxMetaspaceFreeRatio
  2342   status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");
  2343   status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");
  2345   if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {
  2346     jio_fprintf(defaultStream::error_stream(),
  2347                 "MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "
  2348                 "equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",
  2349                 FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",
  2350                 MinMetaspaceFreeRatio,
  2351                 FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",
  2352                 MaxMetaspaceFreeRatio);
  2353     status = false;
  2356   // Trying to keep 100% free is not practical
  2357   MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);
  2359   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
  2360     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
  2363   if (UseParallelOldGC && ParallelOldGCSplitALot) {
  2364     // Settings to encourage splitting.
  2365     if (!FLAG_IS_CMDLINE(NewRatio)) {
  2366       FLAG_SET_CMDLINE(uintx, NewRatio, 2);
  2368     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
  2369       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
  2373   status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit");
  2374   status = status && verify_percentage(GCTimeLimit, "GCTimeLimit");
  2375   if (GCTimeLimit == 100) {
  2376     // Turn off gc-overhead-limit-exceeded checks
  2377     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
  2380   status = status && check_gc_consistency();
  2381   status = status && check_stack_pages();
  2383   if (CMSIncrementalMode) {
  2384     if (!UseConcMarkSweepGC) {
  2385       jio_fprintf(defaultStream::error_stream(),
  2386                   "error:  invalid argument combination.\n"
  2387                   "The CMS collector (-XX:+UseConcMarkSweepGC) must be "
  2388                   "selected in order\nto use CMSIncrementalMode.\n");
  2389       status = false;
  2390     } else {
  2391       status = status && verify_percentage(CMSIncrementalDutyCycle,
  2392                                   "CMSIncrementalDutyCycle");
  2393       status = status && verify_percentage(CMSIncrementalDutyCycleMin,
  2394                                   "CMSIncrementalDutyCycleMin");
  2395       status = status && verify_percentage(CMSIncrementalSafetyFactor,
  2396                                   "CMSIncrementalSafetyFactor");
  2397       status = status && verify_percentage(CMSIncrementalOffset,
  2398                                   "CMSIncrementalOffset");
  2399       status = status && verify_percentage(CMSExpAvgFactor,
  2400                                   "CMSExpAvgFactor");
  2401       // If it was not set on the command line, set
  2402       // CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early.
  2403       if (CMSInitiatingOccupancyFraction < 0) {
  2404         FLAG_SET_DEFAULT(CMSInitiatingOccupancyFraction, 1);
  2409   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
  2410   // insists that we hold the requisite locks so that the iteration is
  2411   // MT-safe. For the verification at start-up and shut-down, we don't
  2412   // yet have a good way of acquiring and releasing these locks,
  2413   // which are not visible at the CollectedHeap level. We want to
  2414   // be able to acquire these locks and then do the iteration rather
  2415   // than just disable the lock verification. This will be fixed under
  2416   // bug 4788986.
  2417   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
  2418     if (VerifyDuringStartup) {
  2419       warning("Heap verification at start-up disabled "
  2420               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
  2421       VerifyDuringStartup = false; // Disable verification at start-up
  2424     if (VerifyBeforeExit) {
  2425       warning("Heap verification at shutdown disabled "
  2426               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
  2427       VerifyBeforeExit = false; // Disable verification at shutdown
  2431   // Note: only executed in non-PRODUCT mode
  2432   if (!UseAsyncConcMarkSweepGC &&
  2433       (ExplicitGCInvokesConcurrent ||
  2434        ExplicitGCInvokesConcurrentAndUnloadsClasses)) {
  2435     jio_fprintf(defaultStream::error_stream(),
  2436                 "error: +ExplicitGCInvokesConcurrent[AndUnloadsClasses] conflicts"
  2437                 " with -UseAsyncConcMarkSweepGC");
  2438     status = false;
  2441   status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");
  2443 #if INCLUDE_ALL_GCS
  2444   if (UseG1GC) {
  2445     status = status && verify_percentage(G1NewSizePercent, "G1NewSizePercent");
  2446     status = status && verify_percentage(G1MaxNewSizePercent, "G1MaxNewSizePercent");
  2447     status = status && verify_interval(G1NewSizePercent, 0, G1MaxNewSizePercent, "G1NewSizePercent");
  2449     status = status && verify_percentage(InitiatingHeapOccupancyPercent,
  2450                                          "InitiatingHeapOccupancyPercent");
  2451     status = status && verify_min_value(G1RefProcDrainInterval, 1,
  2452                                         "G1RefProcDrainInterval");
  2453     status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,
  2454                                         "G1ConcMarkStepDurationMillis");
  2455     status = status && verify_interval(G1ConcRSHotCardLimit, 0, max_jubyte,
  2456                                        "G1ConcRSHotCardLimit");
  2457     status = status && verify_interval(G1ConcRSLogCacheSize, 0, 27,
  2458                                        "G1ConcRSLogCacheSize");
  2459     status = status && verify_interval(StringDeduplicationAgeThreshold, 1, markOopDesc::max_age,
  2460                                        "StringDeduplicationAgeThreshold");
  2462   if (UseConcMarkSweepGC) {
  2463     status = status && verify_min_value(CMSOldPLABNumRefills, 1, "CMSOldPLABNumRefills");
  2464     status = status && verify_min_value(CMSOldPLABToleranceFactor, 1, "CMSOldPLABToleranceFactor");
  2465     status = status && verify_min_value(CMSOldPLABMax, 1, "CMSOldPLABMax");
  2466     status = status && verify_interval(CMSOldPLABMin, 1, CMSOldPLABMax, "CMSOldPLABMin");
  2468     status = status && verify_min_value(CMSYoungGenPerWorker, 1, "CMSYoungGenPerWorker");
  2470     status = status && verify_min_value(CMSSamplingGrain, 1, "CMSSamplingGrain");
  2471     status = status && verify_interval(CMS_SweepWeight, 0, 100, "CMS_SweepWeight");
  2472     status = status && verify_interval(CMS_FLSWeight, 0, 100, "CMS_FLSWeight");
  2474     status = status && verify_interval(FLSCoalescePolicy, 0, 4, "FLSCoalescePolicy");
  2476     status = status && verify_min_value(CMSRescanMultiple, 1, "CMSRescanMultiple");
  2477     status = status && verify_min_value(CMSConcMarkMultiple, 1, "CMSConcMarkMultiple");
  2479     status = status && verify_interval(CMSPrecleanIter, 0, 9, "CMSPrecleanIter");
  2480     status = status && verify_min_value(CMSPrecleanDenominator, 1, "CMSPrecleanDenominator");
  2481     status = status && verify_interval(CMSPrecleanNumerator, 0, CMSPrecleanDenominator - 1, "CMSPrecleanNumerator");
  2483     status = status && verify_percentage(CMSBootstrapOccupancy, "CMSBootstrapOccupancy");
  2485     status = status && verify_min_value(CMSPrecleanThreshold, 100, "CMSPrecleanThreshold");
  2487     status = status && verify_percentage(CMSScheduleRemarkEdenPenetration, "CMSScheduleRemarkEdenPenetration");
  2488     status = status && verify_min_value(CMSScheduleRemarkSamplingRatio, 1, "CMSScheduleRemarkSamplingRatio");
  2489     status = status && verify_min_value(CMSBitMapYieldQuantum, 1, "CMSBitMapYieldQuantum");
  2490     status = status && verify_percentage(CMSTriggerRatio, "CMSTriggerRatio");
  2491     status = status && verify_percentage(CMSIsTooFullPercentage, "CMSIsTooFullPercentage");
  2494   if (UseParallelGC || UseParallelOldGC) {
  2495     status = status && verify_interval(ParallelOldDeadWoodLimiterMean, 0, 100, "ParallelOldDeadWoodLimiterMean");
  2496     status = status && verify_interval(ParallelOldDeadWoodLimiterStdDev, 0, 100, "ParallelOldDeadWoodLimiterStdDev");
  2498     status = status && verify_percentage(YoungGenerationSizeIncrement, "YoungGenerationSizeIncrement");
  2499     status = status && verify_percentage(TenuredGenerationSizeIncrement, "TenuredGenerationSizeIncrement");
  2501     status = status && verify_min_value(YoungGenerationSizeSupplementDecay, 1, "YoungGenerationSizeSupplementDecay");
  2502     status = status && verify_min_value(TenuredGenerationSizeSupplementDecay, 1, "TenuredGenerationSizeSupplementDecay");
  2504     status = status && verify_min_value(ParGCCardsPerStrideChunk, 1, "ParGCCardsPerStrideChunk");
  2506     status = status && verify_min_value(ParallelOldGCSplitInterval, 0, "ParallelOldGCSplitInterval");
  2508 #endif // INCLUDE_ALL_GCS
  2510   status = status && verify_interval(RefDiscoveryPolicy,
  2511                                      ReferenceProcessor::DiscoveryPolicyMin,
  2512                                      ReferenceProcessor::DiscoveryPolicyMax,
  2513                                      "RefDiscoveryPolicy");
  2515   // Limit the lower bound of this flag to 1 as it is used in a division
  2516   // expression.
  2517   status = status && verify_interval(TLABWasteTargetPercent,
  2518                                      1, 100, "TLABWasteTargetPercent");
  2520   status = status && verify_object_alignment();
  2522   status = status && verify_interval(CompressedClassSpaceSize, 1*M, 3*G,
  2523                                       "CompressedClassSpaceSize");
  2525   status = status && verify_interval(MarkStackSizeMax,
  2526                                   1, (max_jint - 1), "MarkStackSizeMax");
  2527   status = status && verify_interval(NUMAChunkResizeWeight, 0, 100, "NUMAChunkResizeWeight");
  2529   status = status && verify_min_value(LogEventsBufferEntries, 1, "LogEventsBufferEntries");
  2531   status = status && verify_min_value(HeapSizePerGCThread, (uintx) os::vm_page_size(), "HeapSizePerGCThread");
  2533   status = status && verify_min_value(GCTaskTimeStampEntries, 1, "GCTaskTimeStampEntries");
  2535   status = status && verify_percentage(ParallelGCBufferWastePct, "ParallelGCBufferWastePct");
  2536   status = status && verify_interval(TargetPLABWastePct, 1, 100, "TargetPLABWastePct");
  2538   status = status && verify_min_value(ParGCStridesPerThread, 1, "ParGCStridesPerThread");
  2540   status = status && verify_min_value(MinRAMFraction, 1, "MinRAMFraction");
  2541   status = status && verify_min_value(InitialRAMFraction, 1, "InitialRAMFraction");
  2542   status = status && verify_min_value(MaxRAMFraction, 1, "MaxRAMFraction");
  2543   status = status && verify_min_value(DefaultMaxRAMFraction, 1, "DefaultMaxRAMFraction");
  2545   status = status && verify_interval(AdaptiveTimeWeight, 0, 100, "AdaptiveTimeWeight");
  2546   status = status && verify_min_value(AdaptiveSizeDecrementScaleFactor, 1, "AdaptiveSizeDecrementScaleFactor");
  2548   status = status && verify_interval(TLABAllocationWeight, 0, 100, "TLABAllocationWeight");
  2549   status = status && verify_min_value(MinTLABSize, 1, "MinTLABSize");
  2550   status = status && verify_min_value(TLABRefillWasteFraction, 1, "TLABRefillWasteFraction");
  2552   status = status && verify_percentage(YoungGenerationSizeSupplement, "YoungGenerationSizeSupplement");
  2553   status = status && verify_percentage(TenuredGenerationSizeSupplement, "TenuredGenerationSizeSupplement");
  2555   // the "age" field in the oop header is 4 bits; do not want to pull in markOop.hpp
  2556   // just for that, so hardcode here.
  2557   status = status && verify_interval(MaxTenuringThreshold, 0, 15, "MaxTenuringThreshold");
  2558   status = status && verify_interval(InitialTenuringThreshold, 0, MaxTenuringThreshold, "MaxTenuringThreshold");
  2559   status = status && verify_percentage(TargetSurvivorRatio, "TargetSurvivorRatio");
  2560   status = status && verify_percentage(MarkSweepDeadRatio, "MarkSweepDeadRatio");
  2562   status = status && verify_min_value(MarkSweepAlwaysCompactCount, 1, "MarkSweepAlwaysCompactCount");
  2563 #ifdef COMPILER1
  2564   status = status && verify_min_value(ValueMapInitialSize, 1, "ValueMapInitialSize");
  2565 #endif
  2567   if (PrintNMTStatistics) {
  2568 #if INCLUDE_NMT
  2569     if (MemTracker::tracking_level() == NMT_off) {
  2570 #endif // INCLUDE_NMT
  2571       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
  2572       PrintNMTStatistics = false;
  2573 #if INCLUDE_NMT
  2575 #endif
  2578   // Need to limit the extent of the padding to reasonable size.
  2579   // 8K is well beyond the reasonable HW cache line size, even with the
  2580   // aggressive prefetching, while still leaving the room for segregating
  2581   // among the distinct pages.
  2582   if (ContendedPaddingWidth < 0 || ContendedPaddingWidth > 8192) {
  2583     jio_fprintf(defaultStream::error_stream(),
  2584                 "ContendedPaddingWidth=" INTX_FORMAT " must be in between %d and %d\n",
  2585                 ContendedPaddingWidth, 0, 8192);
  2586     status = false;
  2589   // Need to enforce the padding not to break the existing field alignments.
  2590   // It is sufficient to check against the largest type size.
  2591   if ((ContendedPaddingWidth % BytesPerLong) != 0) {
  2592     jio_fprintf(defaultStream::error_stream(),
  2593                 "ContendedPaddingWidth=" INTX_FORMAT " must be a multiple of %d\n",
  2594                 ContendedPaddingWidth, BytesPerLong);
  2595     status = false;
  2598   // Check lower bounds of the code cache
  2599   // Template Interpreter code is approximately 3X larger in debug builds.
  2600   uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace;
  2601   if (InitialCodeCacheSize < (uintx)os::vm_page_size()) {
  2602     jio_fprintf(defaultStream::error_stream(),
  2603                 "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K,
  2604                 os::vm_page_size()/K);
  2605     status = false;
  2606   } else if (ReservedCodeCacheSize < InitialCodeCacheSize) {
  2607     jio_fprintf(defaultStream::error_stream(),
  2608                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
  2609                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
  2610     status = false;
  2611   } else if (ReservedCodeCacheSize < min_code_cache_size) {
  2612     jio_fprintf(defaultStream::error_stream(),
  2613                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
  2614                 min_code_cache_size/K);
  2615     status = false;
  2616   } else if (ReservedCodeCacheSize > 2*G) {
  2617     // Code cache size larger than MAXINT is not supported.
  2618     jio_fprintf(defaultStream::error_stream(),
  2619                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
  2620                 (2*G)/M);
  2621     status = false;
  2624   status &= verify_interval(NmethodSweepFraction, 1, ReservedCodeCacheSize/K, "NmethodSweepFraction");
  2625   status &= verify_interval(NmethodSweepActivity, 0, 2000, "NmethodSweepActivity");
  2627   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
  2628     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
  2631 #ifdef COMPILER1
  2632   status &= verify_interval(SafepointPollOffset, 0, os::vm_page_size() - BytesPerWord, "SafepointPollOffset");
  2633 #endif
  2635   int min_number_of_compiler_threads = get_min_number_of_compiler_threads();
  2636   // The default CICompilerCount's value is CI_COMPILER_COUNT.
  2637   assert(min_number_of_compiler_threads <= CI_COMPILER_COUNT, "minimum should be less or equal default number");
  2638   // Check the minimum number of compiler threads
  2639   status &=verify_min_value(CICompilerCount, min_number_of_compiler_threads, "CICompilerCount");
  2641   return status;
  2644 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
  2645   const char* option_type) {
  2646   if (ignore) return false;
  2648   const char* spacer = " ";
  2649   if (option_type == NULL) {
  2650     option_type = ++spacer; // Set both to the empty string.
  2653   if (os::obsolete_option(option)) {
  2654     jio_fprintf(defaultStream::error_stream(),
  2655                 "Obsolete %s%soption: %s\n", option_type, spacer,
  2656       option->optionString);
  2657     return false;
  2658   } else {
  2659     jio_fprintf(defaultStream::error_stream(),
  2660                 "Unrecognized %s%soption: %s\n", option_type, spacer,
  2661       option->optionString);
  2662     return true;
  2666 static const char* user_assertion_options[] = {
  2667   "-da", "-ea", "-disableassertions", "-enableassertions", 0
  2668 };
  2670 static const char* system_assertion_options[] = {
  2671   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
  2672 };
  2674 // Return true if any of the strings in null-terminated array 'names' matches.
  2675 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
  2676 // the option must match exactly.
  2677 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
  2678   bool tail_allowed) {
  2679   for (/* empty */; *names != NULL; ++names) {
  2680     if (match_option(option, *names, tail)) {
  2681       if (**tail == '\0' || tail_allowed && **tail == ':') {
  2682         return true;
  2686   return false;
  2689 bool Arguments::parse_uintx(const char* value,
  2690                             uintx* uintx_arg,
  2691                             uintx min_size) {
  2693   // Check the sign first since atomull() parses only unsigned values.
  2694   bool value_is_positive = !(*value == '-');
  2696   if (value_is_positive) {
  2697     julong n;
  2698     bool good_return = atomull(value, &n);
  2699     if (good_return) {
  2700       bool above_minimum = n >= min_size;
  2701       bool value_is_too_large = n > max_uintx;
  2703       if (above_minimum && !value_is_too_large) {
  2704         *uintx_arg = n;
  2705         return true;
  2709   return false;
  2712 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
  2713                                                   julong* long_arg,
  2714                                                   julong min_size) {
  2715   if (!atomull(s, long_arg)) return arg_unreadable;
  2716   return check_memory_size(*long_arg, min_size);
  2719 // Parse JavaVMInitArgs structure
  2721 jint Arguments::parse_vm_init_args(const JavaVMInitArgs* args) {
  2722   // For components of the system classpath.
  2723   SysClassPath scp(Arguments::get_sysclasspath());
  2724   bool scp_assembly_required = false;
  2726   // Save default settings for some mode flags
  2727   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
  2728   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
  2729   Arguments::_ClipInlining             = ClipInlining;
  2730   Arguments::_BackgroundCompilation    = BackgroundCompilation;
  2732   // Setup flags for mixed which is the default
  2733   set_mode_flags(_mixed);
  2735   // Parse JAVA_TOOL_OPTIONS environment variable (if present)
  2736   jint result = parse_java_tool_options_environment_variable(&scp, &scp_assembly_required);
  2737   if (result != JNI_OK) {
  2738     return result;
  2741   // Parse JavaVMInitArgs structure passed in
  2742   result = parse_each_vm_init_arg(args, &scp, &scp_assembly_required, Flag::COMMAND_LINE);
  2743   if (result != JNI_OK) {
  2744     return result;
  2747   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
  2748   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
  2749   if (result != JNI_OK) {
  2750     return result;
  2753   // We need to ensure processor and memory resources have been properly
  2754   // configured - which may rely on arguments we just processed - before
  2755   // doing the final argument processing. Any argument processing that
  2756   // needs to know about processor and memory resources must occur after
  2757   // this point.
  2759   os::init_container_support();
  2761   // Do final processing now that all arguments have been parsed
  2762   result = finalize_vm_init_args(&scp, scp_assembly_required);
  2763   if (result != JNI_OK) {
  2764     return result;
  2767   return JNI_OK;
  2770 // Checks if name in command-line argument -agent{lib,path}:name[=options]
  2771 // represents a valid HPROF of JDWP agent.  is_path==true denotes that we
  2772 // are dealing with -agentpath (case where name is a path), otherwise with
  2773 // -agentlib
  2774 bool valid_hprof_or_jdwp_agent(char *name, bool is_path) {
  2775   char *_name;
  2776   const char *_hprof = "hprof", *_jdwp = "jdwp";
  2777   size_t _len_hprof, _len_jdwp, _len_prefix;
  2779   if (is_path) {
  2780     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
  2781       return false;
  2784     _name++;  // skip past last path separator
  2785     _len_prefix = strlen(JNI_LIB_PREFIX);
  2787     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
  2788       return false;
  2791     _name += _len_prefix;
  2792     _len_hprof = strlen(_hprof);
  2793     _len_jdwp = strlen(_jdwp);
  2795     if (strncmp(_name, _hprof, _len_hprof) == 0) {
  2796       _name += _len_hprof;
  2798     else if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
  2799       _name += _len_jdwp;
  2801     else {
  2802       return false;
  2805     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
  2806       return false;
  2809     return true;
  2812   if (strcmp(name, _hprof) == 0 || strcmp(name, _jdwp) == 0) {
  2813     return true;
  2816   return false;
  2819 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args,
  2820                                        SysClassPath* scp_p,
  2821                                        bool* scp_assembly_required_p,
  2822                                        Flag::Flags origin) {
  2823   // Remaining part of option string
  2824   const char* tail;
  2826   // iterate over arguments
  2827   for (int index = 0; index < args->nOptions; index++) {
  2828     bool is_absolute_path = false;  // for -agentpath vs -agentlib
  2830     const JavaVMOption* option = args->options + index;
  2832     if (!match_option(option, "-Djava.class.path", &tail) &&
  2833         !match_option(option, "-Dsun.java.command", &tail) &&
  2834         !match_option(option, "-Dsun.java.launcher", &tail)) {
  2836         // add all jvm options to the jvm_args string. This string
  2837         // is used later to set the java.vm.args PerfData string constant.
  2838         // the -Djava.class.path and the -Dsun.java.command options are
  2839         // omitted from jvm_args string as each have their own PerfData
  2840         // string constant object.
  2841         build_jvm_args(option->optionString);
  2844     // -verbose:[class/gc/jni]
  2845     if (match_option(option, "-verbose", &tail)) {
  2846       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
  2847         FLAG_SET_CMDLINE(bool, TraceClassLoading, true);
  2848         FLAG_SET_CMDLINE(bool, TraceClassUnloading, true);
  2849       } else if (!strcmp(tail, ":gc")) {
  2850         FLAG_SET_CMDLINE(bool, PrintGC, true);
  2851       } else if (!strcmp(tail, ":jni")) {
  2852         FLAG_SET_CMDLINE(bool, PrintJNIResolving, true);
  2854     // -da / -ea / -disableassertions / -enableassertions
  2855     // These accept an optional class/package name separated by a colon, e.g.,
  2856     // -da:java.lang.Thread.
  2857     } else if (match_option(option, user_assertion_options, &tail, true)) {
  2858       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
  2859       if (*tail == '\0') {
  2860         JavaAssertions::setUserClassDefault(enable);
  2861       } else {
  2862         assert(*tail == ':', "bogus match by match_option()");
  2863         JavaAssertions::addOption(tail + 1, enable);
  2865     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
  2866     } else if (match_option(option, system_assertion_options, &tail, false)) {
  2867       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
  2868       JavaAssertions::setSystemClassDefault(enable);
  2869     // -bootclasspath:
  2870     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
  2871       scp_p->reset_path(tail);
  2872       *scp_assembly_required_p = true;
  2873     // -bootclasspath/a:
  2874     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
  2875       scp_p->add_suffix(tail);
  2876       *scp_assembly_required_p = true;
  2877     // -bootclasspath/p:
  2878     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
  2879       scp_p->add_prefix(tail);
  2880       *scp_assembly_required_p = true;
  2881     // -Xrun
  2882     } else if (match_option(option, "-Xrun", &tail)) {
  2883       if (tail != NULL) {
  2884         const char* pos = strchr(tail, ':');
  2885         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
  2886         char* name = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
  2887         name[len] = '\0';
  2889         char *options = NULL;
  2890         if(pos != NULL) {
  2891           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
  2892           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtInternal), pos+1, len2);
  2894 #if !INCLUDE_JVMTI
  2895         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
  2896           jio_fprintf(defaultStream::error_stream(),
  2897             "Profiling and debugging agents are not supported in this VM\n");
  2898           return JNI_ERR;
  2900 #endif // !INCLUDE_JVMTI
  2901         add_init_library(name, options);
  2903     // -agentlib and -agentpath
  2904     } else if (match_option(option, "-agentlib:", &tail) ||
  2905           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
  2906       if(tail != NULL) {
  2907         const char* pos = strchr(tail, '=');
  2908         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
  2909         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtInternal), tail, len);
  2910         name[len] = '\0';
  2912         char *options = NULL;
  2913         if(pos != NULL) {
  2914           size_t length = strlen(pos + 1) + 1;
  2915           options = NEW_C_HEAP_ARRAY(char, length, mtInternal);
  2916           jio_snprintf(options, length, "%s", pos + 1);
  2918 #if !INCLUDE_JVMTI
  2919         if (valid_hprof_or_jdwp_agent(name, is_absolute_path)) {
  2920           jio_fprintf(defaultStream::error_stream(),
  2921             "Profiling and debugging agents are not supported in this VM\n");
  2922           return JNI_ERR;
  2924 #endif // !INCLUDE_JVMTI
  2925         add_init_agent(name, options, is_absolute_path);
  2927     // -javaagent
  2928     } else if (match_option(option, "-javaagent:", &tail)) {
  2929 #if !INCLUDE_JVMTI
  2930       jio_fprintf(defaultStream::error_stream(),
  2931         "Instrumentation agents are not supported in this VM\n");
  2932       return JNI_ERR;
  2933 #else
  2934       if(tail != NULL) {
  2935         size_t length = strlen(tail) + 1;
  2936         char *options = NEW_C_HEAP_ARRAY(char, length, mtInternal);
  2937         jio_snprintf(options, length, "%s", tail);
  2938         add_init_agent("instrument", options, false);
  2940 #endif // !INCLUDE_JVMTI
  2941     // -Xnoclassgc
  2942     } else if (match_option(option, "-Xnoclassgc", &tail)) {
  2943       FLAG_SET_CMDLINE(bool, ClassUnloading, false);
  2944     // -Xincgc: i-CMS
  2945     } else if (match_option(option, "-Xincgc", &tail)) {
  2946       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
  2947       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, true);
  2948     // -Xnoincgc: no i-CMS
  2949     } else if (match_option(option, "-Xnoincgc", &tail)) {
  2950       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
  2951       FLAG_SET_CMDLINE(bool, CMSIncrementalMode, false);
  2952     // -Xconcgc
  2953     } else if (match_option(option, "-Xconcgc", &tail)) {
  2954       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true);
  2955     // -Xnoconcgc
  2956     } else if (match_option(option, "-Xnoconcgc", &tail)) {
  2957       FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false);
  2958     // -Xbatch
  2959     } else if (match_option(option, "-Xbatch", &tail)) {
  2960       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
  2961     // -Xmn for compatibility with other JVM vendors
  2962     } else if (match_option(option, "-Xmn", &tail)) {
  2963       julong long_initial_young_size = 0;
  2964       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
  2965       if (errcode != arg_in_range) {
  2966         jio_fprintf(defaultStream::error_stream(),
  2967                     "Invalid initial young generation size: %s\n", option->optionString);
  2968         describe_range_error(errcode);
  2969         return JNI_EINVAL;
  2971       FLAG_SET_CMDLINE(uintx, MaxNewSize, (uintx)long_initial_young_size);
  2972       FLAG_SET_CMDLINE(uintx, NewSize, (uintx)long_initial_young_size);
  2973     // -Xms
  2974     } else if (match_option(option, "-Xms", &tail)) {
  2975       julong long_initial_heap_size = 0;
  2976       // an initial heap size of 0 means automatically determine
  2977       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
  2978       if (errcode != arg_in_range) {
  2979         jio_fprintf(defaultStream::error_stream(),
  2980                     "Invalid initial heap size: %s\n", option->optionString);
  2981         describe_range_error(errcode);
  2982         return JNI_EINVAL;
  2984       set_min_heap_size((uintx)long_initial_heap_size);
  2985       // Currently the minimum size and the initial heap sizes are the same.
  2986       // Can be overridden with -XX:InitialHeapSize.
  2987       FLAG_SET_CMDLINE(uintx, InitialHeapSize, (uintx)long_initial_heap_size);
  2988     // -Xmx
  2989     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
  2990       julong long_max_heap_size = 0;
  2991       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
  2992       if (errcode != arg_in_range) {
  2993         jio_fprintf(defaultStream::error_stream(),
  2994                     "Invalid maximum heap size: %s\n", option->optionString);
  2995         describe_range_error(errcode);
  2996         return JNI_EINVAL;
  2998       FLAG_SET_CMDLINE(uintx, MaxHeapSize, (uintx)long_max_heap_size);
  2999     // Xmaxf
  3000     } else if (match_option(option, "-Xmaxf", &tail)) {
  3001       char* err;
  3002       int maxf = (int)(strtod(tail, &err) * 100);
  3003       if (*err != '\0' || *tail == '\0' || maxf < 0 || maxf > 100) {
  3004         jio_fprintf(defaultStream::error_stream(),
  3005                     "Bad max heap free percentage size: %s\n",
  3006                     option->optionString);
  3007         return JNI_EINVAL;
  3008       } else {
  3009         FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf);
  3011     // Xminf
  3012     } else if (match_option(option, "-Xminf", &tail)) {
  3013       char* err;
  3014       int minf = (int)(strtod(tail, &err) * 100);
  3015       if (*err != '\0' || *tail == '\0' || minf < 0 || minf > 100) {
  3016         jio_fprintf(defaultStream::error_stream(),
  3017                     "Bad min heap free percentage size: %s\n",
  3018                     option->optionString);
  3019         return JNI_EINVAL;
  3020       } else {
  3021         FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf);
  3023     // -Xss
  3024     } else if (match_option(option, "-Xss", &tail)) {
  3025       julong long_ThreadStackSize = 0;
  3026       ArgsRange errcode = parse_memory_size(tail, &long_ThreadStackSize, 1000);
  3027       if (errcode != arg_in_range) {
  3028         jio_fprintf(defaultStream::error_stream(),
  3029                     "Invalid thread stack size: %s\n", option->optionString);
  3030         describe_range_error(errcode);
  3031         return JNI_EINVAL;
  3033       // Internally track ThreadStackSize in units of 1024 bytes.
  3034       FLAG_SET_CMDLINE(intx, ThreadStackSize,
  3035                               round_to((int)long_ThreadStackSize, K) / K);
  3036     // -Xoss
  3037     } else if (match_option(option, "-Xoss", &tail)) {
  3038           // HotSpot does not have separate native and Java stacks, ignore silently for compatibility
  3039     } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) {
  3040       julong long_CodeCacheExpansionSize = 0;
  3041       ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size());
  3042       if (errcode != arg_in_range) {
  3043         jio_fprintf(defaultStream::error_stream(),
  3044                    "Invalid argument: %s. Must be at least %luK.\n", option->optionString,
  3045                    os::vm_page_size()/K);
  3046         return JNI_EINVAL;
  3048       FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize);
  3049     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
  3050                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
  3051       julong long_ReservedCodeCacheSize = 0;
  3053       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
  3054       if (errcode != arg_in_range) {
  3055         jio_fprintf(defaultStream::error_stream(),
  3056                     "Invalid maximum code cache size: %s.\n", option->optionString);
  3057         return JNI_EINVAL;
  3059       FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize);
  3060       //-XX:IncreaseFirstTierCompileThresholdAt=
  3061       } else if (match_option(option, "-XX:IncreaseFirstTierCompileThresholdAt=", &tail)) {
  3062         uintx uint_IncreaseFirstTierCompileThresholdAt = 0;
  3063         if (!parse_uintx(tail, &uint_IncreaseFirstTierCompileThresholdAt, 0) || uint_IncreaseFirstTierCompileThresholdAt > 99) {
  3064           jio_fprintf(defaultStream::error_stream(),
  3065                       "Invalid value for IncreaseFirstTierCompileThresholdAt: %s. Should be between 0 and 99.\n",
  3066                       option->optionString);
  3067           return JNI_EINVAL;
  3069         FLAG_SET_CMDLINE(uintx, IncreaseFirstTierCompileThresholdAt, (uintx)uint_IncreaseFirstTierCompileThresholdAt);
  3070     // -green
  3071     } else if (match_option(option, "-green", &tail)) {
  3072       jio_fprintf(defaultStream::error_stream(),
  3073                   "Green threads support not available\n");
  3074           return JNI_EINVAL;
  3075     // -native
  3076     } else if (match_option(option, "-native", &tail)) {
  3077           // HotSpot always uses native threads, ignore silently for compatibility
  3078     // -Xsqnopause
  3079     } else if (match_option(option, "-Xsqnopause", &tail)) {
  3080           // EVM option, ignore silently for compatibility
  3081     // -Xrs
  3082     } else if (match_option(option, "-Xrs", &tail)) {
  3083           // Classic/EVM option, new functionality
  3084       FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true);
  3085     } else if (match_option(option, "-Xusealtsigs", &tail)) {
  3086           // change default internal VM signals used - lower case for back compat
  3087       FLAG_SET_CMDLINE(bool, UseAltSigs, true);
  3088     // -Xoptimize
  3089     } else if (match_option(option, "-Xoptimize", &tail)) {
  3090           // EVM option, ignore silently for compatibility
  3091     // -Xprof
  3092     } else if (match_option(option, "-Xprof", &tail)) {
  3093 #if INCLUDE_FPROF
  3094       _has_profile = true;
  3095 #else // INCLUDE_FPROF
  3096       jio_fprintf(defaultStream::error_stream(),
  3097         "Flat profiling is not supported in this VM.\n");
  3098       return JNI_ERR;
  3099 #endif // INCLUDE_FPROF
  3100     // -Xconcurrentio
  3101     } else if (match_option(option, "-Xconcurrentio", &tail)) {
  3102       FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true);
  3103       FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
  3104       FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1);
  3105       FLAG_SET_CMDLINE(bool, UseTLAB, false);
  3106       FLAG_SET_CMDLINE(uintx, NewSizeThreadIncrease, 16 * K);  // 20Kb per thread added to new generation
  3108       // -Xinternalversion
  3109     } else if (match_option(option, "-Xinternalversion", &tail)) {
  3110       jio_fprintf(defaultStream::output_stream(), "%s\n",
  3111                   VM_Version::internal_vm_info_string());
  3112       vm_exit(0);
  3113 #ifndef PRODUCT
  3114     // -Xprintflags
  3115     } else if (match_option(option, "-Xprintflags", &tail)) {
  3116       CommandLineFlags::printFlags(tty, false);
  3117       vm_exit(0);
  3118 #endif
  3119     // -D
  3120     } else if (match_option(option, "-D", &tail)) {
  3121       if (CheckEndorsedAndExtDirs) {
  3122         if (match_option(option, "-Djava.endorsed.dirs=", &tail)) {
  3123           // abort if -Djava.endorsed.dirs is set
  3124           jio_fprintf(defaultStream::output_stream(),
  3125             "-Djava.endorsed.dirs will not be supported in a future release.\n"
  3126             "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
  3127           return JNI_EINVAL;
  3129         if (match_option(option, "-Djava.ext.dirs=", &tail)) {
  3130           // abort if -Djava.ext.dirs is set
  3131           jio_fprintf(defaultStream::output_stream(),
  3132             "-Djava.ext.dirs will not be supported in a future release.\n"
  3133             "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
  3134           return JNI_EINVAL;
  3138       if (!add_property(tail)) {
  3139         return JNI_ENOMEM;
  3141       // Out of the box management support
  3142       if (match_option(option, "-Dcom.sun.management", &tail)) {
  3143 #if INCLUDE_MANAGEMENT
  3144         FLAG_SET_CMDLINE(bool, ManagementServer, true);
  3145 #else
  3146         jio_fprintf(defaultStream::output_stream(),
  3147           "-Dcom.sun.management is not supported in this VM.\n");
  3148         return JNI_ERR;
  3149 #endif
  3151     // -Xint
  3152     } else if (match_option(option, "-Xint", &tail)) {
  3153           set_mode_flags(_int);
  3154     // -Xmixed
  3155     } else if (match_option(option, "-Xmixed", &tail)) {
  3156           set_mode_flags(_mixed);
  3157     // -Xcomp
  3158     } else if (match_option(option, "-Xcomp", &tail)) {
  3159       // for testing the compiler; turn off all flags that inhibit compilation
  3160           set_mode_flags(_comp);
  3161     // -Xshare:dump
  3162     } else if (match_option(option, "-Xshare:dump", &tail)) {
  3163       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
  3164       set_mode_flags(_int);     // Prevent compilation, which creates objects
  3165     // -Xshare:on
  3166     } else if (match_option(option, "-Xshare:on", &tail)) {
  3167       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
  3168       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
  3169     // -Xshare:auto
  3170     } else if (match_option(option, "-Xshare:auto", &tail)) {
  3171       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
  3172       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
  3173     // -Xshare:off
  3174     } else if (match_option(option, "-Xshare:off", &tail)) {
  3175       FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
  3176       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
  3177     // -Xverify
  3178     } else if (match_option(option, "-Xverify", &tail)) {
  3179       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
  3180         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true);
  3181         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
  3182       } else if (strcmp(tail, ":remote") == 0) {
  3183         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
  3184         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true);
  3185       } else if (strcmp(tail, ":none") == 0) {
  3186         FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false);
  3187         FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false);
  3188       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
  3189         return JNI_EINVAL;
  3191     // -Xdebug
  3192     } else if (match_option(option, "-Xdebug", &tail)) {
  3193       // note this flag has been used, then ignore
  3194       set_xdebug_mode(true);
  3195     // -Xnoagent
  3196     } else if (match_option(option, "-Xnoagent", &tail)) {
  3197       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
  3198     } else if (match_option(option, "-Xboundthreads", &tail)) {
  3199       // Bind user level threads to kernel threads (Solaris only)
  3200       FLAG_SET_CMDLINE(bool, UseBoundThreads, true);
  3201     } else if (match_option(option, "-Xloggc:", &tail)) {
  3202       // Redirect GC output to the file. -Xloggc:<filename>
  3203       // ostream_init_log(), when called will use this filename
  3204       // to initialize a fileStream.
  3205       _gc_log_filename = strdup(tail);
  3206      if (!is_filename_valid(_gc_log_filename)) {
  3207        jio_fprintf(defaultStream::output_stream(),
  3208                   "Invalid file name for use with -Xloggc: Filename can only contain the "
  3209                   "characters [A-Z][a-z][0-9]-_.%%[p|t] but it has been %s\n"
  3210                   "Note %%p or %%t can only be used once\n", _gc_log_filename);
  3211         return JNI_EINVAL;
  3213       FLAG_SET_CMDLINE(bool, PrintGC, true);
  3214       FLAG_SET_CMDLINE(bool, PrintGCTimeStamps, true);
  3216     // JNI hooks
  3217     } else if (match_option(option, "-Xcheck", &tail)) {
  3218       if (!strcmp(tail, ":jni")) {
  3219 #if !INCLUDE_JNI_CHECK
  3220         warning("JNI CHECKING is not supported in this VM");
  3221 #else
  3222         CheckJNICalls = true;
  3223 #endif // INCLUDE_JNI_CHECK
  3224       } else if (is_bad_option(option, args->ignoreUnrecognized,
  3225                                      "check")) {
  3226         return JNI_EINVAL;
  3228     } else if (match_option(option, "vfprintf", &tail)) {
  3229       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
  3230     } else if (match_option(option, "exit", &tail)) {
  3231       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
  3232     } else if (match_option(option, "abort", &tail)) {
  3233       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
  3234     } else if (match_option(option, "-XX:+NeverTenure", &tail)) {
  3235       // The last option must always win.
  3236       FLAG_SET_CMDLINE(bool, AlwaysTenure, false);
  3237       FLAG_SET_CMDLINE(bool, NeverTenure, true);
  3238     } else if (match_option(option, "-XX:+AlwaysTenure", &tail)) {
  3239       // The last option must always win.
  3240       FLAG_SET_CMDLINE(bool, NeverTenure, false);
  3241       FLAG_SET_CMDLINE(bool, AlwaysTenure, true);
  3242     } else if (match_option(option, "-XX:+CMSPermGenSweepingEnabled", &tail) ||
  3243                match_option(option, "-XX:-CMSPermGenSweepingEnabled", &tail)) {
  3244       jio_fprintf(defaultStream::error_stream(),
  3245         "Please use CMSClassUnloadingEnabled in place of "
  3246         "CMSPermGenSweepingEnabled in the future\n");
  3247     } else if (match_option(option, "-XX:+UseGCTimeLimit", &tail)) {
  3248       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, true);
  3249       jio_fprintf(defaultStream::error_stream(),
  3250         "Please use -XX:+UseGCOverheadLimit in place of "
  3251         "-XX:+UseGCTimeLimit in the future\n");
  3252     } else if (match_option(option, "-XX:-UseGCTimeLimit", &tail)) {
  3253       FLAG_SET_CMDLINE(bool, UseGCOverheadLimit, false);
  3254       jio_fprintf(defaultStream::error_stream(),
  3255         "Please use -XX:-UseGCOverheadLimit in place of "
  3256         "-XX:-UseGCTimeLimit in the future\n");
  3257     // The TLE options are for compatibility with 1.3 and will be
  3258     // removed without notice in a future release.  These options
  3259     // are not to be documented.
  3260     } else if (match_option(option, "-XX:MaxTLERatio=", &tail)) {
  3261       // No longer used.
  3262     } else if (match_option(option, "-XX:+ResizeTLE", &tail)) {
  3263       FLAG_SET_CMDLINE(bool, ResizeTLAB, true);
  3264     } else if (match_option(option, "-XX:-ResizeTLE", &tail)) {
  3265       FLAG_SET_CMDLINE(bool, ResizeTLAB, false);
  3266     } else if (match_option(option, "-XX:+PrintTLE", &tail)) {
  3267       FLAG_SET_CMDLINE(bool, PrintTLAB, true);
  3268     } else if (match_option(option, "-XX:-PrintTLE", &tail)) {
  3269       FLAG_SET_CMDLINE(bool, PrintTLAB, false);
  3270     } else if (match_option(option, "-XX:TLEFragmentationRatio=", &tail)) {
  3271       // No longer used.
  3272     } else if (match_option(option, "-XX:TLESize=", &tail)) {
  3273       julong long_tlab_size = 0;
  3274       ArgsRange errcode = parse_memory_size(tail, &long_tlab_size, 1);
  3275       if (errcode != arg_in_range) {
  3276         jio_fprintf(defaultStream::error_stream(),
  3277                     "Invalid TLAB size: %s\n", option->optionString);
  3278         describe_range_error(errcode);
  3279         return JNI_EINVAL;
  3281       FLAG_SET_CMDLINE(uintx, TLABSize, long_tlab_size);
  3282     } else if (match_option(option, "-XX:TLEThreadRatio=", &tail)) {
  3283       // No longer used.
  3284     } else if (match_option(option, "-XX:+UseTLE", &tail)) {
  3285       FLAG_SET_CMDLINE(bool, UseTLAB, true);
  3286     } else if (match_option(option, "-XX:-UseTLE", &tail)) {
  3287       FLAG_SET_CMDLINE(bool, UseTLAB, false);
  3288     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) {
  3289       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false);
  3290       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true);
  3291     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout", &tail)) {
  3292       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false);
  3293       FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true);
  3294     } else if (match_option(option, "-XX:+ExtendedDTraceProbes", &tail)) {
  3295 #if defined(DTRACE_ENABLED)
  3296       FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true);
  3297       FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true);
  3298       FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true);
  3299       FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true);
  3300 #else // defined(DTRACE_ENABLED)
  3301       jio_fprintf(defaultStream::error_stream(),
  3302                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
  3303       return JNI_EINVAL;
  3304 #endif // defined(DTRACE_ENABLED)
  3305 #ifdef ASSERT
  3306     } else if (match_option(option, "-XX:+FullGCALot", &tail)) {
  3307       FLAG_SET_CMDLINE(bool, FullGCALot, true);
  3308       // disable scavenge before parallel mark-compact
  3309       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
  3310 #endif
  3311     } else if (match_option(option, "-XX:CMSParPromoteBlocksToClaim=", &tail)) {
  3312       julong cms_blocks_to_claim = (julong)atol(tail);
  3313       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
  3314       jio_fprintf(defaultStream::error_stream(),
  3315         "Please use -XX:OldPLABSize in place of "
  3316         "-XX:CMSParPromoteBlocksToClaim in the future\n");
  3317     } else if (match_option(option, "-XX:ParCMSPromoteBlocksToClaim=", &tail)) {
  3318       julong cms_blocks_to_claim = (julong)atol(tail);
  3319       FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, cms_blocks_to_claim);
  3320       jio_fprintf(defaultStream::error_stream(),
  3321         "Please use -XX:OldPLABSize in place of "
  3322         "-XX:ParCMSPromoteBlocksToClaim in the future\n");
  3323     } else if (match_option(option, "-XX:ParallelGCOldGenAllocBufferSize=", &tail)) {
  3324       julong old_plab_size = 0;
  3325       ArgsRange errcode = parse_memory_size(tail, &old_plab_size, 1);
  3326       if (errcode != arg_in_range) {
  3327         jio_fprintf(defaultStream::error_stream(),
  3328                     "Invalid old PLAB size: %s\n", option->optionString);
  3329         describe_range_error(errcode);
  3330         return JNI_EINVAL;
  3332       FLAG_SET_CMDLINE(uintx, OldPLABSize, old_plab_size);
  3333       jio_fprintf(defaultStream::error_stream(),
  3334                   "Please use -XX:OldPLABSize in place of "
  3335                   "-XX:ParallelGCOldGenAllocBufferSize in the future\n");
  3336     } else if (match_option(option, "-XX:ParallelGCToSpaceAllocBufferSize=", &tail)) {
  3337       julong young_plab_size = 0;
  3338       ArgsRange errcode = parse_memory_size(tail, &young_plab_size, 1);
  3339       if (errcode != arg_in_range) {
  3340         jio_fprintf(defaultStream::error_stream(),
  3341                     "Invalid young PLAB size: %s\n", option->optionString);
  3342         describe_range_error(errcode);
  3343         return JNI_EINVAL;
  3345       FLAG_SET_CMDLINE(uintx, YoungPLABSize, young_plab_size);
  3346       jio_fprintf(defaultStream::error_stream(),
  3347                   "Please use -XX:YoungPLABSize in place of "
  3348                   "-XX:ParallelGCToSpaceAllocBufferSize in the future\n");
  3349     } else if (match_option(option, "-XX:CMSMarkStackSize=", &tail) ||
  3350                match_option(option, "-XX:G1MarkStackSize=", &tail)) {
  3351       julong stack_size = 0;
  3352       ArgsRange errcode = parse_memory_size(tail, &stack_size, 1);
  3353       if (errcode != arg_in_range) {
  3354         jio_fprintf(defaultStream::error_stream(),
  3355                     "Invalid mark stack size: %s\n", option->optionString);
  3356         describe_range_error(errcode);
  3357         return JNI_EINVAL;
  3359       FLAG_SET_CMDLINE(uintx, MarkStackSize, stack_size);
  3360     } else if (match_option(option, "-XX:CMSMarkStackSizeMax=", &tail)) {
  3361       julong max_stack_size = 0;
  3362       ArgsRange errcode = parse_memory_size(tail, &max_stack_size, 1);
  3363       if (errcode != arg_in_range) {
  3364         jio_fprintf(defaultStream::error_stream(),
  3365                     "Invalid maximum mark stack size: %s\n",
  3366                     option->optionString);
  3367         describe_range_error(errcode);
  3368         return JNI_EINVAL;
  3370       FLAG_SET_CMDLINE(uintx, MarkStackSizeMax, max_stack_size);
  3371     } else if (match_option(option, "-XX:ParallelMarkingThreads=", &tail) ||
  3372                match_option(option, "-XX:ParallelCMSThreads=", &tail)) {
  3373       uintx conc_threads = 0;
  3374       if (!parse_uintx(tail, &conc_threads, 1)) {
  3375         jio_fprintf(defaultStream::error_stream(),
  3376                     "Invalid concurrent threads: %s\n", option->optionString);
  3377         return JNI_EINVAL;
  3379       FLAG_SET_CMDLINE(uintx, ConcGCThreads, conc_threads);
  3380     } else if (match_option(option, "-XX:MaxDirectMemorySize=", &tail)) {
  3381       julong max_direct_memory_size = 0;
  3382       ArgsRange errcode = parse_memory_size(tail, &max_direct_memory_size, 0);
  3383       if (errcode != arg_in_range) {
  3384         jio_fprintf(defaultStream::error_stream(),
  3385                     "Invalid maximum direct memory size: %s\n",
  3386                     option->optionString);
  3387         describe_range_error(errcode);
  3388         return JNI_EINVAL;
  3390       FLAG_SET_CMDLINE(uintx, MaxDirectMemorySize, max_direct_memory_size);
  3391     } else if (match_option(option, "-XX:+UseVMInterruptibleIO", &tail)) {
  3392       // NOTE! In JDK 9, the UseVMInterruptibleIO flag will completely go
  3393       //       away and will cause VM initialization failures!
  3394       warning("-XX:+UseVMInterruptibleIO is obsolete and will be removed in a future release.");
  3395       FLAG_SET_CMDLINE(bool, UseVMInterruptibleIO, true);
  3396 #if !INCLUDE_MANAGEMENT
  3397     } else if (match_option(option, "-XX:+ManagementServer", &tail)) {
  3398         jio_fprintf(defaultStream::error_stream(),
  3399           "ManagementServer is not supported in this VM.\n");
  3400         return JNI_ERR;
  3401 #endif // INCLUDE_MANAGEMENT
  3402     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
  3403       // Skip -XX:Flags= since that case has already been handled
  3404       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
  3405         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
  3406           return JNI_EINVAL;
  3409     // Unknown option
  3410     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
  3411       return JNI_ERR;
  3415   // PrintSharedArchiveAndExit will turn on
  3416   //   -Xshare:on
  3417   //   -XX:+TraceClassPaths
  3418   if (PrintSharedArchiveAndExit) {
  3419     FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
  3420     FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true);
  3421     FLAG_SET_CMDLINE(bool, TraceClassPaths, true);
  3424   // Change the default value for flags  which have different default values
  3425   // when working with older JDKs.
  3426 #ifdef LINUX
  3427  if (JDK_Version::current().compare_major(6) <= 0 &&
  3428       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
  3429     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
  3431 #endif // LINUX
  3432   fix_appclasspath();
  3433   return JNI_OK;
  3436 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
  3437 //
  3438 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
  3439 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
  3440 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
  3441 // path is treated as the current directory.
  3442 //
  3443 // This causes problems with CDS, which requires that all directories specified in the classpath
  3444 // must be empty. In most cases, applications do NOT want to load classes from the current
  3445 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
  3446 // scripts compatible with CDS.
  3447 void Arguments::fix_appclasspath() {
  3448   if (IgnoreEmptyClassPaths) {
  3449     const char separator = *os::path_separator();
  3450     const char* src = _java_class_path->value();
  3452     // skip over all the leading empty paths
  3453     while (*src == separator) {
  3454       src ++;
  3457     char* copy = AllocateHeap(strlen(src) + 1, mtInternal);
  3458     strncpy(copy, src, strlen(src) + 1);
  3460     // trim all trailing empty paths
  3461     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
  3462       *tail = '\0';
  3465     char from[3] = {separator, separator, '\0'};
  3466     char to  [2] = {separator, '\0'};
  3467     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
  3468       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
  3469       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
  3472     _java_class_path->set_value(copy);
  3473     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
  3476   if (!PrintSharedArchiveAndExit) {
  3477     ClassLoader::trace_class_path(tty, "[classpath: ", _java_class_path->value());
  3481 static bool has_jar_files(const char* directory) {
  3482   DIR* dir = os::opendir(directory);
  3483   if (dir == NULL) return false;
  3485   struct dirent *entry;
  3486   bool hasJarFile = false;
  3487   while (!hasJarFile && (entry = os::readdir(dir)) != NULL) {
  3488     const char* name = entry->d_name;
  3489     const char* ext = name + strlen(name) - 4;
  3490     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
  3492   os::closedir(dir);
  3493   return hasJarFile ;
  3496 // returns the number of directories in the given path containing JAR files
  3497 // If the skip argument is not NULL, it will skip that directory
  3498 static int check_non_empty_dirs(const char* path, const char* type, const char* skip) {
  3499   const char separator = *os::path_separator();
  3500   const char* const end = path + strlen(path);
  3501   int nonEmptyDirs = 0;
  3502   while (path < end) {
  3503     const char* tmp_end = strchr(path, separator);
  3504     if (tmp_end == NULL) {
  3505       if ((skip == NULL || strcmp(path, skip) != 0) && has_jar_files(path)) {
  3506         nonEmptyDirs++;
  3507         jio_fprintf(defaultStream::output_stream(),
  3508           "Non-empty %s directory: %s\n", type, path);
  3510       path = end;
  3511     } else {
  3512       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtInternal);
  3513       memcpy(dirpath, path, tmp_end - path);
  3514       dirpath[tmp_end - path] = '\0';
  3515       if ((skip == NULL || strcmp(dirpath, skip) != 0) && has_jar_files(dirpath)) {
  3516         nonEmptyDirs++;
  3517         jio_fprintf(defaultStream::output_stream(),
  3518           "Non-empty %s directory: %s\n", type, dirpath);
  3520       FREE_C_HEAP_ARRAY(char, dirpath, mtInternal);
  3521       path = tmp_end + 1;
  3524   return nonEmptyDirs;
  3527 // Returns true if endorsed standards override mechanism and extension mechanism
  3528 // are not used.
  3529 static bool check_endorsed_and_ext_dirs() {
  3530   if (!CheckEndorsedAndExtDirs)
  3531     return true;
  3533   char endorsedDir[JVM_MAXPATHLEN];
  3534   char extDir[JVM_MAXPATHLEN];
  3535   const char* fileSep = os::file_separator();
  3536   jio_snprintf(endorsedDir, sizeof(endorsedDir), "%s%slib%sendorsed",
  3537                Arguments::get_java_home(), fileSep, fileSep);
  3538   jio_snprintf(extDir, sizeof(extDir), "%s%slib%sext",
  3539                Arguments::get_java_home(), fileSep, fileSep);
  3541   // check endorsed directory
  3542   int nonEmptyDirs = check_non_empty_dirs(Arguments::get_endorsed_dir(), "endorsed", NULL);
  3544   // check the extension directories but skip the default lib/ext directory
  3545   nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs(), "extension", extDir);
  3547   // List of JAR files installed in the default lib/ext directory.
  3548   // -XX:+CheckEndorsedAndExtDirs checks if any non-JDK file installed
  3549   static const char* jdk_ext_jars[] = {
  3550       "access-bridge-32.jar",
  3551       "access-bridge-64.jar",
  3552       "access-bridge.jar",
  3553       "cldrdata.jar",
  3554       "dnsns.jar",
  3555       "jaccess.jar",
  3556       "jfxrt.jar",
  3557       "localedata.jar",
  3558       "nashorn.jar",
  3559       "sunec.jar",
  3560       "sunjce_provider.jar",
  3561       "sunmscapi.jar",
  3562       "sunpkcs11.jar",
  3563       "ucrypto.jar",
  3564       "zipfs.jar",
  3565       NULL
  3566   };
  3568   // check if the default lib/ext directory has any non-JDK jar files; if so, error
  3569   DIR* dir = os::opendir(extDir);
  3570   if (dir != NULL) {
  3571     int num_ext_jars = 0;
  3572     struct dirent *entry;
  3573     while ((entry = os::readdir(dir)) != NULL) {
  3574       const char* name = entry->d_name;
  3575       const char* ext = name + strlen(name) - 4;
  3576       if (ext > name && (os::file_name_strcmp(ext, ".jar") == 0)) {
  3577         bool is_jdk_jar = false;
  3578         const char* jarfile = NULL;
  3579         for (int i=0; (jarfile = jdk_ext_jars[i]) != NULL; i++) {
  3580           if (os::file_name_strcmp(name, jarfile) == 0) {
  3581             is_jdk_jar = true;
  3582             break;
  3585         if (!is_jdk_jar) {
  3586           jio_fprintf(defaultStream::output_stream(),
  3587             "%s installed in <JAVA_HOME>/lib/ext\n", name);
  3588           num_ext_jars++;
  3592     os::closedir(dir);
  3593     if (num_ext_jars > 0) {
  3594       nonEmptyDirs += 1;
  3598   // check if the default lib/endorsed directory exists; if so, error
  3599   dir = os::opendir(endorsedDir);
  3600   if (dir != NULL) {
  3601     jio_fprintf(defaultStream::output_stream(), "<JAVA_HOME>/lib/endorsed exists\n");
  3602     os::closedir(dir);
  3603     nonEmptyDirs += 1;
  3606   if (nonEmptyDirs > 0) {
  3607     jio_fprintf(defaultStream::output_stream(),
  3608       "Endorsed standards override mechanism and extension mechanism "
  3609       "will not be supported in a future release.\n"
  3610       "Refer to JEP 220 for details (http://openjdk.java.net/jeps/220).\n");
  3611     return false;
  3614   return true;
  3617 jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_required) {
  3618   // This must be done after all -D arguments have been processed.
  3619   scp_p->expand_endorsed();
  3621   if (scp_assembly_required || scp_p->get_endorsed() != NULL) {
  3622     // Assemble the bootclasspath elements into the final path.
  3623     Arguments::set_sysclasspath(scp_p->combined_path());
  3626   if (!check_endorsed_and_ext_dirs()) {
  3627     return JNI_ERR;
  3630   // This must be done after all arguments have been processed
  3631   // and the container support has been initialized since AggressiveHeap
  3632   // relies on the amount of total memory available.
  3633   if (AggressiveHeap) {
  3634     jint result = set_aggressive_heap_flags();
  3635     if (result != JNI_OK) {
  3636       return result;
  3639   // This must be done after all arguments have been processed.
  3640   // java_compiler() true means set to "NONE" or empty.
  3641   if (java_compiler() && !xdebug_mode()) {
  3642     // For backwards compatibility, we switch to interpreted mode if
  3643     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
  3644     // not specified.
  3645     set_mode_flags(_int);
  3647   if (CompileThreshold == 0) {
  3648     set_mode_flags(_int);
  3651   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
  3652   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
  3653     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
  3656 #ifndef COMPILER2
  3657   // Don't degrade server performance for footprint
  3658   if (FLAG_IS_DEFAULT(UseLargePages) &&
  3659       MaxHeapSize < LargePageHeapSizeThreshold) {
  3660     // No need for large granularity pages w/small heaps.
  3661     // Note that large pages are enabled/disabled for both the
  3662     // Java heap and the code cache.
  3663     FLAG_SET_DEFAULT(UseLargePages, false);
  3666 #else
  3667   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
  3668     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
  3670 #endif
  3672 #ifndef TIERED
  3673   // Tiered compilation is undefined.
  3674   UNSUPPORTED_OPTION(TieredCompilation, "TieredCompilation");
  3675 #endif
  3677   // If we are running in a headless jre, force java.awt.headless property
  3678   // to be true unless the property has already been set.
  3679   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
  3680   if (os::is_headless_jre()) {
  3681     const char* headless = Arguments::get_property("java.awt.headless");
  3682     if (headless == NULL) {
  3683       char envbuffer[128];
  3684       if (!os::getenv("JAVA_AWT_HEADLESS", envbuffer, sizeof(envbuffer))) {
  3685         if (!add_property("java.awt.headless=true")) {
  3686           return JNI_ENOMEM;
  3688       } else {
  3689         char buffer[256];
  3690         jio_snprintf(buffer, 256, "java.awt.headless=%s", envbuffer);
  3691         if (!add_property(buffer)) {
  3692           return JNI_ENOMEM;
  3698   if (!check_vm_args_consistency()) {
  3699     return JNI_ERR;
  3702   return JNI_OK;
  3705 jint Arguments::parse_java_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
  3706   return parse_options_environment_variable("_JAVA_OPTIONS", scp_p,
  3707                                             scp_assembly_required_p);
  3710 jint Arguments::parse_java_tool_options_environment_variable(SysClassPath* scp_p, bool* scp_assembly_required_p) {
  3711   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", scp_p,
  3712                                             scp_assembly_required_p);
  3715 jint Arguments::parse_options_environment_variable(const char* name, SysClassPath* scp_p, bool* scp_assembly_required_p) {
  3716   const int N_MAX_OPTIONS = 64;
  3717   const int OPTION_BUFFER_SIZE = 1024;
  3718   char buffer[OPTION_BUFFER_SIZE];
  3720   // The variable will be ignored if it exceeds the length of the buffer.
  3721   // Don't check this variable if user has special privileges
  3722   // (e.g. unix su command).
  3723   if (os::getenv(name, buffer, sizeof(buffer)) &&
  3724       !os::have_special_privileges()) {
  3725     JavaVMOption options[N_MAX_OPTIONS];      // Construct option array
  3726     jio_fprintf(defaultStream::error_stream(),
  3727                 "Picked up %s: %s\n", name, buffer);
  3728     char* rd = buffer;                        // pointer to the input string (rd)
  3729     int i;
  3730     for (i = 0; i < N_MAX_OPTIONS;) {         // repeat for all options in the input string
  3731       while (isspace(*rd)) rd++;              // skip whitespace
  3732       if (*rd == 0) break;                    // we re done when the input string is read completely
  3734       // The output, option string, overwrites the input string.
  3735       // Because of quoting, the pointer to the option string (wrt) may lag the pointer to
  3736       // input string (rd).
  3737       char* wrt = rd;
  3739       options[i++].optionString = wrt;        // Fill in option
  3740       while (*rd != 0 && !isspace(*rd)) {     // unquoted strings terminate with a space or NULL
  3741         if (*rd == '\'' || *rd == '"') {      // handle a quoted string
  3742           int quote = *rd;                    // matching quote to look for
  3743           rd++;                               // don't copy open quote
  3744           while (*rd != quote) {              // include everything (even spaces) up until quote
  3745             if (*rd == 0) {                   // string termination means unmatched string
  3746               jio_fprintf(defaultStream::error_stream(),
  3747                           "Unmatched quote in %s\n", name);
  3748               return JNI_ERR;
  3750             *wrt++ = *rd++;                   // copy to option string
  3752           rd++;                               // don't copy close quote
  3753         } else {
  3754           *wrt++ = *rd++;                     // copy to option string
  3757       // Need to check if we're done before writing a NULL,
  3758       // because the write could be to the byte that rd is pointing to.
  3759       if (*rd++ == 0) {
  3760         *wrt = 0;
  3761         break;
  3763       *wrt = 0;                               // Zero terminate option
  3765     // Construct JavaVMInitArgs structure and parse as if it was part of the command line
  3766     JavaVMInitArgs vm_args;
  3767     vm_args.version = JNI_VERSION_1_2;
  3768     vm_args.options = options;
  3769     vm_args.nOptions = i;
  3770     vm_args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
  3772     if (PrintVMOptions) {
  3773       const char* tail;
  3774       for (int i = 0; i < vm_args.nOptions; i++) {
  3775         const JavaVMOption *option = vm_args.options + i;
  3776         if (match_option(option, "-XX:", &tail)) {
  3777           logOption(tail);
  3782     return(parse_each_vm_init_arg(&vm_args, scp_p, scp_assembly_required_p, Flag::ENVIRON_VAR));
  3784   return JNI_OK;
  3787 void Arguments::set_shared_spaces_flags() {
  3788   if (DumpSharedSpaces) {
  3789     if (FailOverToOldVerifier) {
  3790       // Don't fall back to the old verifier on verification failure. If a
  3791       // class fails verification with the split verifier, it might fail the
  3792       // CDS runtime verifier constraint check. In that case, we don't want
  3793       // to share the class. We only archive classes that pass the split verifier.
  3794       FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
  3797     if (RequireSharedSpaces) {
  3798       warning("cannot dump shared archive while using shared archive");
  3800     UseSharedSpaces = false;
  3801 #ifdef _LP64
  3802     if (!UseCompressedOops || !UseCompressedClassPointers) {
  3803       vm_exit_during_initialization(
  3804         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
  3806   } else {
  3807     if (!UseCompressedOops || !UseCompressedClassPointers) {
  3808       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
  3810 #endif
  3814 #if !INCLUDE_ALL_GCS
  3815 static void force_serial_gc() {
  3816   FLAG_SET_DEFAULT(UseSerialGC, true);
  3817   FLAG_SET_DEFAULT(CMSIncrementalMode, false);  // special CMS suboption
  3818   UNSUPPORTED_GC_OPTION(UseG1GC);
  3819   UNSUPPORTED_GC_OPTION(UseParallelGC);
  3820   UNSUPPORTED_GC_OPTION(UseParallelOldGC);
  3821   UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
  3822   UNSUPPORTED_GC_OPTION(UseParNewGC);
  3824 #endif // INCLUDE_ALL_GCS
  3826 // Sharing support
  3827 // Construct the path to the archive
  3828 static char* get_shared_archive_path() {
  3829   char *shared_archive_path;
  3830   if (SharedArchiveFile == NULL) {
  3831     char jvm_path[JVM_MAXPATHLEN];
  3832     os::jvm_path(jvm_path, sizeof(jvm_path));
  3833     char *end = strrchr(jvm_path, *os::file_separator());
  3834     if (end != NULL) *end = '\0';
  3835     size_t jvm_path_len = strlen(jvm_path);
  3836     size_t file_sep_len = strlen(os::file_separator());
  3837     shared_archive_path = NEW_C_HEAP_ARRAY(char, jvm_path_len +
  3838         file_sep_len + 20, mtInternal);
  3839     if (shared_archive_path != NULL) {
  3840       strncpy(shared_archive_path, jvm_path, jvm_path_len + 1);
  3841       strncat(shared_archive_path, os::file_separator(), file_sep_len);
  3842       strncat(shared_archive_path, "classes.jsa", 11);
  3844   } else {
  3845     shared_archive_path = NEW_C_HEAP_ARRAY(char, strlen(SharedArchiveFile) + 1, mtInternal);
  3846     if (shared_archive_path != NULL) {
  3847       strncpy(shared_archive_path, SharedArchiveFile, strlen(SharedArchiveFile) + 1);
  3850   return shared_archive_path;
  3853 #ifndef PRODUCT
  3854 // Determine whether LogVMOutput should be implicitly turned on.
  3855 static bool use_vm_log() {
  3856   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
  3857       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
  3858       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
  3859       PrintAssembly || TraceDeoptimization || TraceDependencies ||
  3860       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
  3861     return true;
  3864 #ifdef COMPILER1
  3865   if (PrintC1Statistics) {
  3866     return true;
  3868 #endif // COMPILER1
  3870 #ifdef COMPILER2
  3871   if (PrintOptoAssembly || PrintOptoStatistics) {
  3872     return true;
  3874 #endif // COMPILER2
  3876   return false;
  3878 #endif // PRODUCT
  3880 // Parse entry point called from JNI_CreateJavaVM
  3882 jint Arguments::parse(const JavaVMInitArgs* args) {
  3884   // Remaining part of option string
  3885   const char* tail;
  3887   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
  3888   const char* hotspotrc = ".hotspotrc";
  3889   bool settings_file_specified = false;
  3890   bool needs_hotspotrc_warning = false;
  3892   ArgumentsExt::process_options(args);
  3894   const char* flags_file;
  3895   int index;
  3896   for (index = 0; index < args->nOptions; index++) {
  3897     const JavaVMOption *option = args->options + index;
  3898     if (match_option(option, "-XX:Flags=", &tail)) {
  3899       flags_file = tail;
  3900       settings_file_specified = true;
  3902     if (match_option(option, "-XX:+PrintVMOptions", &tail)) {
  3903       PrintVMOptions = true;
  3905     if (match_option(option, "-XX:-PrintVMOptions", &tail)) {
  3906       PrintVMOptions = false;
  3908     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions", &tail)) {
  3909       IgnoreUnrecognizedVMOptions = true;
  3911     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions", &tail)) {
  3912       IgnoreUnrecognizedVMOptions = false;
  3914     if (match_option(option, "-XX:+PrintFlagsInitial", &tail)) {
  3915       CommandLineFlags::printFlags(tty, false);
  3916       vm_exit(0);
  3918     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
  3919 #if INCLUDE_NMT
  3920       // The launcher did not setup nmt environment variable properly.
  3921       if (!MemTracker::check_launcher_nmt_support(tail)) {
  3922         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
  3925       // Verify if nmt option is valid.
  3926       if (MemTracker::verify_nmt_option()) {
  3927         // Late initialization, still in single-threaded mode.
  3928         if (MemTracker::tracking_level() >= NMT_summary) {
  3929           MemTracker::init();
  3931       } else {
  3932         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
  3934 #else
  3935       jio_fprintf(defaultStream::error_stream(),
  3936         "Native Memory Tracking is not supported in this VM\n");
  3937       return JNI_ERR;
  3938 #endif
  3942 #ifndef PRODUCT
  3943     if (match_option(option, "-XX:+PrintFlagsWithComments", &tail)) {
  3944       CommandLineFlags::printFlags(tty, true);
  3945       vm_exit(0);
  3947 #endif
  3950   if (IgnoreUnrecognizedVMOptions) {
  3951     // uncast const to modify the flag args->ignoreUnrecognized
  3952     *(jboolean*)(&args->ignoreUnrecognized) = true;
  3955   // Parse specified settings file
  3956   if (settings_file_specified) {
  3957     if (!process_settings_file(flags_file, true, args->ignoreUnrecognized)) {
  3958       return JNI_EINVAL;
  3960   } else {
  3961 #ifdef ASSERT
  3962     // Parse default .hotspotrc settings file
  3963     if (!process_settings_file(".hotspotrc", false, args->ignoreUnrecognized)) {
  3964       return JNI_EINVAL;
  3966 #else
  3967     struct stat buf;
  3968     if (os::stat(hotspotrc, &buf) == 0) {
  3969       needs_hotspotrc_warning = true;
  3971 #endif
  3974   if (PrintVMOptions) {
  3975     for (index = 0; index < args->nOptions; index++) {
  3976       const JavaVMOption *option = args->options + index;
  3977       if (match_option(option, "-XX:", &tail)) {
  3978         logOption(tail);
  3983   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
  3984   jint result = parse_vm_init_args(args);
  3985   if (result != JNI_OK) {
  3986     return result;
  3989   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
  3990   SharedArchivePath = get_shared_archive_path();
  3991   if (SharedArchivePath == NULL) {
  3992     return JNI_ENOMEM;
  3995   // Set up VerifySharedSpaces
  3996   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
  3997     VerifySharedSpaces = true;
  4000   // Delay warning until here so that we've had a chance to process
  4001   // the -XX:-PrintWarnings flag
  4002   if (needs_hotspotrc_warning) {
  4003     warning("%s file is present but has been ignored.  "
  4004             "Run with -XX:Flags=%s to load the file.",
  4005             hotspotrc, hotspotrc);
  4008 #ifdef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
  4009   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
  4010 #endif
  4012 #if INCLUDE_ALL_GCS
  4013   #if (defined JAVASE_EMBEDDED || defined ARM)
  4014     UNSUPPORTED_OPTION(UseG1GC, "G1 GC");
  4015   #endif
  4016 #endif
  4018 #ifndef PRODUCT
  4019   if (TraceBytecodesAt != 0) {
  4020     TraceBytecodes = true;
  4022   if (CountCompiledCalls) {
  4023     if (UseCounterDecay) {
  4024       warning("UseCounterDecay disabled because CountCalls is set");
  4025       UseCounterDecay = false;
  4028 #endif // PRODUCT
  4030   // JSR 292 is not supported before 1.7
  4031   if (!JDK_Version::is_gte_jdk17x_version()) {
  4032     if (EnableInvokeDynamic) {
  4033       if (!FLAG_IS_DEFAULT(EnableInvokeDynamic)) {
  4034         warning("JSR 292 is not supported before 1.7.  Disabling support.");
  4036       EnableInvokeDynamic = false;
  4040   if (EnableInvokeDynamic && ScavengeRootsInCode == 0) {
  4041     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
  4042       warning("forcing ScavengeRootsInCode non-zero because EnableInvokeDynamic is true");
  4044     ScavengeRootsInCode = 1;
  4047   if (PrintGCDetails) {
  4048     // Turn on -verbose:gc options as well
  4049     PrintGC = true;
  4052   if (!JDK_Version::is_gte_jdk18x_version()) {
  4053     // To avoid changing the log format for 7 updates this flag is only
  4054     // true by default in JDK8 and above.
  4055     if (FLAG_IS_DEFAULT(PrintGCCause)) {
  4056       FLAG_SET_DEFAULT(PrintGCCause, false);
  4060   // Set object alignment values.
  4061   set_object_alignment();
  4063 #if !INCLUDE_ALL_GCS
  4064   force_serial_gc();
  4065 #endif // INCLUDE_ALL_GCS
  4066 #if !INCLUDE_CDS
  4067   if (DumpSharedSpaces || RequireSharedSpaces) {
  4068     jio_fprintf(defaultStream::error_stream(),
  4069       "Shared spaces are not supported in this VM\n");
  4070     return JNI_ERR;
  4072   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
  4073     warning("Shared spaces are not supported in this VM");
  4074     FLAG_SET_DEFAULT(UseSharedSpaces, false);
  4075     FLAG_SET_DEFAULT(PrintSharedSpaces, false);
  4077   no_shared_spaces("CDS Disabled");
  4078 #endif // INCLUDE_CDS
  4080   return JNI_OK;
  4083 jint Arguments::apply_ergo() {
  4085   // Set flags based on ergonomics.
  4086   set_ergonomics_flags();
  4088   set_shared_spaces_flags();
  4090 #if defined(SPARC)
  4091   // BIS instructions require 'membar' instruction regardless of the number
  4092   // of CPUs because in virtualized/container environments which might use only 1
  4093   // CPU, BIS instructions may produce incorrect results.
  4095   if (FLAG_IS_DEFAULT(AssumeMP)) {
  4096     FLAG_SET_DEFAULT(AssumeMP, true);
  4098 #endif
  4100   // Check the GC selections again.
  4101   if (!check_gc_consistency()) {
  4102     return JNI_EINVAL;
  4105   if (TieredCompilation) {
  4106     set_tiered_flags();
  4107   } else {
  4108     // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup.
  4109     if (CompilationPolicyChoice >= 2) {
  4110       vm_exit_during_initialization(
  4111         "Incompatible compilation policy selected", NULL);
  4114   // Set NmethodSweepFraction after the size of the code cache is adapted (in case of tiered)
  4115   if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
  4116     FLAG_SET_DEFAULT(NmethodSweepFraction, 1 + ReservedCodeCacheSize / (16 * M));
  4120   // Set heap size based on available physical memory
  4121   set_heap_size();
  4123   ArgumentsExt::set_gc_specific_flags();
  4125   // Initialize Metaspace flags and alignments.
  4126   Metaspace::ergo_initialize();
  4128   // Set bytecode rewriting flags
  4129   set_bytecode_flags();
  4131   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled.
  4132   set_aggressive_opts_flags();
  4134   // Turn off biased locking for locking debug mode flags,
  4135   // which are subtlely different from each other but neither works with
  4136   // biased locking.
  4137   if (UseHeavyMonitors
  4138 #ifdef COMPILER1
  4139       || !UseFastLocking
  4140 #endif // COMPILER1
  4141     ) {
  4142     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
  4143       // flag set to true on command line; warn the user that they
  4144       // can't enable biased locking here
  4145       warning("Biased Locking is not supported with locking debug flags"
  4146               "; ignoring UseBiasedLocking flag." );
  4148     UseBiasedLocking = false;
  4151 #ifdef ZERO
  4152   // Clear flags not supported on zero.
  4153   FLAG_SET_DEFAULT(ProfileInterpreter, false);
  4154   FLAG_SET_DEFAULT(UseBiasedLocking, false);
  4155   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
  4156   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
  4157 #endif // CC_INTERP
  4159 #ifdef COMPILER2
  4160   if (!EliminateLocks) {
  4161     EliminateNestedLocks = false;
  4163   if (!Inline) {
  4164     IncrementalInline = false;
  4166 #ifndef PRODUCT
  4167   if (!IncrementalInline) {
  4168     AlwaysIncrementalInline = false;
  4170 #endif
  4171   if (IncrementalInline && FLAG_IS_DEFAULT(MaxNodeLimit)) {
  4172     // incremental inlining: bump MaxNodeLimit
  4173     FLAG_SET_DEFAULT(MaxNodeLimit, (intx)75000);
  4175   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
  4176     // nothing to use the profiling, turn if off
  4177     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
  4179 #endif
  4181   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
  4182     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
  4183     DebugNonSafepoints = true;
  4186   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
  4187     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
  4190   if (UseOnStackReplacement && !UseLoopCounter) {
  4191     warning("On-stack-replacement requires loop counters; enabling loop counters");
  4192     FLAG_SET_DEFAULT(UseLoopCounter, true);
  4195 #ifndef PRODUCT
  4196   if (CompileTheWorld) {
  4197     // Force NmethodSweeper to sweep whole CodeCache each time.
  4198     if (FLAG_IS_DEFAULT(NmethodSweepFraction)) {
  4199       NmethodSweepFraction = 1;
  4203   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
  4204     if (use_vm_log()) {
  4205       LogVMOutput = true;
  4208 #endif // PRODUCT
  4210   if (PrintCommandLineFlags) {
  4211     CommandLineFlags::printSetFlags(tty);
  4214   // Apply CPU specific policy for the BiasedLocking
  4215   if (UseBiasedLocking) {
  4216     if (!VM_Version::use_biased_locking() &&
  4217         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
  4218       UseBiasedLocking = false;
  4221 #ifdef COMPILER2
  4222   if (!UseBiasedLocking || EmitSync != 0) {
  4223     UseOptoBiasInlining = false;
  4225 #endif
  4227   // set PauseAtExit if the gamma launcher was used and a debugger is attached
  4228   // but only if not already set on the commandline
  4229   if (Arguments::created_by_gamma_launcher() && os::is_debugger_attached()) {
  4230     bool set = false;
  4231     CommandLineFlags::wasSetOnCmdline("PauseAtExit", &set);
  4232     if (!set) {
  4233       FLAG_SET_DEFAULT(PauseAtExit, true);
  4237   return JNI_OK;
  4240 jint Arguments::adjust_after_os() {
  4241   if (UseNUMA) {
  4242     if (UseParallelGC || UseParallelOldGC) {
  4243       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
  4244          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
  4247     // UseNUMAInterleaving is set to ON for all collectors and
  4248     // platforms when UseNUMA is set to ON. NUMA-aware collectors
  4249     // such as the parallel collector for Linux and Solaris will
  4250     // interleave old gen and survivor spaces on top of NUMA
  4251     // allocation policy for the eden space.
  4252     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
  4253     // all platforms and ParallelGC on Windows will interleave all
  4254     // of the heap spaces across NUMA nodes.
  4255     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
  4256       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
  4259   return JNI_OK;
  4262 int Arguments::PropertyList_count(SystemProperty* pl) {
  4263   int count = 0;
  4264   while(pl != NULL) {
  4265     count++;
  4266     pl = pl->next();
  4268   return count;
  4271 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
  4272   assert(key != NULL, "just checking");
  4273   SystemProperty* prop;
  4274   for (prop = pl; prop != NULL; prop = prop->next()) {
  4275     if (strcmp(key, prop->key()) == 0) return prop->value();
  4277   return NULL;
  4280 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
  4281   int count = 0;
  4282   const char* ret_val = NULL;
  4284   while(pl != NULL) {
  4285     if(count >= index) {
  4286       ret_val = pl->key();
  4287       break;
  4289     count++;
  4290     pl = pl->next();
  4293   return ret_val;
  4296 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
  4297   int count = 0;
  4298   char* ret_val = NULL;
  4300   while(pl != NULL) {
  4301     if(count >= index) {
  4302       ret_val = pl->value();
  4303       break;
  4305     count++;
  4306     pl = pl->next();
  4309   return ret_val;
  4312 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
  4313   SystemProperty* p = *plist;
  4314   if (p == NULL) {
  4315     *plist = new_p;
  4316   } else {
  4317     while (p->next() != NULL) {
  4318       p = p->next();
  4320     p->set_next(new_p);
  4324 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, char* v) {
  4325   if (plist == NULL)
  4326     return;
  4328   SystemProperty* new_p = new SystemProperty(k, v, true);
  4329   PropertyList_add(plist, new_p);
  4332 // This add maintains unique property key in the list.
  4333 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, char* v, jboolean append) {
  4334   if (plist == NULL)
  4335     return;
  4337   // If property key exist then update with new value.
  4338   SystemProperty* prop;
  4339   for (prop = *plist; prop != NULL; prop = prop->next()) {
  4340     if (strcmp(k, prop->key()) == 0) {
  4341       if (append) {
  4342         prop->append_value(v);
  4343       } else {
  4344         prop->set_value(v);
  4346       return;
  4350   PropertyList_add(plist, k, v);
  4353 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
  4354 // Returns true if all of the source pointed by src has been copied over to
  4355 // the destination buffer pointed by buf. Otherwise, returns false.
  4356 // Notes:
  4357 // 1. If the length (buflen) of the destination buffer excluding the
  4358 // NULL terminator character is not long enough for holding the expanded
  4359 // pid characters, it also returns false instead of returning the partially
  4360 // expanded one.
  4361 // 2. The passed in "buflen" should be large enough to hold the null terminator.
  4362 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
  4363                                 char* buf, size_t buflen) {
  4364   const char* p = src;
  4365   char* b = buf;
  4366   const char* src_end = &src[srclen];
  4367   char* buf_end = &buf[buflen - 1];
  4369   while (p < src_end && b < buf_end) {
  4370     if (*p == '%') {
  4371       switch (*(++p)) {
  4372       case '%':         // "%%" ==> "%"
  4373         *b++ = *p++;
  4374         break;
  4375       case 'p':  {       //  "%p" ==> current process id
  4376         // buf_end points to the character before the last character so
  4377         // that we could write '\0' to the end of the buffer.
  4378         size_t buf_sz = buf_end - b + 1;
  4379         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
  4381         // if jio_snprintf fails or the buffer is not long enough to hold
  4382         // the expanded pid, returns false.
  4383         if (ret < 0 || ret >= (int)buf_sz) {
  4384           return false;
  4385         } else {
  4386           b += ret;
  4387           assert(*b == '\0', "fail in copy_expand_pid");
  4388           if (p == src_end && b == buf_end + 1) {
  4389             // reach the end of the buffer.
  4390             return true;
  4393         p++;
  4394         break;
  4396       default :
  4397         *b++ = '%';
  4399     } else {
  4400       *b++ = *p++;
  4403   *b = '\0';
  4404   return (p == src_end); // return false if not all of the source was copied

mercurial