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