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