1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/javaAssertions.hpp"
  29 #include "classfile/moduleEntry.hpp"
  30 #include "classfile/stringTable.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "gc/shared/gcArguments.hpp"
  33 #include "gc/shared/genCollectedHeap.hpp"
  34 #include "gc/shared/referenceProcessor.hpp"
  35 #include "gc/shared/taskqueue.hpp"
  36 #include "logging/log.hpp"
  37 #include "logging/logConfiguration.hpp"
  38 #include "logging/logStream.hpp"
  39 #include "logging/logTag.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/universe.inline.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "prims/jvmtiExport.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/arguments_ext.hpp"
  46 #include "runtime/commandLineFlagConstraintList.hpp"
  47 #include "runtime/commandLineFlagWriteableList.hpp"
  48 #include "runtime/commandLineFlagRangeList.hpp"
  49 #include "runtime/globals.hpp"
  50 #include "runtime/globals_extension.hpp"
  51 #include "runtime/java.hpp"
  52 #include "runtime/os.hpp"
  53 #include "runtime/safepointMechanism.hpp"
  54 #include "runtime/vm_version.hpp"
  55 #include "services/management.hpp"
  56 #include "services/memTracker.hpp"
  57 #include "utilities/align.hpp"
  58 #include "utilities/defaultStream.hpp"
  59 #include "utilities/macros.hpp"
  60 #include "utilities/stringUtils.hpp"
  61 #if INCLUDE_JVMCI
  62 #include "jvmci/jvmciRuntime.hpp"
  63 #endif
  64 
  65 // Note: This is a special bug reporting site for the JVM
  66 #define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
  67 #define DEFAULT_JAVA_LAUNCHER  "generic"
  68 
  69 char*  Arguments::_jvm_flags_file               = NULL;
  70 char** Arguments::_jvm_flags_array              = NULL;
  71 int    Arguments::_num_jvm_flags                = 0;
  72 char** Arguments::_jvm_args_array               = NULL;
  73 int    Arguments::_num_jvm_args                 = 0;
  74 char*  Arguments::_java_command                 = NULL;
  75 SystemProperty* Arguments::_system_properties   = NULL;
  76 const char*  Arguments::_gc_log_filename        = NULL;
  77 size_t Arguments::_conservative_max_heap_alignment = 0;
  78 size_t Arguments::_min_heap_size                = 0;
  79 Arguments::Mode Arguments::_mode                = _mixed;
  80 bool   Arguments::_java_compiler                = false;
  81 bool   Arguments::_xdebug_mode                  = false;
  82 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  83 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  84 int    Arguments::_sun_java_launcher_pid        = -1;
  85 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  86 
  87 // These parameters are reset in method parse_vm_init_args()
  88 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  89 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  90 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  91 bool   Arguments::_ClipInlining                 = ClipInlining;
  92 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
  93 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
  94 
  95 char*  Arguments::SharedArchivePath             = NULL;
  96 
  97 AgentLibraryList Arguments::_libraryList;
  98 AgentLibraryList Arguments::_agentList;
  99 
 100 abort_hook_t     Arguments::_abort_hook         = NULL;
 101 exit_hook_t      Arguments::_exit_hook          = NULL;
 102 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 103 
 104 
 105 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 106 SystemProperty *Arguments::_java_library_path = NULL;
 107 SystemProperty *Arguments::_java_home = NULL;
 108 SystemProperty *Arguments::_java_class_path = NULL;
 109 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
 110 
 111 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
 112 PathString *Arguments::_system_boot_class_path = NULL;
 113 bool Arguments::_has_jimage = false;
 114 
 115 char* Arguments::_ext_dirs = NULL;
 116 
 117 bool PathString::set_value(const char *value) {
 118   if (_value != NULL) {
 119     FreeHeap(_value);
 120   }
 121   _value = AllocateHeap(strlen(value)+1, mtArguments);
 122   assert(_value != NULL, "Unable to allocate space for new path value");
 123   if (_value != NULL) {
 124     strcpy(_value, value);
 125   } else {
 126     // not able to allocate
 127     return false;
 128   }
 129   return true;
 130 }
 131 
 132 void PathString::append_value(const char *value) {
 133   char *sp;
 134   size_t len = 0;
 135   if (value != NULL) {
 136     len = strlen(value);
 137     if (_value != NULL) {
 138       len += strlen(_value);
 139     }
 140     sp = AllocateHeap(len+2, mtArguments);
 141     assert(sp != NULL, "Unable to allocate space for new append path value");
 142     if (sp != NULL) {
 143       if (_value != NULL) {
 144         strcpy(sp, _value);
 145         strcat(sp, os::path_separator());
 146         strcat(sp, value);
 147         FreeHeap(_value);
 148       } else {
 149         strcpy(sp, value);
 150       }
 151       _value = sp;
 152     }
 153   }
 154 }
 155 
 156 PathString::PathString(const char* value) {
 157   if (value == NULL) {
 158     _value = NULL;
 159   } else {
 160     _value = AllocateHeap(strlen(value)+1, mtArguments);
 161     strcpy(_value, value);
 162   }
 163 }
 164 
 165 PathString::~PathString() {
 166   if (_value != NULL) {
 167     FreeHeap(_value);
 168     _value = NULL;
 169   }
 170 }
 171 
 172 ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {
 173   assert(module_name != NULL && path != NULL, "Invalid module name or path value");
 174   size_t len = strlen(module_name) + 1;
 175   _module_name = AllocateHeap(len, mtInternal);
 176   strncpy(_module_name, module_name, len); // copy the trailing null
 177   _path =  new PathString(path);
 178 }
 179 
 180 ModulePatchPath::~ModulePatchPath() {
 181   if (_module_name != NULL) {
 182     FreeHeap(_module_name);
 183     _module_name = NULL;
 184   }
 185   if (_path != NULL) {
 186     delete _path;
 187     _path = NULL;
 188   }
 189 }
 190 
 191 SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {
 192   if (key == NULL) {
 193     _key = NULL;
 194   } else {
 195     _key = AllocateHeap(strlen(key)+1, mtArguments);
 196     strcpy(_key, key);
 197   }
 198   _next = NULL;
 199   _internal = internal;
 200   _writeable = writeable;
 201 }
 202 
 203 AgentLibrary::AgentLibrary(const char* name, const char* options,
 204                bool is_absolute_path, void* os_lib,
 205                bool instrument_lib) {
 206   _name = AllocateHeap(strlen(name)+1, mtArguments);
 207   strcpy(_name, name);
 208   if (options == NULL) {
 209     _options = NULL;
 210   } else {
 211     _options = AllocateHeap(strlen(options)+1, mtArguments);
 212     strcpy(_options, options);
 213   }
 214   _is_absolute_path = is_absolute_path;
 215   _os_lib = os_lib;
 216   _next = NULL;
 217   _state = agent_invalid;
 218   _is_static_lib = false;
 219   _is_instrument_lib = instrument_lib;
 220 }
 221 
 222 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 223 // part of the option string.
 224 static bool match_option(const JavaVMOption *option, const char* name,
 225                          const char** tail) {
 226   size_t len = strlen(name);
 227   if (strncmp(option->optionString, name, len) == 0) {
 228     *tail = option->optionString + len;
 229     return true;
 230   } else {
 231     return false;
 232   }
 233 }
 234 
 235 // Check if 'option' matches 'name'. No "tail" is allowed.
 236 static bool match_option(const JavaVMOption *option, const char* name) {
 237   const char* tail = NULL;
 238   bool result = match_option(option, name, &tail);
 239   if (tail != NULL && *tail == '\0') {
 240     return result;
 241   } else {
 242     return false;
 243   }
 244 }
 245 
 246 // Return true if any of the strings in null-terminated array 'names' matches.
 247 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 248 // the option must match exactly.
 249 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 250   bool tail_allowed) {
 251   for (/* empty */; *names != NULL; ++names) {
 252   if (match_option(option, *names, tail)) {
 253       if (**tail == '\0' || (tail_allowed && **tail == ':')) {
 254         return true;
 255       }
 256     }
 257   }
 258   return false;
 259 }
 260 
 261 static void logOption(const char* opt) {
 262   if (PrintVMOptions) {
 263     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 264   }
 265 }
 266 
 267 bool needs_module_property_warning = false;
 268 
 269 #define MODULE_PROPERTY_PREFIX "jdk.module."
 270 #define MODULE_PROPERTY_PREFIX_LEN 11
 271 #define ADDEXPORTS "addexports"
 272 #define ADDEXPORTS_LEN 10
 273 #define ADDREADS "addreads"
 274 #define ADDREADS_LEN 8
 275 #define ADDOPENS "addopens"
 276 #define ADDOPENS_LEN 8
 277 #define PATCH "patch"
 278 #define PATCH_LEN 5
 279 #define ADDMODS "addmods"
 280 #define ADDMODS_LEN 7
 281 #define LIMITMODS "limitmods"
 282 #define LIMITMODS_LEN 9
 283 #define PATH "path"
 284 #define PATH_LEN 4
 285 #define UPGRADE_PATH "upgrade.path"
 286 #define UPGRADE_PATH_LEN 12
 287 
 288 void Arguments::add_init_library(const char* name, char* options) {
 289   _libraryList.add(new AgentLibrary(name, options, false, NULL));
 290 }
 291 
 292 void Arguments::add_init_agent(const char* name, char* options, bool absolute_path) {
 293   _agentList.add(new AgentLibrary(name, options, absolute_path, NULL));
 294 }
 295 
 296 void Arguments::add_instrument_agent(const char* name, char* options, bool absolute_path) {
 297   _agentList.add(new AgentLibrary(name, options, absolute_path, NULL, true));
 298 }
 299 
 300 // Late-binding agents not started via arguments
 301 void Arguments::add_loaded_agent(AgentLibrary *agentLib) {
 302   _agentList.add(agentLib);
 303 }
 304 
 305 void Arguments::add_loaded_agent(const char* name, char* options, bool absolute_path, void* os_lib) {
 306   _agentList.add(new AgentLibrary(name, options, absolute_path, os_lib));
 307 }
 308 
 309 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
 310 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
 311   return ((strncmp(option, property, len) == 0) &&
 312           (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
 313 }
 314 
 315 // Return true if property starts with "jdk.module." and its ensuing chars match
 316 // any of the reserved module properties.
 317 // property should be passed without the leading "-D".
 318 bool Arguments::is_internal_module_property(const char* property) {
 319   assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
 320   if  (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
 321     const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
 322     if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
 323         matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
 324         matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||
 325         matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
 326         matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
 327         matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
 328         matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
 329         matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN)) {
 330       return true;
 331     }
 332   }
 333   return false;
 334 }
 335 
 336 // Process java launcher properties.
 337 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 338   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 339   // sun.java.launcher.pid is defined.
 340   // Must do this before setting up other system properties,
 341   // as some of them may depend on launcher type.
 342   for (int index = 0; index < args->nOptions; index++) {
 343     const JavaVMOption* option = args->options + index;
 344     const char* tail;
 345 
 346     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 347       process_java_launcher_argument(tail, option->extraInfo);
 348       continue;
 349     }
 350     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 351       if (strcmp(tail, "true") == 0) {
 352         _sun_java_launcher_is_altjvm = true;
 353       }
 354       continue;
 355     }
 356     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 357       _sun_java_launcher_pid = atoi(tail);
 358       continue;
 359     }
 360   }
 361 }
 362 
 363 // Initialize system properties key and value.
 364 void Arguments::init_system_properties() {
 365 
 366   // Set up _system_boot_class_path which is not a property but
 367   // relies heavily on argument processing and the jdk.boot.class.path.append
 368   // property. It is used to store the underlying system boot class path.
 369   _system_boot_class_path = new PathString(NULL);
 370 
 371   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 372                                                            "Java Virtual Machine Specification",  false));
 373   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 374   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 375   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 376   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 377 
 378   // Following are JVMTI agent writable properties.
 379   // Properties values are set to NULL and they are
 380   // os specific they are initialized in os::init_system_properties_values().
 381   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 382   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 383   _java_home =  new SystemProperty("java.home", NULL,  true);
 384   _java_class_path = new SystemProperty("java.class.path", "",  true);
 385   // jdk.boot.class.path.append is a non-writeable, internal property.
 386   // It can only be set by either:
 387   //    - -Xbootclasspath/a:
 388   //    - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
 389   _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", "", false, true);
 390 
 391   // Add to System Property list.
 392   PropertyList_add(&_system_properties, _sun_boot_library_path);
 393   PropertyList_add(&_system_properties, _java_library_path);
 394   PropertyList_add(&_system_properties, _java_home);
 395   PropertyList_add(&_system_properties, _java_class_path);
 396   PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
 397 
 398   // Set OS specific system properties values
 399   os::init_system_properties_values();
 400 }
 401 
 402 // Update/Initialize System properties after JDK version number is known
 403 void Arguments::init_version_specific_system_properties() {
 404   enum { bufsz = 16 };
 405   char buffer[bufsz];
 406   const char* spec_vendor = "Oracle Corporation";
 407   uint32_t spec_version = JDK_Version::current().major_version();
 408 
 409   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 410 
 411   PropertyList_add(&_system_properties,
 412       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 413   PropertyList_add(&_system_properties,
 414       new SystemProperty("java.vm.specification.version", buffer, false));
 415   PropertyList_add(&_system_properties,
 416       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 417 }
 418 
 419 /*
 420  *  -XX argument processing:
 421  *
 422  *  -XX arguments are defined in several places, such as:
 423  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 424  *  -XX arguments are parsed in parse_argument().
 425  *  -XX argument bounds checking is done in check_vm_args_consistency().
 426  *
 427  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 428  *
 429  *      ALIASED: An option that is simply another name for another option. This is often
 430  *               part of the process of deprecating a flag, but not all aliases need
 431  *               to be deprecated.
 432  *
 433  *               Create an alias for an option by adding the old and new option names to the
 434  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 435  *
 436  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 437  *               support may be removed in the future. Both regular and aliased options may be
 438  *               deprecated.
 439  *
 440  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 441  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 442  *               Often an option "deprecated" in one major release will
 443  *               be made "obsolete" in the next. In this case the entry should also have its
 444  *               "obsolete_in" field set.
 445  *
 446  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 447  *               on the command line. A warning is printed to let the user know that option might not
 448  *               be accepted in the future.
 449  *
 450  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 451  *               table and setting the "obsolete_in" field.
 452  *
 453  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 454  *               to the current JDK version. The system will flatly refuse to admit the existence of
 455  *               the flag. This allows a flag to die automatically over JDK releases.
 456  *
 457  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 458  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 459  *                  - Newly obsolete or expired deprecated options should have their global variable
 460  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 461  *
 462  * Recommended approach for removing options:
 463  *
 464  * To remove options commonly used by customers (e.g. product, commercial -XX options), use
 465  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 466  *
 467  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 468  * a 2-step model adding major release numbers to the obsolete and expire columns.
 469  *
 470  * To change the name of an option, use the alias table as well as a 2-step
 471  * model adding major release numbers to the deprecate and expire columns.
 472  * Think twice about aliasing commonly used customer options.
 473  *
 474  * There are times when it is appropriate to leave a future release number as undefined.
 475  *
 476  * Tests:  Aliases should be tested in VMAliasOptions.java.
 477  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 478  */
 479 
 480 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 481 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 482 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 483 // the command-line as usual, but will issue a warning.
 484 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 485 // the command-line, while issuing a warning and ignoring the flag value.
 486 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 487 // existence of the flag.
 488 //
 489 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 490 // This table ensures that the handling of options will update automatically when the JDK
 491 // version is incremented, but the source code needs to be cleanup up manually:
 492 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 493 //   variable should be removed, as well as users of the variable.
 494 // - As "deprecated" options age into "obsolete" options, move the entry into the
 495 //   "Obsolete Flags" section of the table.
 496 // - All expired options should be removed from the table.
 497 static SpecialFlag const special_jvm_flags[] = {
 498   // -------------- Deprecated Flags --------------
 499   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 500   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 501   { "UseConcMarkSweepGC",           JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 502   { "AssumeMP",                     JDK_Version::jdk(10),JDK_Version::undefined(), JDK_Version::undefined() },
 503   { "MonitorInUseLists",            JDK_Version::jdk(10),JDK_Version::undefined(), JDK_Version::undefined() },
 504   { "MaxRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 505   { "MinRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 506   { "InitialRAMFraction",           JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 507   { "UseMembar",                    JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
 508   { "FastTLABRefill",               JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 509   { "SafepointSpinBeforeYield",     JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 510   { "DeferThrSuspendLoopCount",     JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 511   { "DeferPollingPageLoopCount",    JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 512   { "UseCGroupMemoryLimitForHeap",  JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::jdk(11) },
 513   { "IgnoreUnverifiableClassesDuringDump", JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 514   { "CheckEndorsedAndExtDirs",      JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 515 
 516   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 517   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8),  JDK_Version::undefined(), JDK_Version::undefined() },
 518   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
 519   { "MustCallLoadClassInternal",    JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
 520   { "UnsyncloadClass",              JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
 521 
 522   // -------------- Obsolete Flags - sorted by expired_in --------------
 523   { "ConvertSleepToYield",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 524   { "ConvertYieldToSleep",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 525   { "MinSleepInterval",              JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 526   { "CheckAssertionStatusDirectives",JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 527   { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 528   { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 529   { "SharedReadWriteSize",           JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 530   { "SharedReadOnlySize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 531   { "SharedMiscDataSize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 532   { "SharedMiscCodeSize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 533 
 534 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 535   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 536   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 537   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 538   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 539   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 540   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 541   { "BytecodeVerificationRemote",   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::undefined() },
 542 #endif
 543 
 544   { NULL, JDK_Version(0), JDK_Version(0) }
 545 };
 546 
 547 // Flags that are aliases for other flags.
 548 typedef struct {
 549   const char* alias_name;
 550   const char* real_name;
 551 } AliasedFlag;
 552 
 553 static AliasedFlag const aliased_jvm_flags[] = {
 554   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
 555   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 556   { NULL, NULL}
 557 };
 558 
 559 // NOTE: A compatibility request will be necessary for each alias to be removed.
 560 static AliasedLoggingFlag const aliased_logging_flags[] = {
 561   { "PrintCompressedOopsMode",   LogLevel::Info,  true,  LOG_TAGS(gc, heap, coops) },
 562   { "PrintSharedSpaces",         LogLevel::Info,  true,  LOG_TAGS(cds) },
 563   { "TraceBiasedLocking",        LogLevel::Info,  true,  LOG_TAGS(biasedlocking) },
 564   { "TraceClassLoading",         LogLevel::Info,  true,  LOG_TAGS(class, load) },
 565   { "TraceClassLoadingPreorder", LogLevel::Debug, true,  LOG_TAGS(class, preorder) },
 566   { "TraceClassPaths",           LogLevel::Info,  true,  LOG_TAGS(class, path) },
 567   { "TraceClassResolution",      LogLevel::Debug, true,  LOG_TAGS(class, resolve) },
 568   { "TraceClassUnloading",       LogLevel::Info,  true,  LOG_TAGS(class, unload) },
 569   { "TraceExceptions",           LogLevel::Info,  true,  LOG_TAGS(exceptions) },
 570   { "TraceLoaderConstraints",    LogLevel::Info,  true,  LOG_TAGS(class, loader, constraints) },
 571   { "TraceMonitorInflation",     LogLevel::Debug, true,  LOG_TAGS(monitorinflation) },
 572   { "TraceSafepointCleanupTime", LogLevel::Info,  true,  LOG_TAGS(safepoint, cleanup) },
 573   { "TraceJVMTIObjectTagging",   LogLevel::Debug, true,  LOG_TAGS(jvmti, objecttagging) },
 574   { "TraceRedefineClasses",      LogLevel::Info,  false, LOG_TAGS(redefine, class) },
 575   { NULL,                        LogLevel::Off,   false, LOG_TAGS(_NO_TAG) }
 576 };
 577 
 578 #ifndef PRODUCT
 579 // These options are removed in jdk9. Remove this code for jdk10.
 580 static AliasedFlag const removed_develop_logging_flags[] = {
 581   { "TraceClassInitialization",   "-Xlog:class+init" },
 582   { "TraceClassLoaderData",       "-Xlog:class+loader+data" },
 583   { "TraceDefaultMethods",        "-Xlog:defaultmethods=debug" },
 584   { "TraceItables",               "-Xlog:itables=debug" },
 585   { "TraceMonitorMismatch",       "-Xlog:monitormismatch=info" },
 586   { "TraceSafepoint",             "-Xlog:safepoint=debug" },
 587   { "TraceStartupTime",           "-Xlog:startuptime" },
 588   { "TraceVMOperation",           "-Xlog:vmoperation=debug" },
 589   { "PrintVtables",               "-Xlog:vtables=debug" },
 590   { "VerboseVerification",        "-Xlog:verification" },
 591   { NULL, NULL }
 592 };
 593 #endif //PRODUCT
 594 
 595 // Return true if "v" is less than "other", where "other" may be "undefined".
 596 static bool version_less_than(JDK_Version v, JDK_Version other) {
 597   assert(!v.is_undefined(), "must be defined");
 598   if (!other.is_undefined() && v.compare(other) >= 0) {
 599     return false;
 600   } else {
 601     return true;
 602   }
 603 }
 604 
 605 extern bool lookup_special_flag_ext(const char *flag_name, SpecialFlag& flag);
 606 
 607 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 608   // Allow extensions to have priority
 609   if (lookup_special_flag_ext(flag_name, flag)) {
 610     return true;
 611   }
 612 
 613   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 614     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 615       flag = special_jvm_flags[i];
 616       return true;
 617     }
 618   }
 619   return false;
 620 }
 621 
 622 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 623   assert(version != NULL, "Must provide a version buffer");
 624   SpecialFlag flag;
 625   if (lookup_special_flag(flag_name, flag)) {
 626     if (!flag.obsolete_in.is_undefined()) {
 627       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 628         *version = flag.obsolete_in;
 629         return true;
 630       }
 631     }
 632   }
 633   return false;
 634 }
 635 
 636 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 637   assert(version != NULL, "Must provide a version buffer");
 638   SpecialFlag flag;
 639   if (lookup_special_flag(flag_name, flag)) {
 640     if (!flag.deprecated_in.is_undefined()) {
 641       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 642           version_less_than(JDK_Version::current(), flag.expired_in)) {
 643         *version = flag.deprecated_in;
 644         return 1;
 645       } else {
 646         return -1;
 647       }
 648     }
 649   }
 650   return 0;
 651 }
 652 
 653 #ifndef PRODUCT
 654 const char* Arguments::removed_develop_logging_flag_name(const char* name){
 655   for (size_t i = 0; removed_develop_logging_flags[i].alias_name != NULL; i++) {
 656     const AliasedFlag& flag = removed_develop_logging_flags[i];
 657     if (strcmp(flag.alias_name, name) == 0) {
 658       return flag.real_name;
 659     }
 660   }
 661   return NULL;
 662 }
 663 #endif // PRODUCT
 664 
 665 const char* Arguments::real_flag_name(const char *flag_name) {
 666   for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {
 667     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 668     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 669         return flag_status.real_name;
 670     }
 671   }
 672   return flag_name;
 673 }
 674 
 675 #ifdef ASSERT
 676 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 677   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 678     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 679       return true;
 680     }
 681   }
 682   return false;
 683 }
 684 
 685 // Verifies the correctness of the entries in the special_jvm_flags table.
 686 // If there is a semantic error (i.e. a bug in the table) such as the obsoletion
 687 // version being earlier than the deprecation version, then a warning is issued
 688 // and verification fails - by returning false. If it is detected that the table
 689 // is out of date, with respect to the current version, then a warning is issued
 690 // but verification does not fail. This allows the VM to operate when the version
 691 // is first updated, without needing to update all the impacted flags at the
 692 // same time.
 693 static bool verify_special_jvm_flags() {
 694   bool success = true;
 695   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 696     const SpecialFlag& flag = special_jvm_flags[i];
 697     if (lookup_special_flag(flag.name, i)) {
 698       warning("Duplicate special flag declaration \"%s\"", flag.name);
 699       success = false;
 700     }
 701     if (flag.deprecated_in.is_undefined() &&
 702         flag.obsolete_in.is_undefined()) {
 703       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 704       success = false;
 705     }
 706 
 707     if (!flag.deprecated_in.is_undefined()) {
 708       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 709         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 710         success = false;
 711       }
 712 
 713       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 714         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 715         success = false;
 716       }
 717     }
 718 
 719     if (!flag.obsolete_in.is_undefined()) {
 720       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 721         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 722         success = false;
 723       }
 724 
 725       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 726       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 727         if (Flag::find_flag(flag.name) != NULL) {
 728           warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 729         }
 730       }
 731     }
 732 
 733     if (!flag.expired_in.is_undefined()) {
 734       // if flag has become expired it should not have a "globals" flag defined anymore.
 735       if (!version_less_than(JDK_Version::current(), flag.expired_in)) {
 736         if (Flag::find_flag(flag.name) != NULL) {
 737           warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 738         }
 739       }
 740     }
 741 
 742   }
 743   return success;
 744 }
 745 #endif
 746 
 747 // Parses a size specification string.
 748 bool Arguments::atojulong(const char *s, julong* result) {
 749   julong n = 0;
 750 
 751   // First char must be a digit. Don't allow negative numbers or leading spaces.
 752   if (!isdigit(*s)) {
 753     return false;
 754   }
 755 
 756   bool is_hex = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
 757   char* remainder;
 758   errno = 0;
 759   n = strtoull(s, &remainder, (is_hex ? 16 : 10));
 760   if (errno != 0) {
 761     return false;
 762   }
 763 
 764   // Fail if no number was read at all or if the remainder contains more than a single non-digit character.
 765   if (remainder == s || strlen(remainder) > 1) {
 766     return false;
 767   }
 768 
 769   switch (*remainder) {
 770     case 'T': case 't':
 771       *result = n * G * K;
 772       // Check for overflow.
 773       if (*result/((julong)G * K) != n) return false;
 774       return true;
 775     case 'G': case 'g':
 776       *result = n * G;
 777       if (*result/G != n) return false;
 778       return true;
 779     case 'M': case 'm':
 780       *result = n * M;
 781       if (*result/M != n) return false;
 782       return true;
 783     case 'K': case 'k':
 784       *result = n * K;
 785       if (*result/K != n) return false;
 786       return true;
 787     case '\0':
 788       *result = n;
 789       return true;
 790     default:
 791       return false;
 792   }
 793 }
 794 
 795 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {
 796   if (size < min_size) return arg_too_small;
 797   if (size > max_size) return arg_too_big;
 798   return arg_in_range;
 799 }
 800 
 801 // Describe an argument out of range error
 802 void Arguments::describe_range_error(ArgsRange errcode) {
 803   switch(errcode) {
 804   case arg_too_big:
 805     jio_fprintf(defaultStream::error_stream(),
 806                 "The specified size exceeds the maximum "
 807                 "representable size.\n");
 808     break;
 809   case arg_too_small:
 810   case arg_unreadable:
 811   case arg_in_range:
 812     // do nothing for now
 813     break;
 814   default:
 815     ShouldNotReachHere();
 816   }
 817 }
 818 
 819 static bool set_bool_flag(const char* name, bool value, Flag::Flags origin) {
 820   if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
 821     return true;
 822   } else {
 823     return false;
 824   }
 825 }
 826 
 827 static bool set_fp_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 828   char* end;
 829   errno = 0;
 830   double v = strtod(value, &end);
 831   if ((errno != 0) || (*end != 0)) {
 832     return false;
 833   }
 834 
 835   if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
 836     return true;
 837   }
 838   return false;
 839 }
 840 
 841 static bool set_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 842   julong v;
 843   int int_v;
 844   intx intx_v;
 845   bool is_neg = false;
 846   Flag* result = Flag::find_flag(name, strlen(name));
 847 
 848   if (result == NULL) {
 849     return false;
 850   }
 851 
 852   // Check the sign first since atojulong() parses only unsigned values.
 853   if (*value == '-') {
 854     if (!result->is_intx() && !result->is_int()) {
 855       return false;
 856     }
 857     value++;
 858     is_neg = true;
 859   }
 860   if (!Arguments::atojulong(value, &v)) {
 861     return false;
 862   }
 863   if (result->is_int()) {
 864     int_v = (int) v;
 865     if (is_neg) {
 866       int_v = -int_v;
 867     }
 868     return CommandLineFlags::intAtPut(result, &int_v, origin) == Flag::SUCCESS;
 869   } else if (result->is_uint()) {
 870     uint uint_v = (uint) v;
 871     return CommandLineFlags::uintAtPut(result, &uint_v, origin) == Flag::SUCCESS;
 872   } else if (result->is_intx()) {
 873     intx_v = (intx) v;
 874     if (is_neg) {
 875       intx_v = -intx_v;
 876     }
 877     return CommandLineFlags::intxAtPut(result, &intx_v, origin) == Flag::SUCCESS;
 878   } else if (result->is_uintx()) {
 879     uintx uintx_v = (uintx) v;
 880     return CommandLineFlags::uintxAtPut(result, &uintx_v, origin) == Flag::SUCCESS;
 881   } else if (result->is_uint64_t()) {
 882     uint64_t uint64_t_v = (uint64_t) v;
 883     return CommandLineFlags::uint64_tAtPut(result, &uint64_t_v, origin) == Flag::SUCCESS;
 884   } else if (result->is_size_t()) {
 885     size_t size_t_v = (size_t) v;
 886     return CommandLineFlags::size_tAtPut(result, &size_t_v, origin) == Flag::SUCCESS;
 887   } else if (result->is_double()) {
 888     double double_v = (double) v;
 889     return CommandLineFlags::doubleAtPut(result, &double_v, origin) == Flag::SUCCESS;
 890   } else {
 891     return false;
 892   }
 893 }
 894 
 895 static bool set_string_flag(const char* name, const char* value, Flag::Flags origin) {
 896   if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
 897   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 898   FREE_C_HEAP_ARRAY(char, value);
 899   return true;
 900 }
 901 
 902 static bool append_to_string_flag(const char* name, const char* new_value, Flag::Flags origin) {
 903   const char* old_value = "";
 904   if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
 905   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 906   size_t new_len = strlen(new_value);
 907   const char* value;
 908   char* free_this_too = NULL;
 909   if (old_len == 0) {
 910     value = new_value;
 911   } else if (new_len == 0) {
 912     value = old_value;
 913   } else {
 914      size_t length = old_len + 1 + new_len + 1;
 915      char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
 916     // each new setting adds another LINE to the switch:
 917     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
 918     value = buf;
 919     free_this_too = buf;
 920   }
 921   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 922   // CommandLineFlags always returns a pointer that needs freeing.
 923   FREE_C_HEAP_ARRAY(char, value);
 924   if (free_this_too != NULL) {
 925     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 926     FREE_C_HEAP_ARRAY(char, free_this_too);
 927   }
 928   return true;
 929 }
 930 
 931 const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {
 932   const char* real_name = real_flag_name(arg);
 933   JDK_Version since = JDK_Version();
 934   switch (is_deprecated_flag(arg, &since)) {
 935     case -1:
 936       return NULL; // obsolete or expired, don't process normally
 937     case 0:
 938       return real_name;
 939     case 1: {
 940       if (warn) {
 941         char version[256];
 942         since.to_string(version, sizeof(version));
 943         if (real_name != arg) {
 944           warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 945                   arg, version, real_name);
 946         } else {
 947           warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 948                   arg, version);
 949         }
 950       }
 951       return real_name;
 952     }
 953   }
 954   ShouldNotReachHere();
 955   return NULL;
 956 }
 957 
 958 void log_deprecated_flag(const char* name, bool on, AliasedLoggingFlag alf) {
 959   LogTagType tagSet[] = {alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5};
 960   // Set tagset string buffer at max size of 256, large enough for any alias tagset
 961   const int max_tagset_size = 256;
 962   int max_tagset_len = max_tagset_size - 1;
 963   char tagset_buffer[max_tagset_size];
 964   tagset_buffer[0] = '\0';
 965 
 966   // Write tag-set for aliased logging option, in string list form
 967   int max_tags = sizeof(tagSet)/sizeof(tagSet[0]);
 968   for (int i = 0; i < max_tags && tagSet[i] != LogTag::__NO_TAG; i++) {
 969     if (i > 0) {
 970       strncat(tagset_buffer, "+", max_tagset_len - strlen(tagset_buffer));
 971     }
 972     strncat(tagset_buffer, LogTag::name(tagSet[i]), max_tagset_len - strlen(tagset_buffer));
 973   }
 974   if (!alf.exactMatch) {
 975       strncat(tagset_buffer, "*", max_tagset_len - strlen(tagset_buffer));
 976   }
 977   log_warning(arguments)("-XX:%s%s is deprecated. Will use -Xlog:%s=%s instead.",
 978                          (on) ? "+" : "-",
 979                          name,
 980                          tagset_buffer,
 981                          (on) ? LogLevel::name(alf.level) : "off");
 982 }
 983 
 984 AliasedLoggingFlag Arguments::catch_logging_aliases(const char* name, bool on){
 985   for (size_t i = 0; aliased_logging_flags[i].alias_name != NULL; i++) {
 986     const AliasedLoggingFlag& alf = aliased_logging_flags[i];
 987     if (strcmp(alf.alias_name, name) == 0) {
 988       log_deprecated_flag(name, on, alf);
 989       return alf;
 990     }
 991   }
 992   AliasedLoggingFlag a = {NULL, LogLevel::Off, false, LOG_TAGS(_NO_TAG)};
 993   return a;
 994 }
 995 
 996 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
 997 
 998   // range of acceptable characters spelled out for portability reasons
 999 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
1000 #define BUFLEN 255
1001   char name[BUFLEN+1];
1002   char dummy;
1003   const char* real_name;
1004   bool warn_if_deprecated = true;
1005 
1006   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1007     AliasedLoggingFlag alf = catch_logging_aliases(name, false);
1008     if (alf.alias_name != NULL){
1009       LogConfiguration::configure_stdout(LogLevel::Off, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1010       return true;
1011     }
1012     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1013     if (real_name == NULL) {
1014       return false;
1015     }
1016     return set_bool_flag(real_name, false, origin);
1017   }
1018   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1019     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1020     if (alf.alias_name != NULL){
1021       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1022       return true;
1023     }
1024     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1025     if (real_name == NULL) {
1026       return false;
1027     }
1028     return set_bool_flag(real_name, true, origin);
1029   }
1030 
1031   char punct;
1032   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
1033     const char* value = strchr(arg, '=') + 1;
1034     Flag* flag;
1035 
1036     // this scanf pattern matches both strings (handled here) and numbers (handled later))
1037     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1038     if (alf.alias_name != NULL) {
1039       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1040       return true;
1041     }
1042     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1043     if (real_name == NULL) {
1044       return false;
1045     }
1046     flag = Flag::find_flag(real_name);
1047     if (flag != NULL && flag->is_ccstr()) {
1048       if (flag->ccstr_accumulates()) {
1049         return append_to_string_flag(real_name, value, origin);
1050       } else {
1051         if (value[0] == '\0') {
1052           value = NULL;
1053         }
1054         return set_string_flag(real_name, value, origin);
1055       }
1056     } else {
1057       warn_if_deprecated = false; // if arg is deprecated, we've already done warning...
1058     }
1059   }
1060 
1061   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
1062     const char* value = strchr(arg, '=') + 1;
1063     // -XX:Foo:=xxx will reset the string flag to the given value.
1064     if (value[0] == '\0') {
1065       value = NULL;
1066     }
1067     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1068     if (real_name == NULL) {
1069       return false;
1070     }
1071     return set_string_flag(real_name, value, origin);
1072   }
1073 
1074 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"
1075 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
1076 #define        NUMBER_RANGE    "[0123456789eE+-]"
1077   char value[BUFLEN + 1];
1078   char value2[BUFLEN + 1];
1079   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
1080     // Looks like a floating-point number -- try again with more lenient format string
1081     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
1082       real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1083       if (real_name == NULL) {
1084         return false;
1085       }
1086       return set_fp_numeric_flag(real_name, value, origin);
1087     }
1088   }
1089 
1090 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
1091   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
1092     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1093     if (real_name == NULL) {
1094       return false;
1095     }
1096     return set_numeric_flag(real_name, value, origin);
1097   }
1098 
1099   return false;
1100 }
1101 
1102 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
1103   assert(bldarray != NULL, "illegal argument");
1104 
1105   if (arg == NULL) {
1106     return;
1107   }
1108 
1109   int new_count = *count + 1;
1110 
1111   // expand the array and add arg to the last element
1112   if (*bldarray == NULL) {
1113     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
1114   } else {
1115     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
1116   }
1117   (*bldarray)[*count] = os::strdup_check_oom(arg);
1118   *count = new_count;
1119 }
1120 
1121 void Arguments::build_jvm_args(const char* arg) {
1122   add_string(&_jvm_args_array, &_num_jvm_args, arg);
1123 }
1124 
1125 void Arguments::build_jvm_flags(const char* arg) {
1126   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1127 }
1128 
1129 // utility function to return a string that concatenates all
1130 // strings in a given char** array
1131 const char* Arguments::build_resource_string(char** args, int count) {
1132   if (args == NULL || count == 0) {
1133     return NULL;
1134   }
1135   size_t length = 0;
1136   for (int i = 0; i < count; i++) {
1137     length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
1138   }
1139   char* s = NEW_RESOURCE_ARRAY(char, length);
1140   char* dst = s;
1141   for (int j = 0; j < count; j++) {
1142     size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
1143     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
1144     dst += offset;
1145     length -= offset;
1146   }
1147   return (const char*) s;
1148 }
1149 
1150 void Arguments::print_on(outputStream* st) {
1151   st->print_cr("VM Arguments:");
1152   if (num_jvm_flags() > 0) {
1153     st->print("jvm_flags: "); print_jvm_flags_on(st);
1154     st->cr();
1155   }
1156   if (num_jvm_args() > 0) {
1157     st->print("jvm_args: "); print_jvm_args_on(st);
1158     st->cr();
1159   }
1160   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1161   if (_java_class_path != NULL) {
1162     char* path = _java_class_path->value();
1163     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
1164   }
1165   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1166 }
1167 
1168 void Arguments::print_summary_on(outputStream* st) {
1169   // Print the command line.  Environment variables that are helpful for
1170   // reproducing the problem are written later in the hs_err file.
1171   // flags are from setting file
1172   if (num_jvm_flags() > 0) {
1173     st->print_raw("Settings File: ");
1174     print_jvm_flags_on(st);
1175     st->cr();
1176   }
1177   // args are the command line and environment variable arguments.
1178   st->print_raw("Command Line: ");
1179   if (num_jvm_args() > 0) {
1180     print_jvm_args_on(st);
1181   }
1182   // this is the classfile and any arguments to the java program
1183   if (java_command() != NULL) {
1184     st->print("%s", java_command());
1185   }
1186   st->cr();
1187 }
1188 
1189 void Arguments::print_jvm_flags_on(outputStream* st) {
1190   if (_num_jvm_flags > 0) {
1191     for (int i=0; i < _num_jvm_flags; i++) {
1192       st->print("%s ", _jvm_flags_array[i]);
1193     }
1194   }
1195 }
1196 
1197 void Arguments::print_jvm_args_on(outputStream* st) {
1198   if (_num_jvm_args > 0) {
1199     for (int i=0; i < _num_jvm_args; i++) {
1200       st->print("%s ", _jvm_args_array[i]);
1201     }
1202   }
1203 }
1204 
1205 bool Arguments::process_argument(const char* arg,
1206                                  jboolean ignore_unrecognized,
1207                                  Flag::Flags origin) {
1208   JDK_Version since = JDK_Version();
1209 
1210   if (parse_argument(arg, origin)) {
1211     return true;
1212   }
1213 
1214   // Determine if the flag has '+', '-', or '=' characters.
1215   bool has_plus_minus = (*arg == '+' || *arg == '-');
1216   const char* const argname = has_plus_minus ? arg + 1 : arg;
1217 
1218   size_t arg_len;
1219   const char* equal_sign = strchr(argname, '=');
1220   if (equal_sign == NULL) {
1221     arg_len = strlen(argname);
1222   } else {
1223     arg_len = equal_sign - argname;
1224   }
1225 
1226   // Only make the obsolete check for valid arguments.
1227   if (arg_len <= BUFLEN) {
1228     // Construct a string which consists only of the argument name without '+', '-', or '='.
1229     char stripped_argname[BUFLEN+1]; // +1 for '\0'
1230     jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1231     if (is_obsolete_flag(stripped_argname, &since)) {
1232       char version[256];
1233       since.to_string(version, sizeof(version));
1234       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1235       return true;
1236     }
1237 #ifndef PRODUCT
1238     else {
1239       const char* replacement;
1240       if ((replacement = removed_develop_logging_flag_name(stripped_argname)) != NULL){
1241         log_warning(arguments)("%s has been removed. Please use %s instead.",
1242                                stripped_argname,
1243                                replacement);
1244         return false;
1245       }
1246     }
1247 #endif //PRODUCT
1248   }
1249 
1250   // For locked flags, report a custom error message if available.
1251   // Otherwise, report the standard unrecognized VM option.
1252   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
1253   if (found_flag != NULL) {
1254     char locked_message_buf[BUFLEN];
1255     Flag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1256     if (strlen(locked_message_buf) == 0) {
1257       if (found_flag->is_bool() && !has_plus_minus) {
1258         jio_fprintf(defaultStream::error_stream(),
1259           "Missing +/- setting for VM option '%s'\n", argname);
1260       } else if (!found_flag->is_bool() && has_plus_minus) {
1261         jio_fprintf(defaultStream::error_stream(),
1262           "Unexpected +/- setting in VM option '%s'\n", argname);
1263       } else {
1264         jio_fprintf(defaultStream::error_stream(),
1265           "Improperly specified VM option '%s'\n", argname);
1266       }
1267     } else {
1268 #ifdef PRODUCT
1269       bool mismatched = ((msg_type == Flag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1270                          (msg_type == Flag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1271       if (ignore_unrecognized && mismatched) {
1272         return true;
1273       }
1274 #endif
1275       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1276     }
1277   } else {
1278     if (ignore_unrecognized) {
1279       return true;
1280     }
1281     jio_fprintf(defaultStream::error_stream(),
1282                 "Unrecognized VM option '%s'\n", argname);
1283     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
1284     if (fuzzy_matched != NULL) {
1285       jio_fprintf(defaultStream::error_stream(),
1286                   "Did you mean '%s%s%s'? ",
1287                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1288                   fuzzy_matched->_name,
1289                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1290     }
1291   }
1292 
1293   // allow for commandline "commenting out" options like -XX:#+Verbose
1294   return arg[0] == '#';
1295 }
1296 
1297 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1298   FILE* stream = fopen(file_name, "rb");
1299   if (stream == NULL) {
1300     if (should_exist) {
1301       jio_fprintf(defaultStream::error_stream(),
1302                   "Could not open settings file %s\n", file_name);
1303       return false;
1304     } else {
1305       return true;
1306     }
1307   }
1308 
1309   char token[1024];
1310   int  pos = 0;
1311 
1312   bool in_white_space = true;
1313   bool in_comment     = false;
1314   bool in_quote       = false;
1315   char quote_c        = 0;
1316   bool result         = true;
1317 
1318   int c = getc(stream);
1319   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1320     if (in_white_space) {
1321       if (in_comment) {
1322         if (c == '\n') in_comment = false;
1323       } else {
1324         if (c == '#') in_comment = true;
1325         else if (!isspace(c)) {
1326           in_white_space = false;
1327           token[pos++] = c;
1328         }
1329       }
1330     } else {
1331       if (c == '\n' || (!in_quote && isspace(c))) {
1332         // token ends at newline, or at unquoted whitespace
1333         // this allows a way to include spaces in string-valued options
1334         token[pos] = '\0';
1335         logOption(token);
1336         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1337         build_jvm_flags(token);
1338         pos = 0;
1339         in_white_space = true;
1340         in_quote = false;
1341       } else if (!in_quote && (c == '\'' || c == '"')) {
1342         in_quote = true;
1343         quote_c = c;
1344       } else if (in_quote && (c == quote_c)) {
1345         in_quote = false;
1346       } else {
1347         token[pos++] = c;
1348       }
1349     }
1350     c = getc(stream);
1351   }
1352   if (pos > 0) {
1353     token[pos] = '\0';
1354     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1355     build_jvm_flags(token);
1356   }
1357   fclose(stream);
1358   return result;
1359 }
1360 
1361 //=============================================================================================================
1362 // Parsing of properties (-D)
1363 
1364 const char* Arguments::get_property(const char* key) {
1365   return PropertyList_get_value(system_properties(), key);
1366 }
1367 
1368 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1369   const char* eq = strchr(prop, '=');
1370   const char* key;
1371   const char* value = "";
1372 
1373   if (eq == NULL) {
1374     // property doesn't have a value, thus use passed string
1375     key = prop;
1376   } else {
1377     // property have a value, thus extract it and save to the
1378     // allocated string
1379     size_t key_len = eq - prop;
1380     char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1381 
1382     jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1383     key = tmp_key;
1384 
1385     value = &prop[key_len + 1];
1386   }
1387 
1388   if (strcmp(key, "java.compiler") == 0) {
1389     process_java_compiler_argument(value);
1390     // Record value in Arguments, but let it get passed to Java.
1391   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
1392              strcmp(key, "sun.java.launcher.pid") == 0) {
1393     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
1394     // private and are processed in process_sun_java_launcher_properties();
1395     // the sun.java.launcher property is passed on to the java application
1396   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1397     // append is true, writable is true, internal is false
1398     PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1399                             WriteableProperty, ExternalProperty);
1400   } else {
1401     if (strcmp(key, "sun.java.command") == 0) {
1402       char *old_java_command = _java_command;
1403       _java_command = os::strdup_check_oom(value, mtArguments);
1404       if (old_java_command != NULL) {
1405         os::free(old_java_command);
1406       }
1407     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1408       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1409       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1410       // its value without going through the property list or making a Java call.
1411       _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1412       if (old_java_vendor_url_bug != DEFAULT_VENDOR_URL_BUG) {
1413         assert(old_java_vendor_url_bug != NULL, "_java_vendor_url_bug is NULL");
1414         os::free((void *)old_java_vendor_url_bug);
1415       }
1416     }
1417 
1418     // Create new property and add at the end of the list
1419     PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1420   }
1421 
1422   if (key != prop) {
1423     // SystemProperty copy passed value, thus free previously allocated
1424     // memory
1425     FreeHeap((void *)key);
1426   }
1427 
1428   return true;
1429 }
1430 
1431 #if INCLUDE_CDS
1432 void Arguments::check_unsupported_dumping_properties() {
1433   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
1434   const char* unsupported_properties[] = { "jdk.module.main",
1435                                            "jdk.module.limitmods",
1436                                            "jdk.module.path",
1437                                            "jdk.module.upgrade.path",
1438                                            "jdk.module.patch.0" };
1439   const char* unsupported_options[] = { "-m", // cannot use at dump time
1440                                         "--limit-modules", // ignored at dump time
1441                                         "--module-path", // ignored at dump time
1442                                         "--upgrade-module-path", // ignored at dump time
1443                                         "--patch-module" // ignored at dump time
1444                                       };
1445   assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1446   // If a vm option is found in the unsupported_options array with index less than the info_idx,
1447   // vm will exit with an error message. Otherwise, it will print an informational message if
1448   // -Xlog:cds is enabled.
1449   uint info_idx = 1;
1450   SystemProperty* sp = system_properties();
1451   while (sp != NULL) {
1452     for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1453       if (strcmp(sp->key(), unsupported_properties[i]) == 0) {
1454         if (i < info_idx) {
1455           vm_exit_during_initialization(
1456             "Cannot use the following option when dumping the shared archive", unsupported_options[i]);
1457         } else {
1458           log_info(cds)("Info: the %s option is ignored when dumping the shared archive",
1459                         unsupported_options[i]);
1460         }
1461       }
1462     }
1463     sp = sp->next();
1464   }
1465 
1466   // Check for an exploded module build in use with -Xshare:dump.
1467   if (!has_jimage()) {
1468     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
1469   }
1470 }
1471 #endif
1472 
1473 //===========================================================================================================
1474 // Setting int/mixed/comp mode flags
1475 
1476 void Arguments::set_mode_flags(Mode mode) {
1477   // Set up default values for all flags.
1478   // If you add a flag to any of the branches below,
1479   // add a default value for it here.
1480   set_java_compiler(false);
1481   _mode                      = mode;
1482 
1483   // Ensure Agent_OnLoad has the correct initial values.
1484   // This may not be the final mode; mode may change later in onload phase.
1485   PropertyList_unique_add(&_system_properties, "java.vm.info",
1486                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1487 
1488   UseInterpreter             = true;
1489   UseCompiler                = true;
1490   UseLoopCounter             = true;
1491 
1492   // Default values may be platform/compiler dependent -
1493   // use the saved values
1494   ClipInlining               = Arguments::_ClipInlining;
1495   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1496   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1497   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1498   if (TieredCompilation) {
1499     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1500       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1501     }
1502     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1503       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1504     }
1505   }
1506 
1507   // Change from defaults based on mode
1508   switch (mode) {
1509   default:
1510     ShouldNotReachHere();
1511     break;
1512   case _int:
1513     UseCompiler              = false;
1514     UseLoopCounter           = false;
1515     AlwaysCompileLoopMethods = false;
1516     UseOnStackReplacement    = false;
1517     break;
1518   case _mixed:
1519     // same as default
1520     break;
1521   case _comp:
1522     UseInterpreter           = false;
1523     BackgroundCompilation    = false;
1524     ClipInlining             = false;
1525     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1526     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1527     // compile a level 4 (C2) and then continue executing it.
1528     if (TieredCompilation) {
1529       Tier3InvokeNotifyFreqLog = 0;
1530       Tier4InvocationThreshold = 0;
1531     }
1532     break;
1533   }
1534 }
1535 
1536 // Conflict: required to use shared spaces (-Xshare:on), but
1537 // incompatible command line options were chosen.
1538 static void no_shared_spaces(const char* message) {
1539   if (RequireSharedSpaces) {
1540     jio_fprintf(defaultStream::error_stream(),
1541       "Class data sharing is inconsistent with other specified options.\n");
1542     vm_exit_during_initialization("Unable to use shared archive.", message);
1543   } else {
1544     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1545   }
1546 }
1547 
1548 // Returns threshold scaled with the value of scale.
1549 // If scale < 0.0, threshold is returned without scaling.
1550 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1551   if (scale == 1.0 || scale < 0.0) {
1552     return threshold;
1553   } else {
1554     return (intx)(threshold * scale);
1555   }
1556 }
1557 
1558 // Returns freq_log scaled with the value of scale.
1559 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1560 // If scale < 0.0, freq_log is returned without scaling.
1561 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1562   // Check if scaling is necessary or if negative value was specified.
1563   if (scale == 1.0 || scale < 0.0) {
1564     return freq_log;
1565   }
1566   // Check values to avoid calculating log2 of 0.
1567   if (scale == 0.0 || freq_log == 0) {
1568     return 0;
1569   }
1570   // Determine the maximum notification frequency value currently supported.
1571   // The largest mask value that the interpreter/C1 can handle is
1572   // of length InvocationCounter::number_of_count_bits. Mask values are always
1573   // one bit shorter then the value of the notification frequency. Set
1574   // max_freq_bits accordingly.
1575   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1576   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1577   if (scaled_freq == 0) {
1578     // Return 0 right away to avoid calculating log2 of 0.
1579     return 0;
1580   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1581     return max_freq_bits;
1582   } else {
1583     return log2_intptr(scaled_freq);
1584   }
1585 }
1586 
1587 void Arguments::set_tiered_flags() {
1588   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1589   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1590     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1591   }
1592   if (CompilationPolicyChoice < 2) {
1593     vm_exit_during_initialization(
1594       "Incompatible compilation policy selected", NULL);
1595   }
1596   // Increase the code cache size - tiered compiles a lot more.
1597   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1598     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1599                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1600   }
1601   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1602   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1603     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1604   }
1605   if (!UseInterpreter) { // -Xcomp
1606     Tier3InvokeNotifyFreqLog = 0;
1607     Tier4InvocationThreshold = 0;
1608   }
1609 
1610   if (CompileThresholdScaling < 0) {
1611     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1612   }
1613 
1614   // Scale tiered compilation thresholds.
1615   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1616   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1617     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1618     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1619 
1620     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1621     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1622     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1623     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1624 
1625     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1626     // once these thresholds become supported.
1627 
1628     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1629     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1630 
1631     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1632     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1633 
1634     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1635 
1636     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1637     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1638     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1639     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1640   }
1641 }
1642 
1643 void set_object_alignment() {
1644   // Object alignment.
1645   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1646   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1647   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1648   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1649   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1650   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1651 
1652   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1653   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1654 
1655   // Oop encoding heap max
1656   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1657 
1658   if (SurvivorAlignmentInBytes == 0) {
1659     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1660   }
1661 }
1662 
1663 size_t Arguments::max_heap_for_compressed_oops() {
1664   // Avoid sign flip.
1665   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1666   // We need to fit both the NULL page and the heap into the memory budget, while
1667   // keeping alignment constraints of the heap. To guarantee the latter, as the
1668   // NULL page is located before the heap, we pad the NULL page to the conservative
1669   // maximum alignment that the GC may ever impose upon the heap.
1670   size_t displacement_due_to_null_page = align_up((size_t)os::vm_page_size(),
1671                                                   _conservative_max_heap_alignment);
1672 
1673   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1674   NOT_LP64(ShouldNotReachHere(); return 0);
1675 }
1676 
1677 void Arguments::set_use_compressed_oops() {
1678 #ifndef ZERO
1679 #ifdef _LP64
1680   // MaxHeapSize is not set up properly at this point, but
1681   // the only value that can override MaxHeapSize if we are
1682   // to use UseCompressedOops is InitialHeapSize.
1683   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1684 
1685   if (max_heap_size <= max_heap_for_compressed_oops()) {
1686 #if !defined(COMPILER1) || defined(TIERED)
1687     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1688       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1689     }
1690 #endif
1691   } else {
1692     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1693       warning("Max heap size too large for Compressed Oops");
1694       FLAG_SET_DEFAULT(UseCompressedOops, false);
1695       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1696     }
1697   }
1698 #endif // _LP64
1699 #endif // ZERO
1700 }
1701 
1702 
1703 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1704 // set_use_compressed_oops().
1705 void Arguments::set_use_compressed_klass_ptrs() {
1706 #ifndef ZERO
1707 #ifdef _LP64
1708   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1709   if (!UseCompressedOops) {
1710     if (UseCompressedClassPointers) {
1711       warning("UseCompressedClassPointers requires UseCompressedOops");
1712     }
1713     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1714   } else {
1715     // Turn on UseCompressedClassPointers too
1716     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1717       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1718     }
1719     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1720     if (UseCompressedClassPointers) {
1721       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1722         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1723         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1724       }
1725     }
1726   }
1727 #endif // _LP64
1728 #endif // !ZERO
1729 }
1730 
1731 void Arguments::set_conservative_max_heap_alignment() {
1732   // The conservative maximum required alignment for the heap is the maximum of
1733   // the alignments imposed by several sources: any requirements from the heap
1734   // itself, the collector policy and the maximum page size we may run the VM
1735   // with.
1736   size_t heap_alignment = GCArguments::arguments()->conservative_max_heap_alignment();
1737   _conservative_max_heap_alignment = MAX4(heap_alignment,
1738                                           (size_t)os::vm_allocation_granularity(),
1739                                           os::max_page_size(),
1740                                           CollectorPolicy::compute_heap_alignment());
1741 }
1742 
1743 #ifdef TIERED
1744 bool Arguments::compilation_mode_selected() {
1745  return !FLAG_IS_DEFAULT(TieredCompilation) || !FLAG_IS_DEFAULT(TieredStopAtLevel) ||
1746         !FLAG_IS_DEFAULT(UseAOT) JVMCI_ONLY(|| !FLAG_IS_DEFAULT(EnableJVMCI) || !FLAG_IS_DEFAULT(UseJVMCICompiler));
1747 
1748 }
1749 
1750 void Arguments::select_compilation_mode_ergonomically() {
1751 #if defined(_WINDOWS) && !defined(_LP64)
1752   if (FLAG_IS_DEFAULT(NeverActAsServerClassMachine)) {
1753     FLAG_SET_ERGO(bool, NeverActAsServerClassMachine, true);
1754   }
1755 #endif
1756   if (NeverActAsServerClassMachine) {
1757     set_client_compilation_mode();
1758   }
1759 }
1760 #endif //TIERED
1761 
1762 #if INCLUDE_JVMCI
1763 void Arguments::set_jvmci_specific_flags() {
1764   if (UseJVMCICompiler) {
1765     if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
1766       FLAG_SET_DEFAULT(TypeProfileWidth, 8);
1767     }
1768     if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) {
1769       FLAG_SET_DEFAULT(OnStackReplacePercentage, 933);
1770     }
1771     if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1772       FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M);
1773     }
1774     if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) {
1775       FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M);
1776     }
1777     if (FLAG_IS_DEFAULT(MetaspaceSize)) {
1778       FLAG_SET_DEFAULT(MetaspaceSize, 12*M);
1779     }
1780     if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) {
1781       FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K);
1782     }
1783     if (TieredStopAtLevel != CompLevel_full_optimization) {
1784       // Currently JVMCI compiler can only work at the full optimization level
1785       warning("forcing TieredStopAtLevel to full optimization because JVMCI is enabled");
1786       TieredStopAtLevel = CompLevel_full_optimization;
1787     }
1788     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
1789       FLAG_SET_DEFAULT(TypeProfileLevel, 0);
1790     }
1791   }
1792 }
1793 #endif
1794 
1795 jint Arguments::set_ergonomics_flags() {
1796 #ifdef TIERED
1797   if (!compilation_mode_selected()) {
1798     select_compilation_mode_ergonomically();
1799   }
1800 #endif
1801 
1802   jint gc_result = GCArguments::initialize();
1803   if (gc_result != JNI_OK) {
1804     return gc_result;
1805   }
1806 
1807 #if COMPILER2_OR_JVMCI
1808   // Shared spaces work fine with other GCs but causes bytecode rewriting
1809   // to be disabled, which hurts interpreter performance and decreases
1810   // server performance.  When -server is specified, keep the default off
1811   // unless it is asked for.  Future work: either add bytecode rewriting
1812   // at link time, or rewrite bytecodes in non-shared methods.
1813   if (is_server_compilation_mode_vm() && !DumpSharedSpaces && !RequireSharedSpaces &&
1814       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1815     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1816   }
1817 #endif
1818 
1819   set_conservative_max_heap_alignment();
1820 
1821 #ifndef ZERO
1822 #ifdef _LP64
1823   set_use_compressed_oops();
1824 
1825   // set_use_compressed_klass_ptrs() must be called after calling
1826   // set_use_compressed_oops().
1827   set_use_compressed_klass_ptrs();
1828 
1829   // Also checks that certain machines are slower with compressed oops
1830   // in vm_version initialization code.
1831 #endif // _LP64
1832 #endif // !ZERO
1833 
1834   return JNI_OK;
1835 }
1836 
1837 void Arguments::set_gc_specific_flags() {
1838   // Set GC flags
1839   GCArguments::arguments()->initialize_flags();
1840 }
1841 
1842 julong Arguments::limit_by_allocatable_memory(julong limit) {
1843   julong max_allocatable;
1844   julong result = limit;
1845   if (os::has_allocatable_memory_limit(&max_allocatable)) {
1846     result = MIN2(result, max_allocatable / MaxVirtMemFraction);
1847   }
1848   return result;
1849 }
1850 
1851 // Use static initialization to get the default before parsing
1852 static const size_t DefaultHeapBaseMinAddress = HeapBaseMinAddress;
1853 
1854 void Arguments::set_heap_size() {
1855   julong phys_mem =
1856     FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM)
1857                             : (julong)MaxRAM;
1858 
1859   // Experimental support for CGroup memory limits
1860   if (UseCGroupMemoryLimitForHeap) {
1861     // This is a rough indicator that a CGroup limit may be in force
1862     // for this process
1863     const char* lim_file = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
1864     FILE *fp = fopen(lim_file, "r");
1865     if (fp != NULL) {
1866       julong cgroup_max = 0;
1867       int ret = fscanf(fp, JULONG_FORMAT, &cgroup_max);
1868       if (ret == 1 && cgroup_max > 0) {
1869         // If unlimited, cgroup_max will be a very large, but unspecified
1870         // value, so use initial phys_mem as a limit
1871         log_info(gc, heap)("Setting phys_mem to the min of cgroup limit ("
1872                            JULONG_FORMAT "MB) and initial phys_mem ("
1873                            JULONG_FORMAT "MB)", cgroup_max/M, phys_mem/M);
1874         phys_mem = MIN2(cgroup_max, phys_mem);
1875       } else {
1876         warning("Unable to read/parse cgroup memory limit from %s: %s",
1877                 lim_file, errno != 0 ? strerror(errno) : "unknown error");
1878       }
1879       fclose(fp);
1880     } else {
1881       warning("Unable to open cgroup memory limit file %s (%s)", lim_file, strerror(errno));
1882     }
1883   }
1884 
1885   // Convert deprecated flags
1886   if (FLAG_IS_DEFAULT(MaxRAMPercentage) &&
1887       !FLAG_IS_DEFAULT(MaxRAMFraction))
1888     MaxRAMPercentage = 100.0 / MaxRAMFraction;
1889 
1890   if (FLAG_IS_DEFAULT(MinRAMPercentage) &&
1891       !FLAG_IS_DEFAULT(MinRAMFraction))
1892     MinRAMPercentage = 100.0 / MinRAMFraction;
1893 
1894   if (FLAG_IS_DEFAULT(InitialRAMPercentage) &&
1895       !FLAG_IS_DEFAULT(InitialRAMFraction))
1896     InitialRAMPercentage = 100.0 / InitialRAMFraction;
1897 
1898   // If the maximum heap size has not been set with -Xmx,
1899   // then set it as fraction of the size of physical memory,
1900   // respecting the maximum and minimum sizes of the heap.
1901   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
1902     julong reasonable_max = (julong)((phys_mem * MaxRAMPercentage) / 100);
1903     const julong reasonable_min = (julong)((phys_mem * MinRAMPercentage) / 100);
1904     if (reasonable_min < MaxHeapSize) {
1905       // Small physical memory, so use a minimum fraction of it for the heap
1906       reasonable_max = reasonable_min;
1907     } else {
1908       // Not-small physical memory, so require a heap at least
1909       // as large as MaxHeapSize
1910       reasonable_max = MAX2(reasonable_max, (julong)MaxHeapSize);
1911     }
1912 
1913     if (!FLAG_IS_DEFAULT(ErgoHeapSizeLimit) && ErgoHeapSizeLimit != 0) {
1914       // Limit the heap size to ErgoHeapSizeLimit
1915       reasonable_max = MIN2(reasonable_max, (julong)ErgoHeapSizeLimit);
1916     }
1917     if (UseCompressedOops) {
1918       // Limit the heap size to the maximum possible when using compressed oops
1919       julong max_coop_heap = (julong)max_heap_for_compressed_oops();
1920 
1921       // HeapBaseMinAddress can be greater than default but not less than.
1922       if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {
1923         if (HeapBaseMinAddress < DefaultHeapBaseMinAddress) {
1924           // matches compressed oops printing flags
1925           log_debug(gc, heap, coops)("HeapBaseMinAddress must be at least " SIZE_FORMAT
1926                                      " (" SIZE_FORMAT "G) which is greater than value given " SIZE_FORMAT,
1927                                      DefaultHeapBaseMinAddress,
1928                                      DefaultHeapBaseMinAddress/G,
1929                                      HeapBaseMinAddress);
1930           FLAG_SET_ERGO(size_t, HeapBaseMinAddress, DefaultHeapBaseMinAddress);
1931         }
1932       }
1933 
1934       if (HeapBaseMinAddress + MaxHeapSize < max_coop_heap) {
1935         // Heap should be above HeapBaseMinAddress to get zero based compressed oops
1936         // but it should be not less than default MaxHeapSize.
1937         max_coop_heap -= HeapBaseMinAddress;
1938       }
1939       reasonable_max = MIN2(reasonable_max, max_coop_heap);
1940     }
1941     reasonable_max = limit_by_allocatable_memory(reasonable_max);
1942 
1943     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
1944       // An initial heap size was specified on the command line,
1945       // so be sure that the maximum size is consistent.  Done
1946       // after call to limit_by_allocatable_memory because that
1947       // method might reduce the allocation size.
1948       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
1949     }
1950 
1951     log_trace(gc, heap)("  Maximum heap size " SIZE_FORMAT, (size_t) reasonable_max);
1952     FLAG_SET_ERGO(size_t, MaxHeapSize, (size_t)reasonable_max);
1953   }
1954 
1955   // If the minimum or initial heap_size have not been set or requested to be set
1956   // ergonomically, set them accordingly.
1957   if (InitialHeapSize == 0 || min_heap_size() == 0) {
1958     julong reasonable_minimum = (julong)(OldSize + NewSize);
1959 
1960     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
1961 
1962     reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
1963 
1964     if (InitialHeapSize == 0) {
1965       julong reasonable_initial = (julong)((phys_mem * InitialRAMPercentage) / 100);
1966 
1967       reasonable_initial = MAX3(reasonable_initial, reasonable_minimum, (julong)min_heap_size());
1968       reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
1969 
1970       reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
1971 
1972       log_trace(gc, heap)("  Initial heap size " SIZE_FORMAT, (size_t)reasonable_initial);
1973       FLAG_SET_ERGO(size_t, InitialHeapSize, (size_t)reasonable_initial);
1974     }
1975     // If the minimum heap size has not been set (via -Xms),
1976     // synchronize with InitialHeapSize to avoid errors with the default value.
1977     if (min_heap_size() == 0) {
1978       set_min_heap_size(MIN2((size_t)reasonable_minimum, InitialHeapSize));
1979       log_trace(gc, heap)("  Minimum heap size " SIZE_FORMAT, min_heap_size());
1980     }
1981   }
1982 }
1983 
1984 // This option inspects the machine and attempts to set various
1985 // parameters to be optimal for long-running, memory allocation
1986 // intensive jobs.  It is intended for machines with large
1987 // amounts of cpu and memory.
1988 jint Arguments::set_aggressive_heap_flags() {
1989   // initHeapSize is needed since _initial_heap_size is 4 bytes on a 32 bit
1990   // VM, but we may not be able to represent the total physical memory
1991   // available (like having 8gb of memory on a box but using a 32bit VM).
1992   // Thus, we need to make sure we're using a julong for intermediate
1993   // calculations.
1994   julong initHeapSize;
1995   julong total_memory = os::physical_memory();
1996 
1997   if (total_memory < (julong) 256 * M) {
1998     jio_fprintf(defaultStream::error_stream(),
1999             "You need at least 256mb of memory to use -XX:+AggressiveHeap\n");
2000     vm_exit(1);
2001   }
2002 
2003   // The heap size is half of available memory, or (at most)
2004   // all of possible memory less 160mb (leaving room for the OS
2005   // when using ISM).  This is the maximum; because adaptive sizing
2006   // is turned on below, the actual space used may be smaller.
2007 
2008   initHeapSize = MIN2(total_memory / (julong) 2,
2009           total_memory - (julong) 160 * M);
2010 
2011   initHeapSize = limit_by_allocatable_memory(initHeapSize);
2012 
2013   if (FLAG_IS_DEFAULT(MaxHeapSize)) {
2014     if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, initHeapSize) != Flag::SUCCESS) {
2015       return JNI_EINVAL;
2016     }
2017     if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, initHeapSize) != Flag::SUCCESS) {
2018       return JNI_EINVAL;
2019     }
2020     // Currently the minimum size and the initial heap sizes are the same.
2021     set_min_heap_size(initHeapSize);
2022   }
2023   if (FLAG_IS_DEFAULT(NewSize)) {
2024     // Make the young generation 3/8ths of the total heap.
2025     if (FLAG_SET_CMDLINE(size_t, NewSize,
2026             ((julong) MaxHeapSize / (julong) 8) * (julong) 3) != Flag::SUCCESS) {
2027       return JNI_EINVAL;
2028     }
2029     if (FLAG_SET_CMDLINE(size_t, MaxNewSize, NewSize) != Flag::SUCCESS) {
2030       return JNI_EINVAL;
2031     }
2032   }
2033 
2034 #if !defined(_ALLBSD_SOURCE) && !defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
2035   FLAG_SET_DEFAULT(UseLargePages, true);
2036 #endif
2037 
2038   // Increase some data structure sizes for efficiency
2039   if (FLAG_SET_CMDLINE(size_t, BaseFootPrintEstimate, MaxHeapSize) != Flag::SUCCESS) {
2040     return JNI_EINVAL;
2041   }
2042   if (FLAG_SET_CMDLINE(bool, ResizeTLAB, false) != Flag::SUCCESS) {
2043     return JNI_EINVAL;
2044   }
2045   if (FLAG_SET_CMDLINE(size_t, TLABSize, 256 * K) != Flag::SUCCESS) {
2046     return JNI_EINVAL;
2047   }
2048 
2049   // See the OldPLABSize comment below, but replace 'after promotion'
2050   // with 'after copying'.  YoungPLABSize is the size of the survivor
2051   // space per-gc-thread buffers.  The default is 4kw.
2052   if (FLAG_SET_CMDLINE(size_t, YoungPLABSize, 256 * K) != Flag::SUCCESS) { // Note: this is in words
2053     return JNI_EINVAL;
2054   }
2055 
2056   // OldPLABSize is the size of the buffers in the old gen that
2057   // UseParallelGC uses to promote live data that doesn't fit in the
2058   // survivor spaces.  At any given time, there's one for each gc thread.
2059   // The default size is 1kw. These buffers are rarely used, since the
2060   // survivor spaces are usually big enough.  For specjbb, however, there
2061   // are occasions when there's lots of live data in the young gen
2062   // and we end up promoting some of it.  We don't have a definite
2063   // explanation for why bumping OldPLABSize helps, but the theory
2064   // is that a bigger PLAB results in retaining something like the
2065   // original allocation order after promotion, which improves mutator
2066   // locality.  A minor effect may be that larger PLABs reduce the
2067   // number of PLAB allocation events during gc.  The value of 8kw
2068   // was arrived at by experimenting with specjbb.
2069   if (FLAG_SET_CMDLINE(size_t, OldPLABSize, 8 * K) != Flag::SUCCESS) { // Note: this is in words
2070     return JNI_EINVAL;
2071   }
2072 
2073   // Enable parallel GC and adaptive generation sizing
2074   if (FLAG_SET_CMDLINE(bool, UseParallelGC, true) != Flag::SUCCESS) {
2075     return JNI_EINVAL;
2076   }
2077 
2078   // Encourage steady state memory management
2079   if (FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100) != Flag::SUCCESS) {
2080     return JNI_EINVAL;
2081   }
2082 
2083   // This appears to improve mutator locality
2084   if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
2085     return JNI_EINVAL;
2086   }
2087 
2088   // Get around early Solaris scheduling bug
2089   // (affinity vs other jobs on system)
2090   // but disallow DR and offlining (5008695).
2091   if (FLAG_SET_CMDLINE(bool, BindGCTaskThreadsToCPUs, true) != Flag::SUCCESS) {
2092     return JNI_EINVAL;
2093   }
2094 
2095   return JNI_OK;
2096 }
2097 
2098 // This must be called after ergonomics.
2099 void Arguments::set_bytecode_flags() {
2100   if (!RewriteBytecodes) {
2101     FLAG_SET_DEFAULT(RewriteFrequentPairs, false);
2102   }
2103 }
2104 
2105 // Aggressive optimization flags  -XX:+AggressiveOpts
2106 jint Arguments::set_aggressive_opts_flags() {
2107 #ifdef COMPILER2
2108   if (AggressiveUnboxing) {
2109     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2110       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2111     } else if (!EliminateAutoBox) {
2112       // warning("AggressiveUnboxing is disabled because EliminateAutoBox is disabled");
2113       AggressiveUnboxing = false;
2114     }
2115     if (FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
2116       FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
2117     } else if (!DoEscapeAnalysis) {
2118       // warning("AggressiveUnboxing is disabled because DoEscapeAnalysis is disabled");
2119       AggressiveUnboxing = false;
2120     }
2121   }
2122   if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2123     if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
2124       FLAG_SET_DEFAULT(EliminateAutoBox, true);
2125     }
2126     if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
2127       FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
2128     }
2129 
2130     // Feed the cache size setting into the JDK
2131     char buffer[1024];
2132     jio_snprintf(buffer, 1024, "java.lang.Integer.IntegerCache.high=" INTX_FORMAT, AutoBoxCacheMax);
2133     if (!add_property(buffer)) {
2134       return JNI_ENOMEM;
2135     }
2136   }
2137   if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
2138     FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
2139   }
2140 #endif
2141 
2142   if (AggressiveOpts) {
2143 // Sample flag setting code
2144 //    if (FLAG_IS_DEFAULT(EliminateZeroing)) {
2145 //      FLAG_SET_DEFAULT(EliminateZeroing, true);
2146 //    }
2147   }
2148 
2149   return JNI_OK;
2150 }
2151 
2152 //===========================================================================================================
2153 // Parsing of java.compiler property
2154 
2155 void Arguments::process_java_compiler_argument(const char* arg) {
2156   // For backwards compatibility, Djava.compiler=NONE or ""
2157   // causes us to switch to -Xint mode UNLESS -Xdebug
2158   // is also specified.
2159   if (strlen(arg) == 0 || strcasecmp(arg, "NONE") == 0) {
2160     set_java_compiler(true);    // "-Djava.compiler[=...]" most recently seen.
2161   }
2162 }
2163 
2164 void Arguments::process_java_launcher_argument(const char* launcher, void* extra_info) {
2165   _sun_java_launcher = os::strdup_check_oom(launcher);
2166 }
2167 
2168 bool Arguments::created_by_java_launcher() {
2169   assert(_sun_java_launcher != NULL, "property must have value");
2170   return strcmp(DEFAULT_JAVA_LAUNCHER, _sun_java_launcher) != 0;
2171 }
2172 
2173 bool Arguments::sun_java_launcher_is_altjvm() {
2174   return _sun_java_launcher_is_altjvm;
2175 }
2176 
2177 //===========================================================================================================
2178 // Parsing of main arguments
2179 
2180 #if INCLUDE_JVMCI
2181 // Check consistency of jvmci vm argument settings.
2182 bool Arguments::check_jvmci_args_consistency() {
2183    return JVMCIGlobals::check_jvmci_flags_are_consistent();
2184 }
2185 #endif //INCLUDE_JVMCI
2186 
2187 // Check consistency of GC selection
2188 bool Arguments::check_gc_consistency() {
2189   // Ensure that the user has not selected conflicting sets
2190   // of collectors.
2191   uint i = 0;
2192   if (UseSerialGC)                       i++;
2193   if (UseConcMarkSweepGC)                i++;
2194   if (UseParallelGC || UseParallelOldGC) i++;
2195   if (UseG1GC)                           i++;
2196   if (i > 1) {
2197     jio_fprintf(defaultStream::error_stream(),
2198                 "Conflicting collector combinations in option list; "
2199                 "please refer to the release notes for the combinations "
2200                 "allowed\n");
2201     return false;
2202   }
2203 
2204   return true;
2205 }
2206 
2207 // Check the consistency of vm_init_args
2208 bool Arguments::check_vm_args_consistency() {
2209   // Method for adding checks for flag consistency.
2210   // The intent is to warn the user of all possible conflicts,
2211   // before returning an error.
2212   // Note: Needs platform-dependent factoring.
2213   bool status = true;
2214 
2215   if (TLABRefillWasteFraction == 0) {
2216     jio_fprintf(defaultStream::error_stream(),
2217                 "TLABRefillWasteFraction should be a denominator, "
2218                 "not " SIZE_FORMAT "\n",
2219                 TLABRefillWasteFraction);
2220     status = false;
2221   }
2222 
2223   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
2224     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
2225   }
2226 
2227   if (!(UseParallelGC || UseParallelOldGC) && FLAG_IS_DEFAULT(ScavengeBeforeFullGC)) {
2228     FLAG_SET_DEFAULT(ScavengeBeforeFullGC, false);
2229   }
2230 
2231   if (GCTimeLimit == 100) {
2232     // Turn off gc-overhead-limit-exceeded checks
2233     FLAG_SET_DEFAULT(UseGCOverheadLimit, false);
2234   }
2235 
2236   status = status && check_gc_consistency();
2237 
2238   // CMS space iteration, which FLSVerifyAllHeapreferences entails,
2239   // insists that we hold the requisite locks so that the iteration is
2240   // MT-safe. For the verification at start-up and shut-down, we don't
2241   // yet have a good way of acquiring and releasing these locks,
2242   // which are not visible at the CollectedHeap level. We want to
2243   // be able to acquire these locks and then do the iteration rather
2244   // than just disable the lock verification. This will be fixed under
2245   // bug 4788986.
2246   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
2247     if (VerifyDuringStartup) {
2248       warning("Heap verification at start-up disabled "
2249               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2250       VerifyDuringStartup = false; // Disable verification at start-up
2251     }
2252 
2253     if (VerifyBeforeExit) {
2254       warning("Heap verification at shutdown disabled "
2255               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
2256       VerifyBeforeExit = false; // Disable verification at shutdown
2257     }
2258   }
2259 
2260   if (PrintNMTStatistics) {
2261 #if INCLUDE_NMT
2262     if (MemTracker::tracking_level() == NMT_off) {
2263 #endif // INCLUDE_NMT
2264       warning("PrintNMTStatistics is disabled, because native memory tracking is not enabled");
2265       PrintNMTStatistics = false;
2266 #if INCLUDE_NMT
2267     }
2268 #endif
2269   }
2270 
2271 #if INCLUDE_JVMCI
2272   status = status && check_jvmci_args_consistency();
2273 
2274   if (EnableJVMCI) {
2275     PropertyList_unique_add(&_system_properties, "jdk.internal.vm.ci.enabled", "true",
2276         AddProperty, UnwriteableProperty, InternalProperty);
2277 
2278     if (!ScavengeRootsInCode) {
2279       warning("forcing ScavengeRootsInCode non-zero because JVMCI is enabled");
2280       ScavengeRootsInCode = 1;
2281     }
2282   }
2283 #endif
2284 
2285   // Check lower bounds of the code cache
2286   // Template Interpreter code is approximately 3X larger in debug builds.
2287   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
2288   if (ReservedCodeCacheSize < InitialCodeCacheSize) {
2289     jio_fprintf(defaultStream::error_stream(),
2290                 "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n",
2291                 ReservedCodeCacheSize/K, InitialCodeCacheSize/K);
2292     status = false;
2293   } else if (ReservedCodeCacheSize < min_code_cache_size) {
2294     jio_fprintf(defaultStream::error_stream(),
2295                 "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K,
2296                 min_code_cache_size/K);
2297     status = false;
2298   } else if (ReservedCodeCacheSize > CODE_CACHE_SIZE_LIMIT) {
2299     // Code cache size larger than CODE_CACHE_SIZE_LIMIT is not supported.
2300     jio_fprintf(defaultStream::error_stream(),
2301                 "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M,
2302                 CODE_CACHE_SIZE_LIMIT/M);
2303     status = false;
2304   } else if (NonNMethodCodeHeapSize < min_code_cache_size) {
2305     jio_fprintf(defaultStream::error_stream(),
2306                 "Invalid NonNMethodCodeHeapSize=%dK. Must be at least %uK.\n", NonNMethodCodeHeapSize/K,
2307                 min_code_cache_size/K);
2308     status = false;
2309   }
2310 
2311 #ifdef _LP64
2312   if (!FLAG_IS_DEFAULT(CICompilerCount) && !FLAG_IS_DEFAULT(CICompilerCountPerCPU) && CICompilerCountPerCPU) {
2313     warning("The VM option CICompilerCountPerCPU overrides CICompilerCount.");
2314   }
2315 #endif
2316 
2317 #ifndef SUPPORT_RESERVED_STACK_AREA
2318   if (StackReservedPages != 0) {
2319     FLAG_SET_CMDLINE(intx, StackReservedPages, 0);
2320     warning("Reserved Stack Area not supported on this platform");
2321   }
2322 #endif
2323 
2324   if (BackgroundCompilation && (CompileTheWorld || ReplayCompiles)) {
2325     if (!FLAG_IS_DEFAULT(BackgroundCompilation)) {
2326       warning("BackgroundCompilation disabled due to CompileTheWorld or ReplayCompiles options.");
2327     }
2328     FLAG_SET_CMDLINE(bool, BackgroundCompilation, false);
2329   }
2330   if (UseCompiler && is_interpreter_only()) {
2331     if (!FLAG_IS_DEFAULT(UseCompiler)) {
2332       warning("UseCompiler disabled due to -Xint.");
2333     }
2334     FLAG_SET_CMDLINE(bool, UseCompiler, false);
2335   }
2336 #ifdef COMPILER2
2337   if (PostLoopMultiversioning && !RangeCheckElimination) {
2338     if (!FLAG_IS_DEFAULT(PostLoopMultiversioning)) {
2339       warning("PostLoopMultiversioning disabled because RangeCheckElimination is disabled.");
2340     }
2341     FLAG_SET_CMDLINE(bool, PostLoopMultiversioning, false);
2342   }
2343   if (UseCountedLoopSafepoints && LoopStripMiningIter == 0) {
2344     if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
2345       warning("When counted loop safepoints are enabled, LoopStripMiningIter must be at least 1 (a safepoint every 1 iteration): setting it to 1");
2346     }
2347     LoopStripMiningIter = 1;
2348   } else if (!UseCountedLoopSafepoints && LoopStripMiningIter > 0) {
2349     if (!FLAG_IS_DEFAULT(UseCountedLoopSafepoints) || !FLAG_IS_DEFAULT(LoopStripMiningIter)) {
2350       warning("Disabling counted safepoints implies no loop strip mining: setting LoopStripMiningIter to 0");
2351     }
2352     LoopStripMiningIter = 0;
2353   }
2354   if (FLAG_IS_DEFAULT(LoopStripMiningIterShortLoop)) {
2355     // blind guess
2356     LoopStripMiningIterShortLoop = LoopStripMiningIter / 10;
2357   }
2358 #endif
2359   if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
2360     if ((UseNUMAInterleaving && !FLAG_IS_DEFAULT(UseNUMAInterleaving)) || (UseNUMA && !FLAG_IS_DEFAULT(UseNUMA))) {
2361       log_warning(arguments) ("NUMA support for Heap depends on the file system when AllocateHeapAt option is used.\n");
2362     }
2363   }
2364   return status;
2365 }
2366 
2367 bool Arguments::is_bad_option(const JavaVMOption* option, jboolean ignore,
2368   const char* option_type) {
2369   if (ignore) return false;
2370 
2371   const char* spacer = " ";
2372   if (option_type == NULL) {
2373     option_type = ++spacer; // Set both to the empty string.
2374   }
2375 
2376   if (os::obsolete_option(option)) {
2377     jio_fprintf(defaultStream::error_stream(),
2378                 "Obsolete %s%soption: %s\n", option_type, spacer,
2379       option->optionString);
2380     return false;
2381   } else {
2382     jio_fprintf(defaultStream::error_stream(),
2383                 "Unrecognized %s%soption: %s\n", option_type, spacer,
2384       option->optionString);
2385     return true;
2386   }
2387 }
2388 
2389 static const char* user_assertion_options[] = {
2390   "-da", "-ea", "-disableassertions", "-enableassertions", 0
2391 };
2392 
2393 static const char* system_assertion_options[] = {
2394   "-dsa", "-esa", "-disablesystemassertions", "-enablesystemassertions", 0
2395 };
2396 
2397 bool Arguments::parse_uintx(const char* value,
2398                             uintx* uintx_arg,
2399                             uintx min_size) {
2400 
2401   // Check the sign first since atojulong() parses only unsigned values.
2402   bool value_is_positive = !(*value == '-');
2403 
2404   if (value_is_positive) {
2405     julong n;
2406     bool good_return = atojulong(value, &n);
2407     if (good_return) {
2408       bool above_minimum = n >= min_size;
2409       bool value_is_too_large = n > max_uintx;
2410 
2411       if (above_minimum && !value_is_too_large) {
2412         *uintx_arg = n;
2413         return true;
2414       }
2415     }
2416   }
2417   return false;
2418 }
2419 
2420 unsigned int addreads_count = 0;
2421 unsigned int addexports_count = 0;
2422 unsigned int addopens_count = 0;
2423 unsigned int addmods_count = 0;
2424 unsigned int patch_mod_count = 0;
2425 
2426 bool Arguments::create_property(const char* prop_name, const char* prop_value, PropertyInternal internal) {
2427   size_t prop_len = strlen(prop_name) + strlen(prop_value) + 2;
2428   char* property = AllocateHeap(prop_len, mtArguments);
2429   int ret = jio_snprintf(property, prop_len, "%s=%s", prop_name, prop_value);
2430   if (ret < 0 || ret >= (int)prop_len) {
2431     FreeHeap(property);
2432     return false;
2433   }
2434   bool added = add_property(property, UnwriteableProperty, internal);
2435   FreeHeap(property);
2436   return added;
2437 }
2438 
2439 bool Arguments::create_numbered_property(const char* prop_base_name, const char* prop_value, unsigned int count) {
2440   const unsigned int props_count_limit = 1000;
2441   const int max_digits = 3;
2442   const int extra_symbols_count = 3; // includes '.', '=', '\0'
2443 
2444   // Make sure count is < props_count_limit. Otherwise, memory allocation will be too small.
2445   if (count < props_count_limit) {
2446     size_t prop_len = strlen(prop_base_name) + strlen(prop_value) + max_digits + extra_symbols_count;
2447     char* property = AllocateHeap(prop_len, mtArguments);
2448     int ret = jio_snprintf(property, prop_len, "%s.%d=%s", prop_base_name, count, prop_value);
2449     if (ret < 0 || ret >= (int)prop_len) {
2450       FreeHeap(property);
2451       jio_fprintf(defaultStream::error_stream(), "Failed to create property %s.%d=%s\n", prop_base_name, count, prop_value);
2452       return false;
2453     }
2454     bool added = add_property(property, UnwriteableProperty, InternalProperty);
2455     FreeHeap(property);
2456     return added;
2457   }
2458 
2459   jio_fprintf(defaultStream::error_stream(), "Property count limit exceeded: %s, limit=%d\n", prop_base_name, props_count_limit);
2460   return false;
2461 }
2462 
2463 Arguments::ArgsRange Arguments::parse_memory_size(const char* s,
2464                                                   julong* long_arg,
2465                                                   julong min_size,
2466                                                   julong max_size) {
2467   if (!atojulong(s, long_arg)) return arg_unreadable;
2468   return check_memory_size(*long_arg, min_size, max_size);
2469 }
2470 
2471 // Parse JavaVMInitArgs structure
2472 
2473 jint Arguments::parse_vm_init_args(const JavaVMInitArgs *java_tool_options_args,
2474                                    const JavaVMInitArgs *java_options_args,
2475                                    const JavaVMInitArgs *cmd_line_args) {
2476   bool patch_mod_javabase = false;
2477 
2478   // Save default settings for some mode flags
2479   Arguments::_AlwaysCompileLoopMethods = AlwaysCompileLoopMethods;
2480   Arguments::_UseOnStackReplacement    = UseOnStackReplacement;
2481   Arguments::_ClipInlining             = ClipInlining;
2482   Arguments::_BackgroundCompilation    = BackgroundCompilation;
2483   if (TieredCompilation) {
2484     Arguments::_Tier3InvokeNotifyFreqLog = Tier3InvokeNotifyFreqLog;
2485     Arguments::_Tier4InvocationThreshold = Tier4InvocationThreshold;
2486   }
2487 
2488   // Setup flags for mixed which is the default
2489   set_mode_flags(_mixed);
2490 
2491   // Parse args structure generated from JAVA_TOOL_OPTIONS environment
2492   // variable (if present).
2493   jint result = parse_each_vm_init_arg(java_tool_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2494   if (result != JNI_OK) {
2495     return result;
2496   }
2497 
2498   // Parse args structure generated from the command line flags.
2499   result = parse_each_vm_init_arg(cmd_line_args, &patch_mod_javabase, Flag::COMMAND_LINE);
2500   if (result != JNI_OK) {
2501     return result;
2502   }
2503 
2504   // Parse args structure generated from the _JAVA_OPTIONS environment
2505   // variable (if present) (mimics classic VM)
2506   result = parse_each_vm_init_arg(java_options_args, &patch_mod_javabase, Flag::ENVIRON_VAR);
2507   if (result != JNI_OK) {
2508     return result;
2509   }
2510 
2511   // We need to ensure processor and memory resources have been properly
2512   // configured - which may rely on arguments we just processed - before
2513   // doing the final argument processing. Any argument processing that
2514   // needs to know about processor and memory resources must occur after
2515   // this point.
2516 
2517   os::init_container_support();
2518 
2519   // Do final processing now that all arguments have been parsed
2520   result = finalize_vm_init_args(patch_mod_javabase);
2521   if (result != JNI_OK) {
2522     return result;
2523   }
2524 
2525   return JNI_OK;
2526 }
2527 
2528 // Checks if name in command-line argument -agent{lib,path}:name[=options]
2529 // represents a valid JDWP agent.  is_path==true denotes that we
2530 // are dealing with -agentpath (case where name is a path), otherwise with
2531 // -agentlib
2532 bool valid_jdwp_agent(char *name, bool is_path) {
2533   char *_name;
2534   const char *_jdwp = "jdwp";
2535   size_t _len_jdwp, _len_prefix;
2536 
2537   if (is_path) {
2538     if ((_name = strrchr(name, (int) *os::file_separator())) == NULL) {
2539       return false;
2540     }
2541 
2542     _name++;  // skip past last path separator
2543     _len_prefix = strlen(JNI_LIB_PREFIX);
2544 
2545     if (strncmp(_name, JNI_LIB_PREFIX, _len_prefix) != 0) {
2546       return false;
2547     }
2548 
2549     _name += _len_prefix;
2550     _len_jdwp = strlen(_jdwp);
2551 
2552     if (strncmp(_name, _jdwp, _len_jdwp) == 0) {
2553       _name += _len_jdwp;
2554     }
2555     else {
2556       return false;
2557     }
2558 
2559     if (strcmp(_name, JNI_LIB_SUFFIX) != 0) {
2560       return false;
2561     }
2562 
2563     return true;
2564   }
2565 
2566   if (strcmp(name, _jdwp) == 0) {
2567     return true;
2568   }
2569 
2570   return false;
2571 }
2572 
2573 int Arguments::process_patch_mod_option(const char* patch_mod_tail, bool* patch_mod_javabase) {
2574   // --patch-module=<module>=<file>(<pathsep><file>)*
2575   assert(patch_mod_tail != NULL, "Unexpected NULL patch-module value");
2576   // Find the equal sign between the module name and the path specification
2577   const char* module_equal = strchr(patch_mod_tail, '=');
2578   if (module_equal == NULL) {
2579     jio_fprintf(defaultStream::output_stream(), "Missing '=' in --patch-module specification\n");
2580     return JNI_ERR;
2581   } else {
2582     // Pick out the module name
2583     size_t module_len = module_equal - patch_mod_tail;
2584     char* module_name = NEW_C_HEAP_ARRAY_RETURN_NULL(char, module_len+1, mtArguments);
2585     if (module_name != NULL) {
2586       memcpy(module_name, patch_mod_tail, module_len);
2587       *(module_name + module_len) = '\0';
2588       // The path piece begins one past the module_equal sign
2589       add_patch_mod_prefix(module_name, module_equal + 1, patch_mod_javabase);
2590       FREE_C_HEAP_ARRAY(char, module_name);
2591       if (!create_numbered_property("jdk.module.patch", patch_mod_tail, patch_mod_count++)) {
2592         return JNI_ENOMEM;
2593       }
2594     } else {
2595       return JNI_ENOMEM;
2596     }
2597   }
2598   return JNI_OK;
2599 }
2600 
2601 // Parse -Xss memory string parameter and convert to ThreadStackSize in K.
2602 jint Arguments::parse_xss(const JavaVMOption* option, const char* tail, intx* out_ThreadStackSize) {
2603   // The min and max sizes match the values in globals.hpp, but scaled
2604   // with K. The values have been chosen so that alignment with page
2605   // size doesn't change the max value, which makes the conversions
2606   // back and forth between Xss value and ThreadStackSize value easier.
2607   // The values have also been chosen to fit inside a 32-bit signed type.
2608   const julong min_ThreadStackSize = 0;
2609   const julong max_ThreadStackSize = 1 * M;
2610 
2611   const julong min_size = min_ThreadStackSize * K;
2612   const julong max_size = max_ThreadStackSize * K;
2613 
2614   assert(is_aligned(max_size, os::vm_page_size()), "Implementation assumption");
2615 
2616   julong size = 0;
2617   ArgsRange errcode = parse_memory_size(tail, &size, min_size, max_size);
2618   if (errcode != arg_in_range) {
2619     bool silent = (option == NULL); // Allow testing to silence error messages
2620     if (!silent) {
2621       jio_fprintf(defaultStream::error_stream(),
2622                   "Invalid thread stack size: %s\n", option->optionString);
2623       describe_range_error(errcode);
2624     }
2625     return JNI_EINVAL;
2626   }
2627 
2628   // Internally track ThreadStackSize in units of 1024 bytes.
2629   const julong size_aligned = align_up(size, K);
2630   assert(size <= size_aligned,
2631          "Overflow: " JULONG_FORMAT " " JULONG_FORMAT,
2632          size, size_aligned);
2633 
2634   const julong size_in_K = size_aligned / K;
2635   assert(size_in_K < (julong)max_intx,
2636          "size_in_K doesn't fit in the type of ThreadStackSize: " JULONG_FORMAT,
2637          size_in_K);
2638 
2639   // Check that code expanding ThreadStackSize to a page aligned number of bytes won't overflow.
2640   const julong max_expanded = align_up(size_in_K * K, os::vm_page_size());
2641   assert(max_expanded < max_uintx && max_expanded >= size_in_K,
2642          "Expansion overflowed: " JULONG_FORMAT " " JULONG_FORMAT,
2643          max_expanded, size_in_K);
2644 
2645   *out_ThreadStackSize = (intx)size_in_K;
2646 
2647   return JNI_OK;
2648 }
2649 
2650 jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, bool* patch_mod_javabase, Flag::Flags origin) {
2651   // For match_option to return remaining or value part of option string
2652   const char* tail;
2653 
2654   // iterate over arguments
2655   for (int index = 0; index < args->nOptions; index++) {
2656     bool is_absolute_path = false;  // for -agentpath vs -agentlib
2657 
2658     const JavaVMOption* option = args->options + index;
2659 
2660     if (!match_option(option, "-Djava.class.path", &tail) &&
2661         !match_option(option, "-Dsun.java.command", &tail) &&
2662         !match_option(option, "-Dsun.java.launcher", &tail)) {
2663 
2664         // add all jvm options to the jvm_args string. This string
2665         // is used later to set the java.vm.args PerfData string constant.
2666         // the -Djava.class.path and the -Dsun.java.command options are
2667         // omitted from jvm_args string as each have their own PerfData
2668         // string constant object.
2669         build_jvm_args(option->optionString);
2670     }
2671 
2672     // -verbose:[class/module/gc/jni]
2673     if (match_option(option, "-verbose", &tail)) {
2674       if (!strcmp(tail, ":class") || !strcmp(tail, "")) {
2675         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, load));
2676         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, unload));
2677       } else if (!strcmp(tail, ":module")) {
2678         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, load));
2679         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(module, unload));
2680       } else if (!strcmp(tail, ":gc")) {
2681         LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
2682       } else if (!strcmp(tail, ":jni")) {
2683         if (FLAG_SET_CMDLINE(bool, PrintJNIResolving, true) != Flag::SUCCESS) {
2684           return JNI_EINVAL;
2685         }
2686       }
2687     // -da / -ea / -disableassertions / -enableassertions
2688     // These accept an optional class/package name separated by a colon, e.g.,
2689     // -da:java.lang.Thread.
2690     } else if (match_option(option, user_assertion_options, &tail, true)) {
2691       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2692       if (*tail == '\0') {
2693         JavaAssertions::setUserClassDefault(enable);
2694       } else {
2695         assert(*tail == ':', "bogus match by match_option()");
2696         JavaAssertions::addOption(tail + 1, enable);
2697       }
2698     // -dsa / -esa / -disablesystemassertions / -enablesystemassertions
2699     } else if (match_option(option, system_assertion_options, &tail, false)) {
2700       bool enable = option->optionString[1] == 'e';     // char after '-' is 'e'
2701       JavaAssertions::setSystemClassDefault(enable);
2702     // -bootclasspath:
2703     } else if (match_option(option, "-Xbootclasspath:", &tail)) {
2704         jio_fprintf(defaultStream::output_stream(),
2705           "-Xbootclasspath is no longer a supported option.\n");
2706         return JNI_EINVAL;
2707     // -bootclasspath/a:
2708     } else if (match_option(option, "-Xbootclasspath/a:", &tail)) {
2709       Arguments::append_sysclasspath(tail);
2710     // -bootclasspath/p:
2711     } else if (match_option(option, "-Xbootclasspath/p:", &tail)) {
2712         jio_fprintf(defaultStream::output_stream(),
2713           "-Xbootclasspath/p is no longer a supported option.\n");
2714         return JNI_EINVAL;
2715     // -Xrun
2716     } else if (match_option(option, "-Xrun", &tail)) {
2717       if (tail != NULL) {
2718         const char* pos = strchr(tail, ':');
2719         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2720         char* name = NEW_C_HEAP_ARRAY(char, len + 1, mtArguments);
2721         jio_snprintf(name, len + 1, "%s", tail);
2722 
2723         char *options = NULL;
2724         if(pos != NULL) {
2725           size_t len2 = strlen(pos+1) + 1; // options start after ':'.  Final zero must be copied.
2726           options = (char*)memcpy(NEW_C_HEAP_ARRAY(char, len2, mtArguments), pos+1, len2);
2727         }
2728 #if !INCLUDE_JVMTI
2729         if (strcmp(name, "jdwp") == 0) {
2730           jio_fprintf(defaultStream::error_stream(),
2731             "Debugging agents are not supported in this VM\n");
2732           return JNI_ERR;
2733         }
2734 #endif // !INCLUDE_JVMTI
2735         add_init_library(name, options);
2736       }
2737     } else if (match_option(option, "--add-reads=", &tail)) {
2738       if (!create_numbered_property("jdk.module.addreads", tail, addreads_count++)) {
2739         return JNI_ENOMEM;
2740       }
2741     } else if (match_option(option, "--add-exports=", &tail)) {
2742       if (!create_numbered_property("jdk.module.addexports", tail, addexports_count++)) {
2743         return JNI_ENOMEM;
2744       }
2745     } else if (match_option(option, "--add-opens=", &tail)) {
2746       if (!create_numbered_property("jdk.module.addopens", tail, addopens_count++)) {
2747         return JNI_ENOMEM;
2748       }
2749     } else if (match_option(option, "--add-modules=", &tail)) {
2750       if (!create_numbered_property("jdk.module.addmods", tail, addmods_count++)) {
2751         return JNI_ENOMEM;
2752       }
2753     } else if (match_option(option, "--limit-modules=", &tail)) {
2754       if (!create_property("jdk.module.limitmods", tail, InternalProperty)) {
2755         return JNI_ENOMEM;
2756       }
2757     } else if (match_option(option, "--module-path=", &tail)) {
2758       if (!create_property("jdk.module.path", tail, ExternalProperty)) {
2759         return JNI_ENOMEM;
2760       }
2761     } else if (match_option(option, "--upgrade-module-path=", &tail)) {
2762       if (!create_property("jdk.module.upgrade.path", tail, ExternalProperty)) {
2763         return JNI_ENOMEM;
2764       }
2765     } else if (match_option(option, "--patch-module=", &tail)) {
2766       // --patch-module=<module>=<file>(<pathsep><file>)*
2767       int res = process_patch_mod_option(tail, patch_mod_javabase);
2768       if (res != JNI_OK) {
2769         return res;
2770       }
2771     } else if (match_option(option, "--illegal-access=", &tail)) {
2772       if (!create_property("jdk.module.illegalAccess", tail, ExternalProperty)) {
2773         return JNI_ENOMEM;
2774       }
2775     // -agentlib and -agentpath
2776     } else if (match_option(option, "-agentlib:", &tail) ||
2777           (is_absolute_path = match_option(option, "-agentpath:", &tail))) {
2778       if(tail != NULL) {
2779         const char* pos = strchr(tail, '=');
2780         size_t len = (pos == NULL) ? strlen(tail) : pos - tail;
2781         char* name = strncpy(NEW_C_HEAP_ARRAY(char, len + 1, mtArguments), tail, len);
2782         name[len] = '\0';
2783 
2784         char *options = NULL;
2785         if(pos != NULL) {
2786           options = os::strdup_check_oom(pos + 1, mtArguments);
2787         }
2788 #if !INCLUDE_JVMTI
2789         if (valid_jdwp_agent(name, is_absolute_path)) {
2790           jio_fprintf(defaultStream::error_stream(),
2791             "Debugging agents are not supported in this VM\n");
2792           return JNI_ERR;
2793         }
2794 #endif // !INCLUDE_JVMTI
2795         add_init_agent(name, options, is_absolute_path);
2796       }
2797     // -javaagent
2798     } else if (match_option(option, "-javaagent:", &tail)) {
2799 #if !INCLUDE_JVMTI
2800       jio_fprintf(defaultStream::error_stream(),
2801         "Instrumentation agents are not supported in this VM\n");
2802       return JNI_ERR;
2803 #else
2804       if (tail != NULL) {
2805         size_t length = strlen(tail) + 1;
2806         char *options = NEW_C_HEAP_ARRAY(char, length, mtArguments);
2807         jio_snprintf(options, length, "%s", tail);
2808         add_instrument_agent("instrument", options, false);
2809         // java agents need module java.instrument
2810         if (!create_numbered_property("jdk.module.addmods", "java.instrument", addmods_count++)) {
2811           return JNI_ENOMEM;
2812         }
2813       }
2814 #endif // !INCLUDE_JVMTI
2815     // -Xnoclassgc
2816     } else if (match_option(option, "-Xnoclassgc")) {
2817       if (FLAG_SET_CMDLINE(bool, ClassUnloading, false) != Flag::SUCCESS) {
2818         return JNI_EINVAL;
2819       }
2820     // -Xconcgc
2821     } else if (match_option(option, "-Xconcgc")) {
2822       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, true) != Flag::SUCCESS) {
2823         return JNI_EINVAL;
2824       }
2825       handle_extra_cms_flags("-Xconcgc uses UseConcMarkSweepGC");
2826     // -Xnoconcgc
2827     } else if (match_option(option, "-Xnoconcgc")) {
2828       if (FLAG_SET_CMDLINE(bool, UseConcMarkSweepGC, false) != Flag::SUCCESS) {
2829         return JNI_EINVAL;
2830       }
2831       handle_extra_cms_flags("-Xnoconcgc uses UseConcMarkSweepGC");
2832     // -Xbatch
2833     } else if (match_option(option, "-Xbatch")) {
2834       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2835         return JNI_EINVAL;
2836       }
2837     // -Xmn for compatibility with other JVM vendors
2838     } else if (match_option(option, "-Xmn", &tail)) {
2839       julong long_initial_young_size = 0;
2840       ArgsRange errcode = parse_memory_size(tail, &long_initial_young_size, 1);
2841       if (errcode != arg_in_range) {
2842         jio_fprintf(defaultStream::error_stream(),
2843                     "Invalid initial young generation size: %s\n", option->optionString);
2844         describe_range_error(errcode);
2845         return JNI_EINVAL;
2846       }
2847       if (FLAG_SET_CMDLINE(size_t, MaxNewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2848         return JNI_EINVAL;
2849       }
2850       if (FLAG_SET_CMDLINE(size_t, NewSize, (size_t)long_initial_young_size) != Flag::SUCCESS) {
2851         return JNI_EINVAL;
2852       }
2853     // -Xms
2854     } else if (match_option(option, "-Xms", &tail)) {
2855       julong long_initial_heap_size = 0;
2856       // an initial heap size of 0 means automatically determine
2857       ArgsRange errcode = parse_memory_size(tail, &long_initial_heap_size, 0);
2858       if (errcode != arg_in_range) {
2859         jio_fprintf(defaultStream::error_stream(),
2860                     "Invalid initial heap size: %s\n", option->optionString);
2861         describe_range_error(errcode);
2862         return JNI_EINVAL;
2863       }
2864       set_min_heap_size((size_t)long_initial_heap_size);
2865       // Currently the minimum size and the initial heap sizes are the same.
2866       // Can be overridden with -XX:InitialHeapSize.
2867       if (FLAG_SET_CMDLINE(size_t, InitialHeapSize, (size_t)long_initial_heap_size) != Flag::SUCCESS) {
2868         return JNI_EINVAL;
2869       }
2870     // -Xmx
2871     } else if (match_option(option, "-Xmx", &tail) || match_option(option, "-XX:MaxHeapSize=", &tail)) {
2872       julong long_max_heap_size = 0;
2873       ArgsRange errcode = parse_memory_size(tail, &long_max_heap_size, 1);
2874       if (errcode != arg_in_range) {
2875         jio_fprintf(defaultStream::error_stream(),
2876                     "Invalid maximum heap size: %s\n", option->optionString);
2877         describe_range_error(errcode);
2878         return JNI_EINVAL;
2879       }
2880       if (FLAG_SET_CMDLINE(size_t, MaxHeapSize, (size_t)long_max_heap_size) != Flag::SUCCESS) {
2881         return JNI_EINVAL;
2882       }
2883     // Xmaxf
2884     } else if (match_option(option, "-Xmaxf", &tail)) {
2885       char* err;
2886       int maxf = (int)(strtod(tail, &err) * 100);
2887       if (*err != '\0' || *tail == '\0') {
2888         jio_fprintf(defaultStream::error_stream(),
2889                     "Bad max heap free percentage size: %s\n",
2890                     option->optionString);
2891         return JNI_EINVAL;
2892       } else {
2893         if (FLAG_SET_CMDLINE(uintx, MaxHeapFreeRatio, maxf) != Flag::SUCCESS) {
2894             return JNI_EINVAL;
2895         }
2896       }
2897     // Xminf
2898     } else if (match_option(option, "-Xminf", &tail)) {
2899       char* err;
2900       int minf = (int)(strtod(tail, &err) * 100);
2901       if (*err != '\0' || *tail == '\0') {
2902         jio_fprintf(defaultStream::error_stream(),
2903                     "Bad min heap free percentage size: %s\n",
2904                     option->optionString);
2905         return JNI_EINVAL;
2906       } else {
2907         if (FLAG_SET_CMDLINE(uintx, MinHeapFreeRatio, minf) != Flag::SUCCESS) {
2908           return JNI_EINVAL;
2909         }
2910       }
2911     // -Xss
2912     } else if (match_option(option, "-Xss", &tail)) {
2913       intx value = 0;
2914       jint err = parse_xss(option, tail, &value);
2915       if (err != JNI_OK) {
2916         return err;
2917       }
2918       if (FLAG_SET_CMDLINE(intx, ThreadStackSize, value) != Flag::SUCCESS) {
2919         return JNI_EINVAL;
2920       }
2921     } else if (match_option(option, "-Xmaxjitcodesize", &tail) ||
2922                match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) {
2923       julong long_ReservedCodeCacheSize = 0;
2924 
2925       ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1);
2926       if (errcode != arg_in_range) {
2927         jio_fprintf(defaultStream::error_stream(),
2928                     "Invalid maximum code cache size: %s.\n", option->optionString);
2929         return JNI_EINVAL;
2930       }
2931       if (FLAG_SET_CMDLINE(uintx, ReservedCodeCacheSize, (uintx)long_ReservedCodeCacheSize) != Flag::SUCCESS) {
2932         return JNI_EINVAL;
2933       }
2934     // -green
2935     } else if (match_option(option, "-green")) {
2936       jio_fprintf(defaultStream::error_stream(),
2937                   "Green threads support not available\n");
2938           return JNI_EINVAL;
2939     // -native
2940     } else if (match_option(option, "-native")) {
2941           // HotSpot always uses native threads, ignore silently for compatibility
2942     // -Xrs
2943     } else if (match_option(option, "-Xrs")) {
2944           // Classic/EVM option, new functionality
2945       if (FLAG_SET_CMDLINE(bool, ReduceSignalUsage, true) != Flag::SUCCESS) {
2946         return JNI_EINVAL;
2947       }
2948       // -Xprof
2949     } else if (match_option(option, "-Xprof")) {
2950       char version[256];
2951       // Obsolete in JDK 10
2952       JDK_Version::jdk(10).to_string(version, sizeof(version));
2953       warning("Ignoring option %s; support was removed in %s", option->optionString, version);
2954     // -Xconcurrentio
2955     } else if (match_option(option, "-Xconcurrentio")) {
2956       if (FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true) != Flag::SUCCESS) {
2957         return JNI_EINVAL;
2958       }
2959       if (FLAG_SET_CMDLINE(bool, BackgroundCompilation, false) != Flag::SUCCESS) {
2960         return JNI_EINVAL;
2961       }
2962       if (FLAG_SET_CMDLINE(intx, DeferThrSuspendLoopCount, 1) != Flag::SUCCESS) {
2963         return JNI_EINVAL;
2964       }
2965       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2966         return JNI_EINVAL;
2967       }
2968       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2969         return JNI_EINVAL;
2970       }
2971 
2972       // -Xinternalversion
2973     } else if (match_option(option, "-Xinternalversion")) {
2974       jio_fprintf(defaultStream::output_stream(), "%s\n",
2975                   VM_Version::internal_vm_info_string());
2976       vm_exit(0);
2977 #ifndef PRODUCT
2978     // -Xprintflags
2979     } else if (match_option(option, "-Xprintflags")) {
2980       CommandLineFlags::printFlags(tty, false);
2981       vm_exit(0);
2982 #endif
2983     // -D
2984     } else if (match_option(option, "-D", &tail)) {
2985       const char* value;
2986       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2987             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2988         // abort if -Djava.endorsed.dirs is set
2989         jio_fprintf(defaultStream::output_stream(),
2990           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2991           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2992         return JNI_EINVAL;
2993       }
2994       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2995             *value != '\0' && strcmp(value, "\"\"") != 0) {
2996         // abort if -Djava.ext.dirs is set
2997         jio_fprintf(defaultStream::output_stream(),
2998           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2999         return JNI_EINVAL;
3000       }
3001       // Check for module related properties.  They must be set using the modules
3002       // options. For example: use "--add-modules=java.sql", not
3003       // "-Djdk.module.addmods=java.sql"
3004       if (is_internal_module_property(option->optionString + 2)) {
3005         needs_module_property_warning = true;
3006         continue;
3007       }
3008 
3009       if (!add_property(tail)) {
3010         return JNI_ENOMEM;
3011       }
3012       // Out of the box management support
3013       if (match_option(option, "-Dcom.sun.management", &tail)) {
3014 #if INCLUDE_MANAGEMENT
3015         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3016           return JNI_EINVAL;
3017         }
3018         // management agent in module jdk.management.agent
3019         if (!create_numbered_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
3020           return JNI_ENOMEM;
3021         }
3022 #else
3023         jio_fprintf(defaultStream::output_stream(),
3024           "-Dcom.sun.management is not supported in this VM.\n");
3025         return JNI_ERR;
3026 #endif
3027       }
3028     // -Xint
3029     } else if (match_option(option, "-Xint")) {
3030           set_mode_flags(_int);
3031     // -Xmixed
3032     } else if (match_option(option, "-Xmixed")) {
3033           set_mode_flags(_mixed);
3034     // -Xcomp
3035     } else if (match_option(option, "-Xcomp")) {
3036       // for testing the compiler; turn off all flags that inhibit compilation
3037           set_mode_flags(_comp);
3038     // -Xshare:dump
3039     } else if (match_option(option, "-Xshare:dump")) {
3040       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3041         return JNI_EINVAL;
3042       }
3043       set_mode_flags(_int);     // Prevent compilation, which creates objects
3044     // -Xshare:on
3045     } else if (match_option(option, "-Xshare:on")) {
3046       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3047         return JNI_EINVAL;
3048       }
3049       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3050         return JNI_EINVAL;
3051       }
3052     // -Xshare:auto
3053     } else if (match_option(option, "-Xshare:auto")) {
3054       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3055         return JNI_EINVAL;
3056       }
3057       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3058         return JNI_EINVAL;
3059       }
3060     // -Xshare:off
3061     } else if (match_option(option, "-Xshare:off")) {
3062       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3063         return JNI_EINVAL;
3064       }
3065       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3066         return JNI_EINVAL;
3067       }
3068     // -Xverify
3069     } else if (match_option(option, "-Xverify", &tail)) {
3070       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3071         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3072           return JNI_EINVAL;
3073         }
3074         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3075           return JNI_EINVAL;
3076         }
3077       } else if (strcmp(tail, ":remote") == 0) {
3078         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3079           return JNI_EINVAL;
3080         }
3081         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3082           return JNI_EINVAL;
3083         }
3084       } else if (strcmp(tail, ":none") == 0) {
3085         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3086           return JNI_EINVAL;
3087         }
3088         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3089           return JNI_EINVAL;
3090         }
3091       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3092         return JNI_EINVAL;
3093       }
3094     // -Xdebug
3095     } else if (match_option(option, "-Xdebug")) {
3096       // note this flag has been used, then ignore
3097       set_xdebug_mode(true);
3098     // -Xnoagent
3099     } else if (match_option(option, "-Xnoagent")) {
3100       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3101     } else if (match_option(option, "-Xloggc:", &tail)) {
3102       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3103       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3104       _gc_log_filename = os::strdup_check_oom(tail);
3105     } else if (match_option(option, "-Xlog", &tail)) {
3106       bool ret = false;
3107       if (strcmp(tail, ":help") == 0) {
3108         LogConfiguration::print_command_line_help(defaultStream::output_stream());
3109         vm_exit(0);
3110       } else if (strcmp(tail, ":disable") == 0) {
3111         LogConfiguration::disable_logging();
3112         ret = true;
3113       } else if (*tail == '\0') {
3114         ret = LogConfiguration::parse_command_line_arguments();
3115         assert(ret, "-Xlog without arguments should never fail to parse");
3116       } else if (*tail == ':') {
3117         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3118       }
3119       if (ret == false) {
3120         jio_fprintf(defaultStream::error_stream(),
3121                     "Invalid -Xlog option '-Xlog%s'\n",
3122                     tail);
3123         return JNI_EINVAL;
3124       }
3125     // JNI hooks
3126     } else if (match_option(option, "-Xcheck", &tail)) {
3127       if (!strcmp(tail, ":jni")) {
3128 #if !INCLUDE_JNI_CHECK
3129         warning("JNI CHECKING is not supported in this VM");
3130 #else
3131         CheckJNICalls = true;
3132 #endif // INCLUDE_JNI_CHECK
3133       } else if (is_bad_option(option, args->ignoreUnrecognized,
3134                                      "check")) {
3135         return JNI_EINVAL;
3136       }
3137     } else if (match_option(option, "vfprintf")) {
3138       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3139     } else if (match_option(option, "exit")) {
3140       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3141     } else if (match_option(option, "abort")) {
3142       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3143     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3144     // and the last option wins.
3145     } else if (match_option(option, "-XX:+NeverTenure")) {
3146       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3147         return JNI_EINVAL;
3148       }
3149       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3150         return JNI_EINVAL;
3151       }
3152       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3153         return JNI_EINVAL;
3154       }
3155     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3156       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3157         return JNI_EINVAL;
3158       }
3159       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3160         return JNI_EINVAL;
3161       }
3162       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3163         return JNI_EINVAL;
3164       }
3165     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3166       uintx max_tenuring_thresh = 0;
3167       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3168         jio_fprintf(defaultStream::error_stream(),
3169                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3170         return JNI_EINVAL;
3171       }
3172 
3173       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3174         return JNI_EINVAL;
3175       }
3176 
3177       if (MaxTenuringThreshold == 0) {
3178         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3179           return JNI_EINVAL;
3180         }
3181         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3182           return JNI_EINVAL;
3183         }
3184       } else {
3185         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3186           return JNI_EINVAL;
3187         }
3188         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3189           return JNI_EINVAL;
3190         }
3191       }
3192     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3193       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3194         return JNI_EINVAL;
3195       }
3196       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3197         return JNI_EINVAL;
3198       }
3199     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3200       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3201         return JNI_EINVAL;
3202       }
3203       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3204         return JNI_EINVAL;
3205       }
3206     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3207 #if defined(DTRACE_ENABLED)
3208       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3209         return JNI_EINVAL;
3210       }
3211       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3212         return JNI_EINVAL;
3213       }
3214       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3215         return JNI_EINVAL;
3216       }
3217       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3218         return JNI_EINVAL;
3219       }
3220 #else // defined(DTRACE_ENABLED)
3221       jio_fprintf(defaultStream::error_stream(),
3222                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3223       return JNI_EINVAL;
3224 #endif // defined(DTRACE_ENABLED)
3225 #ifdef ASSERT
3226     } else if (match_option(option, "-XX:+FullGCALot")) {
3227       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3228         return JNI_EINVAL;
3229       }
3230       // disable scavenge before parallel mark-compact
3231       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3232         return JNI_EINVAL;
3233       }
3234 #endif
3235 #if !INCLUDE_MANAGEMENT
3236     } else if (match_option(option, "-XX:+ManagementServer")) {
3237         jio_fprintf(defaultStream::error_stream(),
3238           "ManagementServer is not supported in this VM.\n");
3239         return JNI_ERR;
3240 #endif // INCLUDE_MANAGEMENT
3241     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3242       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3243       // already been handled
3244       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3245           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3246         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3247           return JNI_EINVAL;
3248         }
3249       }
3250     // Unknown option
3251     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3252       return JNI_ERR;
3253     }
3254   }
3255 
3256   // PrintSharedArchiveAndExit will turn on
3257   //   -Xshare:on
3258   //   -Xlog:class+path=info
3259   if (PrintSharedArchiveAndExit) {
3260     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3261       return JNI_EINVAL;
3262     }
3263     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3264       return JNI_EINVAL;
3265     }
3266     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3267   }
3268 
3269   // Change the default value for flags  which have different default values
3270   // when working with older JDKs.
3271 #ifdef LINUX
3272  if (JDK_Version::current().compare_major(6) <= 0 &&
3273       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3274     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3275   }
3276 #endif // LINUX
3277   fix_appclasspath();
3278   return JNI_OK;
3279 }
3280 
3281 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3282   // For java.base check for duplicate --patch-module options being specified on the command line.
3283   // This check is only required for java.base, all other duplicate module specifications
3284   // will be checked during module system initialization.  The module system initialization
3285   // will throw an ExceptionInInitializerError if this situation occurs.
3286   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
3287     if (*patch_mod_javabase) {
3288       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
3289     } else {
3290       *patch_mod_javabase = true;
3291     }
3292   }
3293 
3294   // Create GrowableArray lazily, only if --patch-module has been specified
3295   if (_patch_mod_prefix == NULL) {
3296     _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3297   }
3298 
3299   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3300 }
3301 
3302 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3303 //
3304 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3305 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3306 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3307 // path is treated as the current directory.
3308 //
3309 // This causes problems with CDS, which requires that all directories specified in the classpath
3310 // must be empty. In most cases, applications do NOT want to load classes from the current
3311 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3312 // scripts compatible with CDS.
3313 void Arguments::fix_appclasspath() {
3314   if (IgnoreEmptyClassPaths) {
3315     const char separator = *os::path_separator();
3316     const char* src = _java_class_path->value();
3317 
3318     // skip over all the leading empty paths
3319     while (*src == separator) {
3320       src ++;
3321     }
3322 
3323     char* copy = os::strdup_check_oom(src, mtArguments);
3324 
3325     // trim all trailing empty paths
3326     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3327       *tail = '\0';
3328     }
3329 
3330     char from[3] = {separator, separator, '\0'};
3331     char to  [2] = {separator, '\0'};
3332     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3333       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3334       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3335     }
3336 
3337     _java_class_path->set_writeable_value(copy);
3338     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3339   }
3340 }
3341 
3342 static bool has_jar_files(const char* directory) {
3343   DIR* dir = os::opendir(directory);
3344   if (dir == NULL) return false;
3345 
3346   struct dirent *entry;
3347   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtArguments);
3348   bool hasJarFile = false;
3349   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3350     const char* name = entry->d_name;
3351     const char* ext = name + strlen(name) - 4;
3352     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3353   }
3354   FREE_C_HEAP_ARRAY(char, dbuf);
3355   os::closedir(dir);
3356   return hasJarFile ;
3357 }
3358 
3359 static int check_non_empty_dirs(const char* path) {
3360   const char separator = *os::path_separator();
3361   const char* const end = path + strlen(path);
3362   int nonEmptyDirs = 0;
3363   while (path < end) {
3364     const char* tmp_end = strchr(path, separator);
3365     if (tmp_end == NULL) {
3366       if (has_jar_files(path)) {
3367         nonEmptyDirs++;
3368         jio_fprintf(defaultStream::output_stream(),
3369           "Non-empty directory: %s\n", path);
3370       }
3371       path = end;
3372     } else {
3373       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtArguments);
3374       memcpy(dirpath, path, tmp_end - path);
3375       dirpath[tmp_end - path] = '\0';
3376       if (has_jar_files(dirpath)) {
3377         nonEmptyDirs++;
3378         jio_fprintf(defaultStream::output_stream(),
3379           "Non-empty directory: %s\n", dirpath);
3380       }
3381       FREE_C_HEAP_ARRAY(char, dirpath);
3382       path = tmp_end + 1;
3383     }
3384   }
3385   return nonEmptyDirs;
3386 }
3387 
3388 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
3389   // check if the default lib/endorsed directory exists; if so, error
3390   char path[JVM_MAXPATHLEN];
3391   const char* fileSep = os::file_separator();
3392   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3393 
3394   if (CheckEndorsedAndExtDirs) {
3395     int nonEmptyDirs = 0;
3396     // check endorsed directory
3397     nonEmptyDirs += check_non_empty_dirs(path);
3398     // check the extension directories
3399     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3400     if (nonEmptyDirs > 0) {
3401       return JNI_ERR;
3402     }
3403   }
3404 
3405   DIR* dir = os::opendir(path);
3406   if (dir != NULL) {
3407     jio_fprintf(defaultStream::output_stream(),
3408       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3409       "in modular form will be supported via the concept of upgradeable modules.\n");
3410     os::closedir(dir);
3411     return JNI_ERR;
3412   }
3413 
3414   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3415   dir = os::opendir(path);
3416   if (dir != NULL) {
3417     jio_fprintf(defaultStream::output_stream(),
3418       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3419       "Use -classpath instead.\n.");
3420     os::closedir(dir);
3421     return JNI_ERR;
3422   }
3423 
3424   // This must be done after all arguments have been processed
3425   // and the container support has been initialized since AggressiveHeap
3426   // relies on the amount of total memory available.
3427   if (AggressiveHeap) {
3428     jint result = set_aggressive_heap_flags();
3429     if (result != JNI_OK) {
3430       return result;
3431     }
3432   }
3433 
3434   // This must be done after all arguments have been processed.
3435   // java_compiler() true means set to "NONE" or empty.
3436   if (java_compiler() && !xdebug_mode()) {
3437     // For backwards compatibility, we switch to interpreted mode if
3438     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3439     // not specified.
3440     set_mode_flags(_int);
3441   }
3442 
3443   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3444   // but like -Xint, leave compilation thresholds unaffected.
3445   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3446   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3447     set_mode_flags(_int);
3448   }
3449 
3450   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3451   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3452     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3453   }
3454 
3455 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3456   // Don't degrade server performance for footprint
3457   if (FLAG_IS_DEFAULT(UseLargePages) &&
3458       MaxHeapSize < LargePageHeapSizeThreshold) {
3459     // No need for large granularity pages w/small heaps.
3460     // Note that large pages are enabled/disabled for both the
3461     // Java heap and the code cache.
3462     FLAG_SET_DEFAULT(UseLargePages, false);
3463   }
3464 
3465 #elif defined(COMPILER2)
3466   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3467     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3468   }
3469 #endif
3470 
3471 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3472   UNSUPPORTED_OPTION(ProfileInterpreter);
3473   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3474 #endif
3475 
3476 #ifndef TIERED
3477   // Tiered compilation is undefined.
3478   UNSUPPORTED_OPTION(TieredCompilation);
3479 #endif
3480 
3481 #if INCLUDE_JVMCI
3482   if (EnableJVMCI &&
3483       !create_numbered_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
3484     return JNI_ENOMEM;
3485   }
3486 #endif
3487 
3488   // If we are running in a headless jre, force java.awt.headless property
3489   // to be true unless the property has already been set.
3490   // Also allow the OS environment variable JAVA_AWT_HEADLESS to set headless state.
3491   if (os::is_headless_jre()) {
3492     const char* headless = Arguments::get_property("java.awt.headless");
3493     if (headless == NULL) {
3494       const char *headless_env = ::getenv("JAVA_AWT_HEADLESS");
3495       if (headless_env == NULL) {
3496         if (!add_property("java.awt.headless=true")) {
3497           return JNI_ENOMEM;
3498         }
3499       } else {
3500         char buffer[256];
3501         jio_snprintf(buffer, sizeof(buffer), "java.awt.headless=%s", headless_env);
3502         if (!add_property(buffer)) {
3503           return JNI_ENOMEM;
3504         }
3505       }
3506     }
3507   }
3508 
3509   if (!check_vm_args_consistency()) {
3510     return JNI_ERR;
3511   }
3512 
3513 #if INCLUDE_JVMCI
3514   if (UseJVMCICompiler) {
3515     Compilation_mode = CompMode_server;
3516   }
3517 #endif
3518 
3519 #if INCLUDE_CDS
3520   if (DumpSharedSpaces) {
3521     // Disable biased locking now as it interferes with the clean up of
3522     // the archived Klasses and Java string objects (at dump time only).
3523     UseBiasedLocking = false;
3524   }
3525   if (UseSharedSpaces && patch_mod_javabase) {
3526     no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
3527   }
3528 #endif
3529 
3530   return JNI_OK;
3531 }
3532 
3533 // Helper class for controlling the lifetime of JavaVMInitArgs
3534 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3535 // deleted on the destruction of the ScopedVMInitArgs object.
3536 class ScopedVMInitArgs : public StackObj {
3537  private:
3538   JavaVMInitArgs _args;
3539   char*          _container_name;
3540   bool           _is_set;
3541   char*          _vm_options_file_arg;
3542 
3543  public:
3544   ScopedVMInitArgs(const char *container_name) {
3545     _args.version = JNI_VERSION_1_2;
3546     _args.nOptions = 0;
3547     _args.options = NULL;
3548     _args.ignoreUnrecognized = false;
3549     _container_name = (char *)container_name;
3550     _is_set = false;
3551     _vm_options_file_arg = NULL;
3552   }
3553 
3554   // Populates the JavaVMInitArgs object represented by this
3555   // ScopedVMInitArgs object with the arguments in options.  The
3556   // allocated memory is deleted by the destructor.  If this method
3557   // returns anything other than JNI_OK, then this object is in a
3558   // partially constructed state, and should be abandoned.
3559   jint set_args(GrowableArray<JavaVMOption>* options) {
3560     _is_set = true;
3561     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3562         JavaVMOption, options->length(), mtArguments);
3563     if (options_arr == NULL) {
3564       return JNI_ENOMEM;
3565     }
3566     _args.options = options_arr;
3567 
3568     for (int i = 0; i < options->length(); i++) {
3569       options_arr[i] = options->at(i);
3570       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3571       if (options_arr[i].optionString == NULL) {
3572         // Rely on the destructor to do cleanup.
3573         _args.nOptions = i;
3574         return JNI_ENOMEM;
3575       }
3576     }
3577 
3578     _args.nOptions = options->length();
3579     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3580     return JNI_OK;
3581   }
3582 
3583   JavaVMInitArgs* get()             { return &_args; }
3584   char* container_name()            { return _container_name; }
3585   bool  is_set()                    { return _is_set; }
3586   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3587   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3588 
3589   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3590     if (_vm_options_file_arg != NULL) {
3591       os::free(_vm_options_file_arg);
3592     }
3593     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3594   }
3595 
3596   ~ScopedVMInitArgs() {
3597     if (_vm_options_file_arg != NULL) {
3598       os::free(_vm_options_file_arg);
3599     }
3600     if (_args.options == NULL) return;
3601     for (int i = 0; i < _args.nOptions; i++) {
3602       os::free(_args.options[i].optionString);
3603     }
3604     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3605   }
3606 
3607   // Insert options into this option list, to replace option at
3608   // vm_options_file_pos (-XX:VMOptionsFile)
3609   jint insert(const JavaVMInitArgs* args,
3610               const JavaVMInitArgs* args_to_insert,
3611               const int vm_options_file_pos) {
3612     assert(_args.options == NULL, "shouldn't be set yet");
3613     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3614     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3615 
3616     int length = args->nOptions + args_to_insert->nOptions - 1;
3617     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3618               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3619     for (int i = 0; i < args->nOptions; i++) {
3620       if (i == vm_options_file_pos) {
3621         // insert the new options starting at the same place as the
3622         // -XX:VMOptionsFile option
3623         for (int j = 0; j < args_to_insert->nOptions; j++) {
3624           options->push(args_to_insert->options[j]);
3625         }
3626       } else {
3627         options->push(args->options[i]);
3628       }
3629     }
3630     // make into options array
3631     jint result = set_args(options);
3632     delete options;
3633     return result;
3634   }
3635 };
3636 
3637 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3638   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3639 }
3640 
3641 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3642   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3643 }
3644 
3645 jint Arguments::parse_options_environment_variable(const char* name,
3646                                                    ScopedVMInitArgs* vm_args) {
3647   char *buffer = ::getenv(name);
3648 
3649   // Don't check this environment variable if user has special privileges
3650   // (e.g. unix su command).
3651   if (buffer == NULL || os::have_special_privileges()) {
3652     return JNI_OK;
3653   }
3654 
3655   if ((buffer = os::strdup(buffer)) == NULL) {
3656     return JNI_ENOMEM;
3657   }
3658 
3659   jio_fprintf(defaultStream::error_stream(),
3660               "Picked up %s: %s\n", name, buffer);
3661 
3662   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3663 
3664   os::free(buffer);
3665   return retcode;
3666 }
3667 
3668 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3669   // read file into buffer
3670   int fd = ::open(file_name, O_RDONLY);
3671   if (fd < 0) {
3672     jio_fprintf(defaultStream::error_stream(),
3673                 "Could not open options file '%s'\n",
3674                 file_name);
3675     return JNI_ERR;
3676   }
3677 
3678   struct stat stbuf;
3679   int retcode = os::stat(file_name, &stbuf);
3680   if (retcode != 0) {
3681     jio_fprintf(defaultStream::error_stream(),
3682                 "Could not stat options file '%s'\n",
3683                 file_name);
3684     os::close(fd);
3685     return JNI_ERR;
3686   }
3687 
3688   if (stbuf.st_size == 0) {
3689     // tell caller there is no option data and that is ok
3690     os::close(fd);
3691     return JNI_OK;
3692   }
3693 
3694   // '+ 1' for NULL termination even with max bytes
3695   size_t bytes_alloc = stbuf.st_size + 1;
3696 
3697   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3698   if (NULL == buf) {
3699     jio_fprintf(defaultStream::error_stream(),
3700                 "Could not allocate read buffer for options file parse\n");
3701     os::close(fd);
3702     return JNI_ENOMEM;
3703   }
3704 
3705   memset(buf, 0, bytes_alloc);
3706 
3707   // Fill buffer
3708   // Use ::read() instead of os::read because os::read()
3709   // might do a thread state transition
3710   // and it is too early for that here
3711 
3712   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3713   os::close(fd);
3714   if (bytes_read < 0) {
3715     FREE_C_HEAP_ARRAY(char, buf);
3716     jio_fprintf(defaultStream::error_stream(),
3717                 "Could not read options file '%s'\n", file_name);
3718     return JNI_ERR;
3719   }
3720 
3721   if (bytes_read == 0) {
3722     // tell caller there is no option data and that is ok
3723     FREE_C_HEAP_ARRAY(char, buf);
3724     return JNI_OK;
3725   }
3726 
3727   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3728 
3729   FREE_C_HEAP_ARRAY(char, buf);
3730   return retcode;
3731 }
3732 
3733 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3734   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3735 
3736   // some pointers to help with parsing
3737   char *buffer_end = buffer + buf_len;
3738   char *opt_hd = buffer;
3739   char *wrt = buffer;
3740   char *rd = buffer;
3741 
3742   // parse all options
3743   while (rd < buffer_end) {
3744     // skip leading white space from the input string
3745     while (rd < buffer_end && isspace(*rd)) {
3746       rd++;
3747     }
3748 
3749     if (rd >= buffer_end) {
3750       break;
3751     }
3752 
3753     // Remember this is where we found the head of the token.
3754     opt_hd = wrt;
3755 
3756     // Tokens are strings of non white space characters separated
3757     // by one or more white spaces.
3758     while (rd < buffer_end && !isspace(*rd)) {
3759       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3760         int quote = *rd;                    // matching quote to look for
3761         rd++;                               // don't copy open quote
3762         while (rd < buffer_end && *rd != quote) {
3763                                             // include everything (even spaces)
3764                                             // up until the close quote
3765           *wrt++ = *rd++;                   // copy to option string
3766         }
3767 
3768         if (rd < buffer_end) {
3769           rd++;                             // don't copy close quote
3770         } else {
3771                                             // did not see closing quote
3772           jio_fprintf(defaultStream::error_stream(),
3773                       "Unmatched quote in %s\n", name);
3774           delete options;
3775           return JNI_ERR;
3776         }
3777       } else {
3778         *wrt++ = *rd++;                     // copy to option string
3779       }
3780     }
3781 
3782     // steal a white space character and set it to NULL
3783     *wrt++ = '\0';
3784     // We now have a complete token
3785 
3786     JavaVMOption option;
3787     option.optionString = opt_hd;
3788     option.extraInfo = NULL;
3789 
3790     options->append(option);                // Fill in option
3791 
3792     rd++;  // Advance to next character
3793   }
3794 
3795   // Fill out JavaVMInitArgs structure.
3796   jint status = vm_args->set_args(options);
3797 
3798   delete options;
3799   return status;
3800 }
3801 
3802 void Arguments::set_shared_spaces_flags() {
3803   if (DumpSharedSpaces) {
3804     if (FailOverToOldVerifier) {
3805       // Don't fall back to the old verifier on verification failure. If a
3806       // class fails verification with the split verifier, it might fail the
3807       // CDS runtime verifier constraint check. In that case, we don't want
3808       // to share the class. We only archive classes that pass the split verifier.
3809       FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
3810     }
3811 
3812     if (RequireSharedSpaces) {
3813       warning("Cannot dump shared archive while using shared archive");
3814     }
3815     UseSharedSpaces = false;
3816 #ifdef _LP64
3817     if (!UseCompressedOops || !UseCompressedClassPointers) {
3818       vm_exit_during_initialization(
3819         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3820     }
3821   } else {
3822     if (!UseCompressedOops || !UseCompressedClassPointers) {
3823       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3824     }
3825 #endif
3826   }
3827 }
3828 
3829 // Sharing support
3830 // Construct the path to the archive
3831 static char* get_shared_archive_path() {
3832   char *shared_archive_path;
3833   if (SharedArchiveFile == NULL) {
3834     char jvm_path[JVM_MAXPATHLEN];
3835     os::jvm_path(jvm_path, sizeof(jvm_path));
3836     char *end = strrchr(jvm_path, *os::file_separator());
3837     if (end != NULL) *end = '\0';
3838     size_t jvm_path_len = strlen(jvm_path);
3839     size_t file_sep_len = strlen(os::file_separator());
3840     const size_t len = jvm_path_len + file_sep_len + 20;
3841     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3842     if (shared_archive_path != NULL) {
3843       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3844         jvm_path, os::file_separator());
3845     }
3846   } else {
3847     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3848   }
3849   return shared_archive_path;
3850 }
3851 
3852 #ifndef PRODUCT
3853 // Determine whether LogVMOutput should be implicitly turned on.
3854 static bool use_vm_log() {
3855   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3856       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3857       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3858       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3859       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3860     return true;
3861   }
3862 
3863 #ifdef COMPILER1
3864   if (PrintC1Statistics) {
3865     return true;
3866   }
3867 #endif // COMPILER1
3868 
3869 #ifdef COMPILER2
3870   if (PrintOptoAssembly || PrintOptoStatistics) {
3871     return true;
3872   }
3873 #endif // COMPILER2
3874 
3875   return false;
3876 }
3877 
3878 #endif // PRODUCT
3879 
3880 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3881   for (int index = 0; index < args->nOptions; index++) {
3882     const JavaVMOption* option = args->options + index;
3883     const char* tail;
3884     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3885       return true;
3886     }
3887   }
3888   return false;
3889 }
3890 
3891 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3892                                        const char* vm_options_file,
3893                                        const int vm_options_file_pos,
3894                                        ScopedVMInitArgs* vm_options_file_args,
3895                                        ScopedVMInitArgs* args_out) {
3896   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3897   if (code != JNI_OK) {
3898     return code;
3899   }
3900 
3901   if (vm_options_file_args->get()->nOptions < 1) {
3902     return JNI_OK;
3903   }
3904 
3905   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3906     jio_fprintf(defaultStream::error_stream(),
3907                 "A VM options file may not refer to a VM options file. "
3908                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3909                 "options file '%s' in options container '%s' is an error.\n",
3910                 vm_options_file_args->vm_options_file_arg(),
3911                 vm_options_file_args->container_name());
3912     return JNI_EINVAL;
3913   }
3914 
3915   return args_out->insert(args, vm_options_file_args->get(),
3916                           vm_options_file_pos);
3917 }
3918 
3919 // Expand -XX:VMOptionsFile found in args_in as needed.
3920 // mod_args and args_out parameters may return values as needed.
3921 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3922                                             ScopedVMInitArgs* mod_args,
3923                                             JavaVMInitArgs** args_out) {
3924   jint code = match_special_option_and_act(args_in, mod_args);
3925   if (code != JNI_OK) {
3926     return code;
3927   }
3928 
3929   if (mod_args->is_set()) {
3930     // args_in contains -XX:VMOptionsFile and mod_args contains the
3931     // original options from args_in along with the options expanded
3932     // from the VMOptionsFile. Return a short-hand to the caller.
3933     *args_out = mod_args->get();
3934   } else {
3935     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3936   }
3937   return JNI_OK;
3938 }
3939 
3940 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3941                                              ScopedVMInitArgs* args_out) {
3942   // Remaining part of option string
3943   const char* tail;
3944   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3945 
3946   for (int index = 0; index < args->nOptions; index++) {
3947     const JavaVMOption* option = args->options + index;
3948     if (ArgumentsExt::process_options(option)) {
3949       continue;
3950     }
3951     if (match_option(option, "-XX:Flags=", &tail)) {
3952       Arguments::set_jvm_flags_file(tail);
3953       continue;
3954     }
3955     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3956       if (vm_options_file_args.found_vm_options_file_arg()) {
3957         jio_fprintf(defaultStream::error_stream(),
3958                     "The option '%s' is already specified in the options "
3959                     "container '%s' so the specification of '%s' in the "
3960                     "same options container is an error.\n",
3961                     vm_options_file_args.vm_options_file_arg(),
3962                     vm_options_file_args.container_name(),
3963                     option->optionString);
3964         return JNI_EINVAL;
3965       }
3966       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3967       // If there's a VMOptionsFile, parse that
3968       jint code = insert_vm_options_file(args, tail, index,
3969                                          &vm_options_file_args, args_out);
3970       if (code != JNI_OK) {
3971         return code;
3972       }
3973       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3974       if (args_out->is_set()) {
3975         // The VMOptions file inserted some options so switch 'args'
3976         // to the new set of options, and continue processing which
3977         // preserves "last option wins" semantics.
3978         args = args_out->get();
3979         // The first option from the VMOptionsFile replaces the
3980         // current option.  So we back track to process the
3981         // replacement option.
3982         index--;
3983       }
3984       continue;
3985     }
3986     if (match_option(option, "-XX:+PrintVMOptions")) {
3987       PrintVMOptions = true;
3988       continue;
3989     }
3990     if (match_option(option, "-XX:-PrintVMOptions")) {
3991       PrintVMOptions = false;
3992       continue;
3993     }
3994     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3995       IgnoreUnrecognizedVMOptions = true;
3996       continue;
3997     }
3998     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3999       IgnoreUnrecognizedVMOptions = false;
4000       continue;
4001     }
4002     if (match_option(option, "-XX:+PrintFlagsInitial")) {
4003       CommandLineFlags::printFlags(tty, false);
4004       vm_exit(0);
4005     }
4006     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
4007 #if INCLUDE_NMT
4008       // The launcher did not setup nmt environment variable properly.
4009       if (!MemTracker::check_launcher_nmt_support(tail)) {
4010         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
4011       }
4012 
4013       // Verify if nmt option is valid.
4014       if (MemTracker::verify_nmt_option()) {
4015         // Late initialization, still in single-threaded mode.
4016         if (MemTracker::tracking_level() >= NMT_summary) {
4017           MemTracker::init();
4018         }
4019       } else {
4020         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
4021       }
4022       continue;
4023 #else
4024       jio_fprintf(defaultStream::error_stream(),
4025         "Native Memory Tracking is not supported in this VM\n");
4026       return JNI_ERR;
4027 #endif
4028     }
4029 
4030 #ifndef PRODUCT
4031     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4032       CommandLineFlags::printFlags(tty, true);
4033       vm_exit(0);
4034     }
4035 #endif
4036 
4037     if (match_option(option, "-XX:+UseAppCDS")) {
4038       Flag* flag = Flag::find_flag("SharedArchiveFile", 17, true, true);
4039       if (flag->is_diagnostic()) {
4040         flag->clear_diagnostic();
4041       }
4042       continue;
4043     }
4044   }
4045   return JNI_OK;
4046 }
4047 
4048 static void print_options(const JavaVMInitArgs *args) {
4049   const char* tail;
4050   for (int index = 0; index < args->nOptions; index++) {
4051     const JavaVMOption *option = args->options + index;
4052     if (match_option(option, "-XX:", &tail)) {
4053       logOption(tail);
4054     }
4055   }
4056 }
4057 
4058 bool Arguments::handle_deprecated_print_gc_flags() {
4059   if (PrintGC) {
4060     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
4061   }
4062   if (PrintGCDetails) {
4063     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
4064   }
4065 
4066   if (_gc_log_filename != NULL) {
4067     // -Xloggc was used to specify a filename
4068     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
4069 
4070     LogTarget(Error, logging) target;
4071     LogStream errstream(target);
4072     return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
4073   } else if (PrintGC || PrintGCDetails) {
4074     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
4075   }
4076   return true;
4077 }
4078 
4079 void Arguments::handle_extra_cms_flags(const char* msg) {
4080   SpecialFlag flag;
4081   const char *flag_name = "UseConcMarkSweepGC";
4082   if (lookup_special_flag(flag_name, flag)) {
4083     handle_aliases_and_deprecation(flag_name, /* print warning */ true);
4084     warning("%s", msg);
4085   }
4086 }
4087 
4088 // Parse entry point called from JNI_CreateJavaVM
4089 
4090 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
4091   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4092 
4093   // Initialize ranges, constraints and writeables
4094   CommandLineFlagRangeList::init();
4095   CommandLineFlagConstraintList::init();
4096   CommandLineFlagWriteableList::init();
4097 
4098   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4099   const char* hotspotrc = ".hotspotrc";
4100   bool settings_file_specified = false;
4101   bool needs_hotspotrc_warning = false;
4102   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4103   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
4104 
4105   // Pointers to current working set of containers
4106   JavaVMInitArgs* cur_cmd_args;
4107   JavaVMInitArgs* cur_java_options_args;
4108   JavaVMInitArgs* cur_java_tool_options_args;
4109 
4110   // Containers for modified/expanded options
4111   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
4112   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4113   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
4114 
4115 
4116   jint code =
4117       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
4118   if (code != JNI_OK) {
4119     return code;
4120   }
4121 
4122   code = parse_java_options_environment_variable(&initial_java_options_args);
4123   if (code != JNI_OK) {
4124     return code;
4125   }
4126 
4127   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
4128                                      &mod_java_tool_options_args,
4129                                      &cur_java_tool_options_args);
4130   if (code != JNI_OK) {
4131     return code;
4132   }
4133 
4134   code = expand_vm_options_as_needed(initial_cmd_args,
4135                                      &mod_cmd_args,
4136                                      &cur_cmd_args);
4137   if (code != JNI_OK) {
4138     return code;
4139   }
4140 
4141   code = expand_vm_options_as_needed(initial_java_options_args.get(),
4142                                      &mod_java_options_args,
4143                                      &cur_java_options_args);
4144   if (code != JNI_OK) {
4145     return code;
4146   }
4147 
4148   const char* flags_file = Arguments::get_jvm_flags_file();
4149   settings_file_specified = (flags_file != NULL);
4150 
4151   if (IgnoreUnrecognizedVMOptions) {
4152     cur_cmd_args->ignoreUnrecognized = true;
4153     cur_java_tool_options_args->ignoreUnrecognized = true;
4154     cur_java_options_args->ignoreUnrecognized = true;
4155   }
4156 
4157   // Parse specified settings file
4158   if (settings_file_specified) {
4159     if (!process_settings_file(flags_file, true,
4160                                cur_cmd_args->ignoreUnrecognized)) {
4161       return JNI_EINVAL;
4162     }
4163   } else {
4164 #ifdef ASSERT
4165     // Parse default .hotspotrc settings file
4166     if (!process_settings_file(".hotspotrc", false,
4167                                cur_cmd_args->ignoreUnrecognized)) {
4168       return JNI_EINVAL;
4169     }
4170 #else
4171     struct stat buf;
4172     if (os::stat(hotspotrc, &buf) == 0) {
4173       needs_hotspotrc_warning = true;
4174     }
4175 #endif
4176   }
4177 
4178   if (PrintVMOptions) {
4179     print_options(cur_java_tool_options_args);
4180     print_options(cur_cmd_args);
4181     print_options(cur_java_options_args);
4182   }
4183 
4184   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4185   jint result = parse_vm_init_args(cur_java_tool_options_args,
4186                                    cur_java_options_args,
4187                                    cur_cmd_args);
4188 
4189   if (result != JNI_OK) {
4190     return result;
4191   }
4192 
4193   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4194   SharedArchivePath = get_shared_archive_path();
4195   if (SharedArchivePath == NULL) {
4196     return JNI_ENOMEM;
4197   }
4198 
4199   // Set up VerifySharedSpaces
4200   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4201     VerifySharedSpaces = true;
4202   }
4203 
4204   // Delay warning until here so that we've had a chance to process
4205   // the -XX:-PrintWarnings flag
4206   if (needs_hotspotrc_warning) {
4207     warning("%s file is present but has been ignored.  "
4208             "Run with -XX:Flags=%s to load the file.",
4209             hotspotrc, hotspotrc);
4210   }
4211 
4212   if (needs_module_property_warning) {
4213     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
4214             " names that are reserved for internal use.");
4215   }
4216 
4217 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4218   UNSUPPORTED_OPTION(UseLargePages);
4219 #endif
4220 
4221   ArgumentsExt::report_unsupported_options();
4222 
4223 #ifndef PRODUCT
4224   if (TraceBytecodesAt != 0) {
4225     TraceBytecodes = true;
4226   }
4227   if (CountCompiledCalls) {
4228     if (UseCounterDecay) {
4229       warning("UseCounterDecay disabled because CountCalls is set");
4230       UseCounterDecay = false;
4231     }
4232   }
4233 #endif // PRODUCT
4234 
4235   if (ScavengeRootsInCode == 0) {
4236     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4237       warning("Forcing ScavengeRootsInCode non-zero");
4238     }
4239     ScavengeRootsInCode = 1;
4240   }
4241 
4242   if (!handle_deprecated_print_gc_flags()) {
4243     return JNI_EINVAL;
4244   }
4245 
4246   // Set object alignment values.
4247   set_object_alignment();
4248 
4249 #if !INCLUDE_CDS
4250   if (DumpSharedSpaces || RequireSharedSpaces) {
4251     jio_fprintf(defaultStream::error_stream(),
4252       "Shared spaces are not supported in this VM\n");
4253     return JNI_ERR;
4254   }
4255   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) ||
4256       log_is_enabled(Info, cds)) {
4257     warning("Shared spaces are not supported in this VM");
4258     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4259     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
4260   }
4261   no_shared_spaces("CDS Disabled");
4262 #endif // INCLUDE_CDS
4263 
4264   return JNI_OK;
4265 }
4266 
4267 jint Arguments::apply_ergo() {
4268   // Set flags based on ergonomics.
4269   jint result = set_ergonomics_flags();
4270   if (result != JNI_OK) return result;
4271 
4272 #if INCLUDE_JVMCI
4273   set_jvmci_specific_flags();
4274 #endif
4275 
4276   set_shared_spaces_flags();
4277 
4278   // Check the GC selections again.
4279   if (!check_gc_consistency()) {
4280     return JNI_EINVAL;
4281   }
4282 
4283   if (TieredCompilation) {
4284     set_tiered_flags();
4285   } else {
4286     int max_compilation_policy_choice = 1;
4287 #ifdef COMPILER2
4288     if (is_server_compilation_mode_vm()) {
4289       max_compilation_policy_choice = 2;
4290     }
4291 #endif
4292     // Check if the policy is valid.
4293     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4294       vm_exit_during_initialization(
4295         "Incompatible compilation policy selected", NULL);
4296     }
4297     // Scale CompileThreshold
4298     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4299     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4300       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4301     }
4302   }
4303 
4304 #ifdef COMPILER2
4305 #ifndef PRODUCT
4306   if (PrintIdealGraphLevel > 0) {
4307     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4308   }
4309 #endif
4310 #endif
4311 
4312   // Set heap size based on available physical memory
4313   set_heap_size();
4314 
4315   ArgumentsExt::set_gc_specific_flags();
4316 
4317   // Initialize Metaspace flags and alignments
4318   Metaspace::ergo_initialize();
4319 
4320   // Set bytecode rewriting flags
4321   set_bytecode_flags();
4322 
4323   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4324   jint code = set_aggressive_opts_flags();
4325   if (code != JNI_OK) {
4326     return code;
4327   }
4328 
4329   // Turn off biased locking for locking debug mode flags,
4330   // which are subtly different from each other but neither works with
4331   // biased locking
4332   if (UseHeavyMonitors
4333 #ifdef COMPILER1
4334       || !UseFastLocking
4335 #endif // COMPILER1
4336 #if INCLUDE_JVMCI
4337       || !JVMCIUseFastLocking
4338 #endif
4339     ) {
4340     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4341       // flag set to true on command line; warn the user that they
4342       // can't enable biased locking here
4343       warning("Biased Locking is not supported with locking debug flags"
4344               "; ignoring UseBiasedLocking flag." );
4345     }
4346     UseBiasedLocking = false;
4347   }
4348 
4349 #ifdef CC_INTERP
4350   // Clear flags not supported on zero.
4351   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4352   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4353   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4354   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4355 #endif // CC_INTERP
4356 
4357 #ifdef COMPILER2
4358   if (!EliminateLocks) {
4359     EliminateNestedLocks = false;
4360   }
4361   if (!Inline) {
4362     IncrementalInline = false;
4363   }
4364 #ifndef PRODUCT
4365   if (!IncrementalInline) {
4366     AlwaysIncrementalInline = false;
4367   }
4368 #endif
4369   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4370     // nothing to use the profiling, turn if off
4371     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4372   }
4373 #endif
4374 
4375   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4376     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4377     DebugNonSafepoints = true;
4378   }
4379 
4380   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4381     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4382   }
4383 
4384   if (UseOnStackReplacement && !UseLoopCounter) {
4385     warning("On-stack-replacement requires loop counters; enabling loop counters");
4386     FLAG_SET_DEFAULT(UseLoopCounter, true);
4387   }
4388 
4389 #ifndef PRODUCT
4390   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4391     if (use_vm_log()) {
4392       LogVMOutput = true;
4393     }
4394   }
4395 #endif // PRODUCT
4396 
4397   if (PrintCommandLineFlags) {
4398     CommandLineFlags::printSetFlags(tty);
4399   }
4400 
4401   // Apply CPU specific policy for the BiasedLocking
4402   if (UseBiasedLocking) {
4403     if (!VM_Version::use_biased_locking() &&
4404         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4405       UseBiasedLocking = false;
4406     }
4407   }
4408 #ifdef COMPILER2
4409   if (!UseBiasedLocking || EmitSync != 0) {
4410     UseOptoBiasInlining = false;
4411   }
4412 #endif
4413 
4414   // ThreadLocalHandshakesConstraintFunc handles the constraints.
4415   if (FLAG_IS_DEFAULT(ThreadLocalHandshakes) || !SafepointMechanism::supports_thread_local_poll()) {
4416     log_debug(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
4417   } else {
4418     log_info(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
4419   }
4420 
4421   return JNI_OK;
4422 }
4423 
4424 jint Arguments::adjust_after_os() {
4425   if (UseNUMA) {
4426     if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
4427       FLAG_SET_ERGO(bool, UseNUMA, false);
4428     } else if (UseParallelGC || UseParallelOldGC) {
4429       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4430          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4431       }
4432     }
4433     // UseNUMAInterleaving is set to ON for all collectors and
4434     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4435     // such as the parallel collector for Linux and Solaris will
4436     // interleave old gen and survivor spaces on top of NUMA
4437     // allocation policy for the eden space.
4438     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4439     // all platforms and ParallelGC on Windows will interleave all
4440     // of the heap spaces across NUMA nodes.
4441     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4442       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4443     }
4444   }
4445   return JNI_OK;
4446 }
4447 
4448 int Arguments::PropertyList_count(SystemProperty* pl) {
4449   int count = 0;
4450   while(pl != NULL) {
4451     count++;
4452     pl = pl->next();
4453   }
4454   return count;
4455 }
4456 
4457 // Return the number of readable properties.
4458 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4459   int count = 0;
4460   while(pl != NULL) {
4461     if (pl->is_readable()) {
4462       count++;
4463     }
4464     pl = pl->next();
4465   }
4466   return count;
4467 }
4468 
4469 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4470   assert(key != NULL, "just checking");
4471   SystemProperty* prop;
4472   for (prop = pl; prop != NULL; prop = prop->next()) {
4473     if (strcmp(key, prop->key()) == 0) return prop->value();
4474   }
4475   return NULL;
4476 }
4477 
4478 // Return the value of the requested property provided that it is a readable property.
4479 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4480   assert(key != NULL, "just checking");
4481   SystemProperty* prop;
4482   // Return the property value if the keys match and the property is not internal or
4483   // it's the special internal property "jdk.boot.class.path.append".
4484   for (prop = pl; prop != NULL; prop = prop->next()) {
4485     if (strcmp(key, prop->key()) == 0) {
4486       if (!prop->internal()) {
4487         return prop->value();
4488       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4489         return prop->value();
4490       } else {
4491         // Property is internal and not jdk.boot.class.path.append so return NULL.
4492         return NULL;
4493       }
4494     }
4495   }
4496   return NULL;
4497 }
4498 
4499 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4500   int count = 0;
4501   const char* ret_val = NULL;
4502 
4503   while(pl != NULL) {
4504     if(count >= index) {
4505       ret_val = pl->key();
4506       break;
4507     }
4508     count++;
4509     pl = pl->next();
4510   }
4511 
4512   return ret_val;
4513 }
4514 
4515 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4516   int count = 0;
4517   char* ret_val = NULL;
4518 
4519   while(pl != NULL) {
4520     if(count >= index) {
4521       ret_val = pl->value();
4522       break;
4523     }
4524     count++;
4525     pl = pl->next();
4526   }
4527 
4528   return ret_val;
4529 }
4530 
4531 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4532   SystemProperty* p = *plist;
4533   if (p == NULL) {
4534     *plist = new_p;
4535   } else {
4536     while (p->next() != NULL) {
4537       p = p->next();
4538     }
4539     p->set_next(new_p);
4540   }
4541 }
4542 
4543 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4544                                  bool writeable, bool internal) {
4545   if (plist == NULL)
4546     return;
4547 
4548   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4549   PropertyList_add(plist, new_p);
4550 }
4551 
4552 void Arguments::PropertyList_add(SystemProperty *element) {
4553   PropertyList_add(&_system_properties, element);
4554 }
4555 
4556 // This add maintains unique property key in the list.
4557 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4558                                         PropertyAppendable append, PropertyWriteable writeable,
4559                                         PropertyInternal internal) {
4560   if (plist == NULL)
4561     return;
4562 
4563   // If property key exist then update with new value.
4564   SystemProperty* prop;
4565   for (prop = *plist; prop != NULL; prop = prop->next()) {
4566     if (strcmp(k, prop->key()) == 0) {
4567       if (append == AppendProperty) {
4568         prop->append_value(v);
4569       } else {
4570         prop->set_value(v);
4571       }
4572       return;
4573     }
4574   }
4575 
4576   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4577 }
4578 
4579 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4580 // Returns true if all of the source pointed by src has been copied over to
4581 // the destination buffer pointed by buf. Otherwise, returns false.
4582 // Notes:
4583 // 1. If the length (buflen) of the destination buffer excluding the
4584 // NULL terminator character is not long enough for holding the expanded
4585 // pid characters, it also returns false instead of returning the partially
4586 // expanded one.
4587 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4588 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4589                                 char* buf, size_t buflen) {
4590   const char* p = src;
4591   char* b = buf;
4592   const char* src_end = &src[srclen];
4593   char* buf_end = &buf[buflen - 1];
4594 
4595   while (p < src_end && b < buf_end) {
4596     if (*p == '%') {
4597       switch (*(++p)) {
4598       case '%':         // "%%" ==> "%"
4599         *b++ = *p++;
4600         break;
4601       case 'p':  {       //  "%p" ==> current process id
4602         // buf_end points to the character before the last character so
4603         // that we could write '\0' to the end of the buffer.
4604         size_t buf_sz = buf_end - b + 1;
4605         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4606 
4607         // if jio_snprintf fails or the buffer is not long enough to hold
4608         // the expanded pid, returns false.
4609         if (ret < 0 || ret >= (int)buf_sz) {
4610           return false;
4611         } else {
4612           b += ret;
4613           assert(*b == '\0', "fail in copy_expand_pid");
4614           if (p == src_end && b == buf_end + 1) {
4615             // reach the end of the buffer.
4616             return true;
4617           }
4618         }
4619         p++;
4620         break;
4621       }
4622       default :
4623         *b++ = '%';
4624       }
4625     } else {
4626       *b++ = *p++;
4627     }
4628   }
4629   *b = '\0';
4630   return (p == src_end); // return false if not all of the source was copied
4631 }