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.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/safepoint.hpp"
  54 #include "runtime/safepointMechanism.hpp"
  55 #include "runtime/vm_version.hpp"
  56 #include "services/management.hpp"
  57 #include "services/memTracker.hpp"
  58 #include "utilities/align.hpp"
  59 #include "utilities/defaultStream.hpp"
  60 #include "utilities/macros.hpp"
  61 #include "utilities/stringUtils.hpp"
  62 #if INCLUDE_JVMCI
  63 #include "jvmci/jvmciRuntime.hpp"
  64 #endif
  65 
  66 // Note: This is a special bug reporting site for the JVM
  67 #ifdef VENDOR_URL_VM_BUG
  68 # define DEFAULT_VENDOR_URL_BUG VENDOR_URL_VM_BUG
  69 #else
  70 # define DEFAULT_VENDOR_URL_BUG "http://bugreport.java.com/bugreport/crash.jsp"
  71 #endif
  72 #define DEFAULT_JAVA_LAUNCHER  "generic"
  73 
  74 char*  Arguments::_jvm_flags_file               = NULL;
  75 char** Arguments::_jvm_flags_array              = NULL;
  76 int    Arguments::_num_jvm_flags                = 0;
  77 char** Arguments::_jvm_args_array               = NULL;
  78 int    Arguments::_num_jvm_args                 = 0;
  79 char*  Arguments::_java_command                 = NULL;
  80 SystemProperty* Arguments::_system_properties   = NULL;
  81 const char*  Arguments::_gc_log_filename        = NULL;
  82 size_t Arguments::_conservative_max_heap_alignment = 0;
  83 size_t Arguments::_min_heap_size                = 0;
  84 Arguments::Mode Arguments::_mode                = _mixed;
  85 bool   Arguments::_java_compiler                = false;
  86 bool   Arguments::_xdebug_mode                  = false;
  87 const char*  Arguments::_java_vendor_url_bug    = DEFAULT_VENDOR_URL_BUG;
  88 const char*  Arguments::_sun_java_launcher      = DEFAULT_JAVA_LAUNCHER;
  89 int    Arguments::_sun_java_launcher_pid        = -1;
  90 bool   Arguments::_sun_java_launcher_is_altjvm  = false;
  91 
  92 // These parameters are reset in method parse_vm_init_args()
  93 bool   Arguments::_AlwaysCompileLoopMethods     = AlwaysCompileLoopMethods;
  94 bool   Arguments::_UseOnStackReplacement        = UseOnStackReplacement;
  95 bool   Arguments::_BackgroundCompilation        = BackgroundCompilation;
  96 bool   Arguments::_ClipInlining                 = ClipInlining;
  97 intx   Arguments::_Tier3InvokeNotifyFreqLog     = Tier3InvokeNotifyFreqLog;
  98 intx   Arguments::_Tier4InvocationThreshold     = Tier4InvocationThreshold;
  99 
 100 char*  Arguments::SharedArchivePath             = NULL;
 101 
 102 AgentLibraryList Arguments::_libraryList;
 103 AgentLibraryList Arguments::_agentList;
 104 
 105 abort_hook_t     Arguments::_abort_hook         = NULL;
 106 exit_hook_t      Arguments::_exit_hook          = NULL;
 107 vfprintf_hook_t  Arguments::_vfprintf_hook      = NULL;
 108 
 109 
 110 SystemProperty *Arguments::_sun_boot_library_path = NULL;
 111 SystemProperty *Arguments::_java_library_path = NULL;
 112 SystemProperty *Arguments::_java_home = NULL;
 113 SystemProperty *Arguments::_java_class_path = NULL;
 114 SystemProperty *Arguments::_jdk_boot_class_path_append = NULL;
 115 
 116 GrowableArray<ModulePatchPath*> *Arguments::_patch_mod_prefix = NULL;
 117 PathString *Arguments::_system_boot_class_path = NULL;
 118 bool Arguments::_has_jimage = false;
 119 
 120 char* Arguments::_ext_dirs = NULL;
 121 
 122 bool PathString::set_value(const char *value) {
 123   if (_value != NULL) {
 124     FreeHeap(_value);
 125   }
 126   _value = AllocateHeap(strlen(value)+1, mtArguments);
 127   assert(_value != NULL, "Unable to allocate space for new path value");
 128   if (_value != NULL) {
 129     strcpy(_value, value);
 130   } else {
 131     // not able to allocate
 132     return false;
 133   }
 134   return true;
 135 }
 136 
 137 void PathString::append_value(const char *value) {
 138   char *sp;
 139   size_t len = 0;
 140   if (value != NULL) {
 141     len = strlen(value);
 142     if (_value != NULL) {
 143       len += strlen(_value);
 144     }
 145     sp = AllocateHeap(len+2, mtArguments);
 146     assert(sp != NULL, "Unable to allocate space for new append path value");
 147     if (sp != NULL) {
 148       if (_value != NULL) {
 149         strcpy(sp, _value);
 150         strcat(sp, os::path_separator());
 151         strcat(sp, value);
 152         FreeHeap(_value);
 153       } else {
 154         strcpy(sp, value);
 155       }
 156       _value = sp;
 157     }
 158   }
 159 }
 160 
 161 PathString::PathString(const char* value) {
 162   if (value == NULL) {
 163     _value = NULL;
 164   } else {
 165     _value = AllocateHeap(strlen(value)+1, mtArguments);
 166     strcpy(_value, value);
 167   }
 168 }
 169 
 170 PathString::~PathString() {
 171   if (_value != NULL) {
 172     FreeHeap(_value);
 173     _value = NULL;
 174   }
 175 }
 176 
 177 ModulePatchPath::ModulePatchPath(const char* module_name, const char* path) {
 178   assert(module_name != NULL && path != NULL, "Invalid module name or path value");
 179   size_t len = strlen(module_name) + 1;
 180   _module_name = AllocateHeap(len, mtInternal);
 181   strncpy(_module_name, module_name, len); // copy the trailing null
 182   _path =  new PathString(path);
 183 }
 184 
 185 ModulePatchPath::~ModulePatchPath() {
 186   if (_module_name != NULL) {
 187     FreeHeap(_module_name);
 188     _module_name = NULL;
 189   }
 190   if (_path != NULL) {
 191     delete _path;
 192     _path = NULL;
 193   }
 194 }
 195 
 196 SystemProperty::SystemProperty(const char* key, const char* value, bool writeable, bool internal) : PathString(value) {
 197   if (key == NULL) {
 198     _key = NULL;
 199   } else {
 200     _key = AllocateHeap(strlen(key)+1, mtArguments);
 201     strcpy(_key, key);
 202   }
 203   _next = NULL;
 204   _internal = internal;
 205   _writeable = writeable;
 206 }
 207 
 208 AgentLibrary::AgentLibrary(const char* name, const char* options,
 209                bool is_absolute_path, void* os_lib,
 210                bool instrument_lib) {
 211   _name = AllocateHeap(strlen(name)+1, mtArguments);
 212   strcpy(_name, name);
 213   if (options == NULL) {
 214     _options = NULL;
 215   } else {
 216     _options = AllocateHeap(strlen(options)+1, mtArguments);
 217     strcpy(_options, options);
 218   }
 219   _is_absolute_path = is_absolute_path;
 220   _os_lib = os_lib;
 221   _next = NULL;
 222   _state = agent_invalid;
 223   _is_static_lib = false;
 224   _is_instrument_lib = instrument_lib;
 225 }
 226 
 227 // Check if head of 'option' matches 'name', and sets 'tail' to the remaining
 228 // part of the option string.
 229 static bool match_option(const JavaVMOption *option, const char* name,
 230                          const char** tail) {
 231   size_t len = strlen(name);
 232   if (strncmp(option->optionString, name, len) == 0) {
 233     *tail = option->optionString + len;
 234     return true;
 235   } else {
 236     return false;
 237   }
 238 }
 239 
 240 // Check if 'option' matches 'name'. No "tail" is allowed.
 241 static bool match_option(const JavaVMOption *option, const char* name) {
 242   const char* tail = NULL;
 243   bool result = match_option(option, name, &tail);
 244   if (tail != NULL && *tail == '\0') {
 245     return result;
 246   } else {
 247     return false;
 248   }
 249 }
 250 
 251 // Return true if any of the strings in null-terminated array 'names' matches.
 252 // If tail_allowed is true, then the tail must begin with a colon; otherwise,
 253 // the option must match exactly.
 254 static bool match_option(const JavaVMOption* option, const char** names, const char** tail,
 255   bool tail_allowed) {
 256   for (/* empty */; *names != NULL; ++names) {
 257   if (match_option(option, *names, tail)) {
 258       if (**tail == '\0' || (tail_allowed && **tail == ':')) {
 259         return true;
 260       }
 261     }
 262   }
 263   return false;
 264 }
 265 
 266 static void logOption(const char* opt) {
 267   if (PrintVMOptions) {
 268     jio_fprintf(defaultStream::output_stream(), "VM option '%s'\n", opt);
 269   }
 270 }
 271 
 272 bool needs_module_property_warning = false;
 273 
 274 #define MODULE_PROPERTY_PREFIX "jdk.module."
 275 #define MODULE_PROPERTY_PREFIX_LEN 11
 276 #define ADDEXPORTS "addexports"
 277 #define ADDEXPORTS_LEN 10
 278 #define ADDREADS "addreads"
 279 #define ADDREADS_LEN 8
 280 #define ADDOPENS "addopens"
 281 #define ADDOPENS_LEN 8
 282 #define PATCH "patch"
 283 #define PATCH_LEN 5
 284 #define ADDMODS "addmods"
 285 #define ADDMODS_LEN 7
 286 #define LIMITMODS "limitmods"
 287 #define LIMITMODS_LEN 9
 288 #define PATH "path"
 289 #define PATH_LEN 4
 290 #define UPGRADE_PATH "upgrade.path"
 291 #define UPGRADE_PATH_LEN 12
 292 
 293 void Arguments::add_init_library(const char* name, char* options) {
 294   _libraryList.add(new AgentLibrary(name, options, false, NULL));
 295 }
 296 
 297 void Arguments::add_init_agent(const char* name, char* options, bool absolute_path) {
 298   _agentList.add(new AgentLibrary(name, options, absolute_path, NULL));
 299 }
 300 
 301 void Arguments::add_instrument_agent(const char* name, char* options, bool absolute_path) {
 302   _agentList.add(new AgentLibrary(name, options, absolute_path, NULL, true));
 303 }
 304 
 305 // Late-binding agents not started via arguments
 306 void Arguments::add_loaded_agent(AgentLibrary *agentLib) {
 307   _agentList.add(agentLib);
 308 }
 309 
 310 void Arguments::add_loaded_agent(const char* name, char* options, bool absolute_path, void* os_lib) {
 311   _agentList.add(new AgentLibrary(name, options, absolute_path, os_lib));
 312 }
 313 
 314 // Return TRUE if option matches 'property', or 'property=', or 'property.'.
 315 static bool matches_property_suffix(const char* option, const char* property, size_t len) {
 316   return ((strncmp(option, property, len) == 0) &&
 317           (option[len] == '=' || option[len] == '.' || option[len] == '\0'));
 318 }
 319 
 320 // Return true if property starts with "jdk.module." and its ensuing chars match
 321 // any of the reserved module properties.
 322 // property should be passed without the leading "-D".
 323 bool Arguments::is_internal_module_property(const char* property) {
 324   assert((strncmp(property, "-D", 2) != 0), "Unexpected leading -D");
 325   if  (strncmp(property, MODULE_PROPERTY_PREFIX, MODULE_PROPERTY_PREFIX_LEN) == 0) {
 326     const char* property_suffix = property + MODULE_PROPERTY_PREFIX_LEN;
 327     if (matches_property_suffix(property_suffix, ADDEXPORTS, ADDEXPORTS_LEN) ||
 328         matches_property_suffix(property_suffix, ADDREADS, ADDREADS_LEN) ||
 329         matches_property_suffix(property_suffix, ADDOPENS, ADDOPENS_LEN) ||
 330         matches_property_suffix(property_suffix, PATCH, PATCH_LEN) ||
 331         matches_property_suffix(property_suffix, ADDMODS, ADDMODS_LEN) ||
 332         matches_property_suffix(property_suffix, LIMITMODS, LIMITMODS_LEN) ||
 333         matches_property_suffix(property_suffix, PATH, PATH_LEN) ||
 334         matches_property_suffix(property_suffix, UPGRADE_PATH, UPGRADE_PATH_LEN)) {
 335       return true;
 336     }
 337   }
 338   return false;
 339 }
 340 
 341 // Process java launcher properties.
 342 void Arguments::process_sun_java_launcher_properties(JavaVMInitArgs* args) {
 343   // See if sun.java.launcher, sun.java.launcher.is_altjvm or
 344   // sun.java.launcher.pid is defined.
 345   // Must do this before setting up other system properties,
 346   // as some of them may depend on launcher type.
 347   for (int index = 0; index < args->nOptions; index++) {
 348     const JavaVMOption* option = args->options + index;
 349     const char* tail;
 350 
 351     if (match_option(option, "-Dsun.java.launcher=", &tail)) {
 352       process_java_launcher_argument(tail, option->extraInfo);
 353       continue;
 354     }
 355     if (match_option(option, "-Dsun.java.launcher.is_altjvm=", &tail)) {
 356       if (strcmp(tail, "true") == 0) {
 357         _sun_java_launcher_is_altjvm = true;
 358       }
 359       continue;
 360     }
 361     if (match_option(option, "-Dsun.java.launcher.pid=", &tail)) {
 362       _sun_java_launcher_pid = atoi(tail);
 363       continue;
 364     }
 365   }
 366 }
 367 
 368 // Initialize system properties key and value.
 369 void Arguments::init_system_properties() {
 370 
 371   // Set up _system_boot_class_path which is not a property but
 372   // relies heavily on argument processing and the jdk.boot.class.path.append
 373   // property. It is used to store the underlying system boot class path.
 374   _system_boot_class_path = new PathString(NULL);
 375 
 376   PropertyList_add(&_system_properties, new SystemProperty("java.vm.specification.name",
 377                                                            "Java Virtual Machine Specification",  false));
 378   PropertyList_add(&_system_properties, new SystemProperty("java.vm.version", VM_Version::vm_release(),  false));
 379   PropertyList_add(&_system_properties, new SystemProperty("java.vm.name", VM_Version::vm_name(),  false));
 380   PropertyList_add(&_system_properties, new SystemProperty("java.vm.info", VM_Version::vm_info_string(),  true));
 381   PropertyList_add(&_system_properties, new SystemProperty("jdk.debug", VM_Version::jdk_debug_level(),  false));
 382 
 383   // Following are JVMTI agent writable properties.
 384   // Properties values are set to NULL and they are
 385   // os specific they are initialized in os::init_system_properties_values().
 386   _sun_boot_library_path = new SystemProperty("sun.boot.library.path", NULL,  true);
 387   _java_library_path = new SystemProperty("java.library.path", NULL,  true);
 388   _java_home =  new SystemProperty("java.home", NULL,  true);
 389   _java_class_path = new SystemProperty("java.class.path", "",  true);
 390   // jdk.boot.class.path.append is a non-writeable, internal property.
 391   // It can only be set by either:
 392   //    - -Xbootclasspath/a:
 393   //    - AddToBootstrapClassLoaderSearch during JVMTI OnLoad phase
 394   _jdk_boot_class_path_append = new SystemProperty("jdk.boot.class.path.append", "", false, true);
 395 
 396   // Add to System Property list.
 397   PropertyList_add(&_system_properties, _sun_boot_library_path);
 398   PropertyList_add(&_system_properties, _java_library_path);
 399   PropertyList_add(&_system_properties, _java_home);
 400   PropertyList_add(&_system_properties, _java_class_path);
 401   PropertyList_add(&_system_properties, _jdk_boot_class_path_append);
 402 
 403   // Set OS specific system properties values
 404   os::init_system_properties_values();
 405 }
 406 
 407 // Update/Initialize System properties after JDK version number is known
 408 void Arguments::init_version_specific_system_properties() {
 409   enum { bufsz = 16 };
 410   char buffer[bufsz];
 411   const char* spec_vendor = "Oracle Corporation";
 412   uint32_t spec_version = JDK_Version::current().major_version();
 413 
 414   jio_snprintf(buffer, bufsz, UINT32_FORMAT, spec_version);
 415 
 416   PropertyList_add(&_system_properties,
 417       new SystemProperty("java.vm.specification.vendor",  spec_vendor, false));
 418   PropertyList_add(&_system_properties,
 419       new SystemProperty("java.vm.specification.version", buffer, false));
 420   PropertyList_add(&_system_properties,
 421       new SystemProperty("java.vm.vendor", VM_Version::vm_vendor(),  false));
 422 }
 423 
 424 /*
 425  *  -XX argument processing:
 426  *
 427  *  -XX arguments are defined in several places, such as:
 428  *      globals.hpp, globals_<cpu>.hpp, globals_<os>.hpp, <compiler>_globals.hpp, or <gc>_globals.hpp.
 429  *  -XX arguments are parsed in parse_argument().
 430  *  -XX argument bounds checking is done in check_vm_args_consistency().
 431  *
 432  * Over time -XX arguments may change. There are mechanisms to handle common cases:
 433  *
 434  *      ALIASED: An option that is simply another name for another option. This is often
 435  *               part of the process of deprecating a flag, but not all aliases need
 436  *               to be deprecated.
 437  *
 438  *               Create an alias for an option by adding the old and new option names to the
 439  *               "aliased_jvm_flags" table. Delete the old variable from globals.hpp (etc).
 440  *
 441  *   DEPRECATED: An option that is supported, but a warning is printed to let the user know that
 442  *               support may be removed in the future. Both regular and aliased options may be
 443  *               deprecated.
 444  *
 445  *               Add a deprecation warning for an option (or alias) by adding an entry in the
 446  *               "special_jvm_flags" table and setting the "deprecated_in" field.
 447  *               Often an option "deprecated" in one major release will
 448  *               be made "obsolete" in the next. In this case the entry should also have its
 449  *               "obsolete_in" field set.
 450  *
 451  *     OBSOLETE: An option that has been removed (and deleted from globals.hpp), but is still accepted
 452  *               on the command line. A warning is printed to let the user know that option might not
 453  *               be accepted in the future.
 454  *
 455  *               Add an obsolete warning for an option by adding an entry in the "special_jvm_flags"
 456  *               table and setting the "obsolete_in" field.
 457  *
 458  *      EXPIRED: A deprecated or obsolete option that has an "accept_until" version less than or equal
 459  *               to the current JDK version. The system will flatly refuse to admit the existence of
 460  *               the flag. This allows a flag to die automatically over JDK releases.
 461  *
 462  *               Note that manual cleanup of expired options should be done at major JDK version upgrades:
 463  *                  - Newly expired options should be removed from the special_jvm_flags and aliased_jvm_flags tables.
 464  *                  - Newly obsolete or expired deprecated options should have their global variable
 465  *                    definitions removed (from globals.hpp, etc) and related implementations removed.
 466  *
 467  * Recommended approach for removing options:
 468  *
 469  * To remove options commonly used by customers (e.g. product, commercial -XX options), use
 470  * the 3-step model adding major release numbers to the deprecate, obsolete and expire columns.
 471  *
 472  * To remove internal options (e.g. diagnostic, experimental, develop options), use
 473  * a 2-step model adding major release numbers to the obsolete and expire columns.
 474  *
 475  * To change the name of an option, use the alias table as well as a 2-step
 476  * model adding major release numbers to the deprecate and expire columns.
 477  * Think twice about aliasing commonly used customer options.
 478  *
 479  * There are times when it is appropriate to leave a future release number as undefined.
 480  *
 481  * Tests:  Aliases should be tested in VMAliasOptions.java.
 482  *         Deprecated options should be tested in VMDeprecatedOptions.java.
 483  */
 484 
 485 // The special_jvm_flags table declares options that are being deprecated and/or obsoleted. The
 486 // "deprecated_in" or "obsolete_in" fields may be set to "undefined", but not both.
 487 // When the JDK version reaches 'deprecated_in' limit, the JVM will process this flag on
 488 // the command-line as usual, but will issue a warning.
 489 // When the JDK version reaches 'obsolete_in' limit, the JVM will continue accepting this flag on
 490 // the command-line, while issuing a warning and ignoring the flag value.
 491 // Once the JDK version reaches 'expired_in' limit, the JVM will flatly refuse to admit the
 492 // existence of the flag.
 493 //
 494 // MANUAL CLEANUP ON JDK VERSION UPDATES:
 495 // This table ensures that the handling of options will update automatically when the JDK
 496 // version is incremented, but the source code needs to be cleanup up manually:
 497 // - As "deprecated" options age into "obsolete" or "expired" options, the associated "globals"
 498 //   variable should be removed, as well as users of the variable.
 499 // - As "deprecated" options age into "obsolete" options, move the entry into the
 500 //   "Obsolete Flags" section of the table.
 501 // - All expired options should be removed from the table.
 502 static SpecialFlag const special_jvm_flags[] = {
 503   // -------------- Deprecated Flags --------------
 504   // --- Non-alias flags - sorted by obsolete_in then expired_in:
 505   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
 506   { "UseConcMarkSweepGC",           JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 507   { "AssumeMP",                     JDK_Version::jdk(10),JDK_Version::undefined(), JDK_Version::undefined() },
 508   { "MonitorInUseLists",            JDK_Version::jdk(10),JDK_Version::undefined(), JDK_Version::undefined() },
 509   { "MaxRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 510   { "MinRAMFraction",               JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 511   { "InitialRAMFraction",           JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 512   { "UseMembar",                    JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
 513   { "IgnoreUnverifiableClassesDuringDump", JDK_Version::jdk(10),  JDK_Version::undefined(), JDK_Version::undefined() },
 514   { "CheckEndorsedAndExtDirs",      JDK_Version::jdk(10), JDK_Version::undefined(), JDK_Version::undefined() },
 515   { "CompilerThreadHintNoPreempt",  JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 516   { "VMThreadHintNoPreempt",        JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 517   { "PrintSafepointStatistics",     JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 518   { "PrintSafepointStatisticsTimeout", JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 519   { "PrintSafepointStatisticsCount",JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 520   { "AggressiveOpts",               JDK_Version::jdk(11), JDK_Version::jdk(12), JDK_Version::jdk(13) },
 521 
 522   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
 523   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8),  JDK_Version::undefined(), JDK_Version::undefined() },
 524   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9),  JDK_Version::undefined(), JDK_Version::undefined() },
 525   { "MustCallLoadClassInternal",    JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 526   { "UnsyncloadClass",              JDK_Version::jdk(10), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 527 
 528   // -------------- Obsolete Flags - sorted by expired_in --------------
 529   { "ConvertSleepToYield",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 530   { "ConvertYieldToSleep",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 531   { "MinSleepInterval",              JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
 532   { "CheckAssertionStatusDirectives",JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 533   { "PrintMallocFree",               JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 534   { "PrintMalloc",                   JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 535   { "ShowSafepointMsgs",             JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 536   { "FastTLABRefill",                JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 537   { "SafepointSpinBeforeYield",      JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 538   { "DeferThrSuspendLoopCount",      JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 539   { "DeferPollingPageLoopCount",     JDK_Version::jdk(10),     JDK_Version::jdk(11), JDK_Version::jdk(12) },
 540   { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 541   { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 542   { "SharedReadWriteSize",           JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 543   { "SharedReadOnlySize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 544   { "SharedMiscDataSize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 545   { "SharedMiscCodeSize",            JDK_Version::undefined(), JDK_Version::jdk(10), JDK_Version::undefined() },
 546   { "UseUTCFileTimestamp",           JDK_Version::undefined(), JDK_Version::jdk(11), JDK_Version::jdk(12) },
 547 
 548 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
 549   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
 550   { "dep > exp ",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(8) },
 551   { "obs > exp ",                   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(8) },
 552   { "not deprecated or obsolete",   JDK_Version::undefined(), JDK_Version::undefined(), JDK_Version::jdk(9) },
 553   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 554   { "dup option",                   JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
 555   { "BytecodeVerificationRemote",   JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::undefined() },
 556 #endif
 557 
 558   { NULL, JDK_Version(0), JDK_Version(0) }
 559 };
 560 
 561 // Flags that are aliases for other flags.
 562 typedef struct {
 563   const char* alias_name;
 564   const char* real_name;
 565 } AliasedFlag;
 566 
 567 static AliasedFlag const aliased_jvm_flags[] = {
 568   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
 569   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
 570   { NULL, NULL}
 571 };
 572 
 573 // NOTE: A compatibility request will be necessary for each alias to be removed.
 574 static AliasedLoggingFlag const aliased_logging_flags[] = {
 575   { "PrintCompressedOopsMode",   LogLevel::Info,  true,  LOG_TAGS(gc, heap, coops) },
 576   { "PrintSharedSpaces",         LogLevel::Info,  true,  LOG_TAGS(cds) },
 577   { "TraceBiasedLocking",        LogLevel::Info,  true,  LOG_TAGS(biasedlocking) },
 578   { "TraceClassLoading",         LogLevel::Info,  true,  LOG_TAGS(class, load) },
 579   { "TraceClassLoadingPreorder", LogLevel::Debug, true,  LOG_TAGS(class, preorder) },
 580   { "TraceClassPaths",           LogLevel::Info,  true,  LOG_TAGS(class, path) },
 581   { "TraceClassResolution",      LogLevel::Debug, true,  LOG_TAGS(class, resolve) },
 582   { "TraceClassUnloading",       LogLevel::Info,  true,  LOG_TAGS(class, unload) },
 583   { "TraceExceptions",           LogLevel::Info,  true,  LOG_TAGS(exceptions) },
 584   { "TraceLoaderConstraints",    LogLevel::Info,  true,  LOG_TAGS(class, loader, constraints) },
 585   { "TraceMonitorInflation",     LogLevel::Debug, true,  LOG_TAGS(monitorinflation) },
 586   { "TraceSafepointCleanupTime", LogLevel::Info,  true,  LOG_TAGS(safepoint, cleanup) },
 587   { "TraceJVMTIObjectTagging",   LogLevel::Debug, true,  LOG_TAGS(jvmti, objecttagging) },
 588   { "TraceRedefineClasses",      LogLevel::Info,  false, LOG_TAGS(redefine, class) },
 589   { NULL,                        LogLevel::Off,   false, LOG_TAGS(_NO_TAG) }
 590 };
 591 
 592 #ifndef PRODUCT
 593 // These options are removed in jdk9. Remove this code for jdk10.
 594 static AliasedFlag const removed_develop_logging_flags[] = {
 595   { "TraceClassInitialization",   "-Xlog:class+init" },
 596   { "TraceClassLoaderData",       "-Xlog:class+loader+data" },
 597   { "TraceDefaultMethods",        "-Xlog:defaultmethods=debug" },
 598   { "TraceItables",               "-Xlog:itables=debug" },
 599   { "TraceMonitorMismatch",       "-Xlog:monitormismatch=info" },
 600   { "TraceSafepoint",             "-Xlog:safepoint=debug" },
 601   { "TraceStartupTime",           "-Xlog:startuptime" },
 602   { "TraceVMOperation",           "-Xlog:vmoperation=debug" },
 603   { "PrintVtables",               "-Xlog:vtables=debug" },
 604   { "VerboseVerification",        "-Xlog:verification" },
 605   { NULL, NULL }
 606 };
 607 #endif //PRODUCT
 608 
 609 // Return true if "v" is less than "other", where "other" may be "undefined".
 610 static bool version_less_than(JDK_Version v, JDK_Version other) {
 611   assert(!v.is_undefined(), "must be defined");
 612   if (!other.is_undefined() && v.compare(other) >= 0) {
 613     return false;
 614   } else {
 615     return true;
 616   }
 617 }
 618 
 619 extern bool lookup_special_flag_ext(const char *flag_name, SpecialFlag& flag);
 620 
 621 static bool lookup_special_flag(const char *flag_name, SpecialFlag& flag) {
 622   // Allow extensions to have priority
 623   if (lookup_special_flag_ext(flag_name, flag)) {
 624     return true;
 625   }
 626 
 627   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 628     if ((strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 629       flag = special_jvm_flags[i];
 630       return true;
 631     }
 632   }
 633   return false;
 634 }
 635 
 636 bool Arguments::is_obsolete_flag(const char *flag_name, JDK_Version* version) {
 637   assert(version != NULL, "Must provide a version buffer");
 638   SpecialFlag flag;
 639   if (lookup_special_flag(flag_name, flag)) {
 640     if (!flag.obsolete_in.is_undefined()) {
 641       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 642         *version = flag.obsolete_in;
 643         return true;
 644       }
 645     }
 646   }
 647   return false;
 648 }
 649 
 650 int Arguments::is_deprecated_flag(const char *flag_name, JDK_Version* version) {
 651   assert(version != NULL, "Must provide a version buffer");
 652   SpecialFlag flag;
 653   if (lookup_special_flag(flag_name, flag)) {
 654     if (!flag.deprecated_in.is_undefined()) {
 655       if (version_less_than(JDK_Version::current(), flag.obsolete_in) &&
 656           version_less_than(JDK_Version::current(), flag.expired_in)) {
 657         *version = flag.deprecated_in;
 658         return 1;
 659       } else {
 660         return -1;
 661       }
 662     }
 663   }
 664   return 0;
 665 }
 666 
 667 #ifndef PRODUCT
 668 const char* Arguments::removed_develop_logging_flag_name(const char* name){
 669   for (size_t i = 0; removed_develop_logging_flags[i].alias_name != NULL; i++) {
 670     const AliasedFlag& flag = removed_develop_logging_flags[i];
 671     if (strcmp(flag.alias_name, name) == 0) {
 672       return flag.real_name;
 673     }
 674   }
 675   return NULL;
 676 }
 677 #endif // PRODUCT
 678 
 679 const char* Arguments::real_flag_name(const char *flag_name) {
 680   for (size_t i = 0; aliased_jvm_flags[i].alias_name != NULL; i++) {
 681     const AliasedFlag& flag_status = aliased_jvm_flags[i];
 682     if (strcmp(flag_status.alias_name, flag_name) == 0) {
 683         return flag_status.real_name;
 684     }
 685   }
 686   return flag_name;
 687 }
 688 
 689 #ifdef ASSERT
 690 static bool lookup_special_flag(const char *flag_name, size_t skip_index) {
 691   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 692     if ((i != skip_index) && (strcmp(special_jvm_flags[i].name, flag_name) == 0)) {
 693       return true;
 694     }
 695   }
 696   return false;
 697 }
 698 
 699 // Verifies the correctness of the entries in the special_jvm_flags table.
 700 // If there is a semantic error (i.e. a bug in the table) such as the obsoletion
 701 // version being earlier than the deprecation version, then a warning is issued
 702 // and verification fails - by returning false. If it is detected that the table
 703 // is out of date, with respect to the current version, then a warning is issued
 704 // but verification does not fail. This allows the VM to operate when the version
 705 // is first updated, without needing to update all the impacted flags at the
 706 // same time.
 707 static bool verify_special_jvm_flags() {
 708   bool success = true;
 709   for (size_t i = 0; special_jvm_flags[i].name != NULL; i++) {
 710     const SpecialFlag& flag = special_jvm_flags[i];
 711     if (lookup_special_flag(flag.name, i)) {
 712       warning("Duplicate special flag declaration \"%s\"", flag.name);
 713       success = false;
 714     }
 715     if (flag.deprecated_in.is_undefined() &&
 716         flag.obsolete_in.is_undefined()) {
 717       warning("Special flag entry \"%s\" must declare version deprecated and/or obsoleted in.", flag.name);
 718       success = false;
 719     }
 720 
 721     if (!flag.deprecated_in.is_undefined()) {
 722       if (!version_less_than(flag.deprecated_in, flag.obsolete_in)) {
 723         warning("Special flag entry \"%s\" must be deprecated before obsoleted.", flag.name);
 724         success = false;
 725       }
 726 
 727       if (!version_less_than(flag.deprecated_in, flag.expired_in)) {
 728         warning("Special flag entry \"%s\" must be deprecated before expired.", flag.name);
 729         success = false;
 730       }
 731     }
 732 
 733     if (!flag.obsolete_in.is_undefined()) {
 734       if (!version_less_than(flag.obsolete_in, flag.expired_in)) {
 735         warning("Special flag entry \"%s\" must be obsoleted before expired.", flag.name);
 736         success = false;
 737       }
 738 
 739       // if flag has become obsolete it should not have a "globals" flag defined anymore.
 740       if (!version_less_than(JDK_Version::current(), flag.obsolete_in)) {
 741         if (Flag::find_flag(flag.name) != NULL) {
 742           // Temporarily disable the warning: 8196739
 743           // warning("Global variable for obsolete special flag entry \"%s\" should be removed", flag.name);
 744         }
 745       }
 746     }
 747 
 748     if (!flag.expired_in.is_undefined()) {
 749       // if flag has become expired it should not have a "globals" flag defined anymore.
 750       if (!version_less_than(JDK_Version::current(), flag.expired_in)) {
 751         if (Flag::find_flag(flag.name) != NULL) {
 752           // Temporarily disable the warning: 8196739
 753           // warning("Global variable for expired flag entry \"%s\" should be removed", flag.name);
 754         }
 755       }
 756     }
 757 
 758   }
 759   return success;
 760 }
 761 #endif
 762 
 763 // Parses a size specification string.
 764 bool Arguments::atojulong(const char *s, julong* result) {
 765   julong n = 0;
 766 
 767   // First char must be a digit. Don't allow negative numbers or leading spaces.
 768   if (!isdigit(*s)) {
 769     return false;
 770   }
 771 
 772   bool is_hex = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
 773   char* remainder;
 774   errno = 0;
 775   n = strtoull(s, &remainder, (is_hex ? 16 : 10));
 776   if (errno != 0) {
 777     return false;
 778   }
 779 
 780   // Fail if no number was read at all or if the remainder contains more than a single non-digit character.
 781   if (remainder == s || strlen(remainder) > 1) {
 782     return false;
 783   }
 784 
 785   switch (*remainder) {
 786     case 'T': case 't':
 787       *result = n * G * K;
 788       // Check for overflow.
 789       if (*result/((julong)G * K) != n) return false;
 790       return true;
 791     case 'G': case 'g':
 792       *result = n * G;
 793       if (*result/G != n) return false;
 794       return true;
 795     case 'M': case 'm':
 796       *result = n * M;
 797       if (*result/M != n) return false;
 798       return true;
 799     case 'K': case 'k':
 800       *result = n * K;
 801       if (*result/K != n) return false;
 802       return true;
 803     case '\0':
 804       *result = n;
 805       return true;
 806     default:
 807       return false;
 808   }
 809 }
 810 
 811 Arguments::ArgsRange Arguments::check_memory_size(julong size, julong min_size, julong max_size) {
 812   if (size < min_size) return arg_too_small;
 813   if (size > max_size) return arg_too_big;
 814   return arg_in_range;
 815 }
 816 
 817 // Describe an argument out of range error
 818 void Arguments::describe_range_error(ArgsRange errcode) {
 819   switch(errcode) {
 820   case arg_too_big:
 821     jio_fprintf(defaultStream::error_stream(),
 822                 "The specified size exceeds the maximum "
 823                 "representable size.\n");
 824     break;
 825   case arg_too_small:
 826   case arg_unreadable:
 827   case arg_in_range:
 828     // do nothing for now
 829     break;
 830   default:
 831     ShouldNotReachHere();
 832   }
 833 }
 834 
 835 static bool set_bool_flag(const char* name, bool value, Flag::Flags origin) {
 836   if (CommandLineFlags::boolAtPut(name, &value, origin) == Flag::SUCCESS) {
 837     return true;
 838   } else {
 839     return false;
 840   }
 841 }
 842 
 843 static bool set_fp_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 844   char* end;
 845   errno = 0;
 846   double v = strtod(value, &end);
 847   if ((errno != 0) || (*end != 0)) {
 848     return false;
 849   }
 850 
 851   if (CommandLineFlags::doubleAtPut(name, &v, origin) == Flag::SUCCESS) {
 852     return true;
 853   }
 854   return false;
 855 }
 856 
 857 static bool set_numeric_flag(const char* name, char* value, Flag::Flags origin) {
 858   julong v;
 859   int int_v;
 860   intx intx_v;
 861   bool is_neg = false;
 862   Flag* result = Flag::find_flag(name, strlen(name));
 863 
 864   if (result == NULL) {
 865     return false;
 866   }
 867 
 868   // Check the sign first since atojulong() parses only unsigned values.
 869   if (*value == '-') {
 870     if (!result->is_intx() && !result->is_int()) {
 871       return false;
 872     }
 873     value++;
 874     is_neg = true;
 875   }
 876   if (!Arguments::atojulong(value, &v)) {
 877     return false;
 878   }
 879   if (result->is_int()) {
 880     int_v = (int) v;
 881     if (is_neg) {
 882       int_v = -int_v;
 883     }
 884     return CommandLineFlags::intAtPut(result, &int_v, origin) == Flag::SUCCESS;
 885   } else if (result->is_uint()) {
 886     uint uint_v = (uint) v;
 887     return CommandLineFlags::uintAtPut(result, &uint_v, origin) == Flag::SUCCESS;
 888   } else if (result->is_intx()) {
 889     intx_v = (intx) v;
 890     if (is_neg) {
 891       intx_v = -intx_v;
 892     }
 893     return CommandLineFlags::intxAtPut(result, &intx_v, origin) == Flag::SUCCESS;
 894   } else if (result->is_uintx()) {
 895     uintx uintx_v = (uintx) v;
 896     return CommandLineFlags::uintxAtPut(result, &uintx_v, origin) == Flag::SUCCESS;
 897   } else if (result->is_uint64_t()) {
 898     uint64_t uint64_t_v = (uint64_t) v;
 899     return CommandLineFlags::uint64_tAtPut(result, &uint64_t_v, origin) == Flag::SUCCESS;
 900   } else if (result->is_size_t()) {
 901     size_t size_t_v = (size_t) v;
 902     return CommandLineFlags::size_tAtPut(result, &size_t_v, origin) == Flag::SUCCESS;
 903   } else if (result->is_double()) {
 904     double double_v = (double) v;
 905     return CommandLineFlags::doubleAtPut(result, &double_v, origin) == Flag::SUCCESS;
 906   } else {
 907     return false;
 908   }
 909 }
 910 
 911 static bool set_string_flag(const char* name, const char* value, Flag::Flags origin) {
 912   if (CommandLineFlags::ccstrAtPut(name, &value, origin) != Flag::SUCCESS) return false;
 913   // Contract:  CommandLineFlags always returns a pointer that needs freeing.
 914   FREE_C_HEAP_ARRAY(char, value);
 915   return true;
 916 }
 917 
 918 static bool append_to_string_flag(const char* name, const char* new_value, Flag::Flags origin) {
 919   const char* old_value = "";
 920   if (CommandLineFlags::ccstrAt(name, &old_value) != Flag::SUCCESS) return false;
 921   size_t old_len = old_value != NULL ? strlen(old_value) : 0;
 922   size_t new_len = strlen(new_value);
 923   const char* value;
 924   char* free_this_too = NULL;
 925   if (old_len == 0) {
 926     value = new_value;
 927   } else if (new_len == 0) {
 928     value = old_value;
 929   } else {
 930      size_t length = old_len + 1 + new_len + 1;
 931      char* buf = NEW_C_HEAP_ARRAY(char, length, mtArguments);
 932     // each new setting adds another LINE to the switch:
 933     jio_snprintf(buf, length, "%s\n%s", old_value, new_value);
 934     value = buf;
 935     free_this_too = buf;
 936   }
 937   (void) CommandLineFlags::ccstrAtPut(name, &value, origin);
 938   // CommandLineFlags always returns a pointer that needs freeing.
 939   FREE_C_HEAP_ARRAY(char, value);
 940   if (free_this_too != NULL) {
 941     // CommandLineFlags made its own copy, so I must delete my own temp. buffer.
 942     FREE_C_HEAP_ARRAY(char, free_this_too);
 943   }
 944   return true;
 945 }
 946 
 947 const char* Arguments::handle_aliases_and_deprecation(const char* arg, bool warn) {
 948   const char* real_name = real_flag_name(arg);
 949   JDK_Version since = JDK_Version();
 950   switch (is_deprecated_flag(arg, &since)) {
 951     case -1:
 952       return NULL; // obsolete or expired, don't process normally
 953     case 0:
 954       return real_name;
 955     case 1: {
 956       if (warn) {
 957         char version[256];
 958         since.to_string(version, sizeof(version));
 959         if (real_name != arg) {
 960           warning("Option %s was deprecated in version %s and will likely be removed in a future release. Use option %s instead.",
 961                   arg, version, real_name);
 962         } else {
 963           warning("Option %s was deprecated in version %s and will likely be removed in a future release.",
 964                   arg, version);
 965         }
 966       }
 967       return real_name;
 968     }
 969   }
 970   ShouldNotReachHere();
 971   return NULL;
 972 }
 973 
 974 void log_deprecated_flag(const char* name, bool on, AliasedLoggingFlag alf) {
 975   LogTagType tagSet[] = {alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5};
 976   // Set tagset string buffer at max size of 256, large enough for any alias tagset
 977   const int max_tagset_size = 256;
 978   int max_tagset_len = max_tagset_size - 1;
 979   char tagset_buffer[max_tagset_size];
 980   tagset_buffer[0] = '\0';
 981 
 982   // Write tag-set for aliased logging option, in string list form
 983   int max_tags = sizeof(tagSet)/sizeof(tagSet[0]);
 984   for (int i = 0; i < max_tags && tagSet[i] != LogTag::__NO_TAG; i++) {
 985     if (i > 0) {
 986       strncat(tagset_buffer, "+", max_tagset_len - strlen(tagset_buffer));
 987     }
 988     strncat(tagset_buffer, LogTag::name(tagSet[i]), max_tagset_len - strlen(tagset_buffer));
 989   }
 990   if (!alf.exactMatch) {
 991       strncat(tagset_buffer, "*", max_tagset_len - strlen(tagset_buffer));
 992   }
 993   log_warning(arguments)("-XX:%s%s is deprecated. Will use -Xlog:%s=%s instead.",
 994                          (on) ? "+" : "-",
 995                          name,
 996                          tagset_buffer,
 997                          (on) ? LogLevel::name(alf.level) : "off");
 998 }
 999 
1000 AliasedLoggingFlag Arguments::catch_logging_aliases(const char* name, bool on){
1001   for (size_t i = 0; aliased_logging_flags[i].alias_name != NULL; i++) {
1002     const AliasedLoggingFlag& alf = aliased_logging_flags[i];
1003     if (strcmp(alf.alias_name, name) == 0) {
1004       log_deprecated_flag(name, on, alf);
1005       return alf;
1006     }
1007   }
1008   AliasedLoggingFlag a = {NULL, LogLevel::Off, false, LOG_TAGS(_NO_TAG)};
1009   return a;
1010 }
1011 
1012 bool Arguments::parse_argument(const char* arg, Flag::Flags origin) {
1013 
1014   // range of acceptable characters spelled out for portability reasons
1015 #define NAME_RANGE  "[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]"
1016 #define BUFLEN 255
1017   char name[BUFLEN+1];
1018   char dummy;
1019   const char* real_name;
1020   bool warn_if_deprecated = true;
1021 
1022   if (sscanf(arg, "-%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1023     AliasedLoggingFlag alf = catch_logging_aliases(name, false);
1024     if (alf.alias_name != NULL){
1025       LogConfiguration::configure_stdout(LogLevel::Off, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1026       return true;
1027     }
1028     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1029     if (real_name == NULL) {
1030       return false;
1031     }
1032     return set_bool_flag(real_name, false, origin);
1033   }
1034   if (sscanf(arg, "+%" XSTR(BUFLEN) NAME_RANGE "%c", name, &dummy) == 1) {
1035     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1036     if (alf.alias_name != NULL){
1037       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1038       return true;
1039     }
1040     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1041     if (real_name == NULL) {
1042       return false;
1043     }
1044     return set_bool_flag(real_name, true, origin);
1045   }
1046 
1047   char punct;
1048   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "%c", name, &punct) == 2 && punct == '=') {
1049     const char* value = strchr(arg, '=') + 1;
1050     Flag* flag;
1051 
1052     // this scanf pattern matches both strings (handled here) and numbers (handled later))
1053     AliasedLoggingFlag alf = catch_logging_aliases(name, true);
1054     if (alf.alias_name != NULL) {
1055       LogConfiguration::configure_stdout(alf.level, alf.exactMatch, alf.tag0, alf.tag1, alf.tag2, alf.tag3, alf.tag4, alf.tag5);
1056       return true;
1057     }
1058     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1059     if (real_name == NULL) {
1060       return false;
1061     }
1062     flag = Flag::find_flag(real_name);
1063     if (flag != NULL && flag->is_ccstr()) {
1064       if (flag->ccstr_accumulates()) {
1065         return append_to_string_flag(real_name, value, origin);
1066       } else {
1067         if (value[0] == '\0') {
1068           value = NULL;
1069         }
1070         return set_string_flag(real_name, value, origin);
1071       }
1072     } else {
1073       warn_if_deprecated = false; // if arg is deprecated, we've already done warning...
1074     }
1075   }
1076 
1077   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE ":%c", name, &punct) == 2 && punct == '=') {
1078     const char* value = strchr(arg, '=') + 1;
1079     // -XX:Foo:=xxx will reset the string flag to the given value.
1080     if (value[0] == '\0') {
1081       value = NULL;
1082     }
1083     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1084     if (real_name == NULL) {
1085       return false;
1086     }
1087     return set_string_flag(real_name, value, origin);
1088   }
1089 
1090 #define SIGNED_FP_NUMBER_RANGE "[-0123456789.eE+]"
1091 #define SIGNED_NUMBER_RANGE    "[-0123456789]"
1092 #define        NUMBER_RANGE    "[0123456789eE+-]"
1093   char value[BUFLEN + 1];
1094   char value2[BUFLEN + 1];
1095   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_NUMBER_RANGE "." "%" XSTR(BUFLEN) NUMBER_RANGE "%c", name, value, value2, &dummy) == 3) {
1096     // Looks like a floating-point number -- try again with more lenient format string
1097     if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) SIGNED_FP_NUMBER_RANGE "%c", name, value, &dummy) == 2) {
1098       real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1099       if (real_name == NULL) {
1100         return false;
1101       }
1102       return set_fp_numeric_flag(real_name, value, origin);
1103     }
1104   }
1105 
1106 #define VALUE_RANGE "[-kmgtxKMGTX0123456789abcdefABCDEF]"
1107   if (sscanf(arg, "%" XSTR(BUFLEN) NAME_RANGE "=" "%" XSTR(BUFLEN) VALUE_RANGE "%c", name, value, &dummy) == 2) {
1108     real_name = handle_aliases_and_deprecation(name, warn_if_deprecated);
1109     if (real_name == NULL) {
1110       return false;
1111     }
1112     return set_numeric_flag(real_name, value, origin);
1113   }
1114 
1115   return false;
1116 }
1117 
1118 void Arguments::add_string(char*** bldarray, int* count, const char* arg) {
1119   assert(bldarray != NULL, "illegal argument");
1120 
1121   if (arg == NULL) {
1122     return;
1123   }
1124 
1125   int new_count = *count + 1;
1126 
1127   // expand the array and add arg to the last element
1128   if (*bldarray == NULL) {
1129     *bldarray = NEW_C_HEAP_ARRAY(char*, new_count, mtArguments);
1130   } else {
1131     *bldarray = REALLOC_C_HEAP_ARRAY(char*, *bldarray, new_count, mtArguments);
1132   }
1133   (*bldarray)[*count] = os::strdup_check_oom(arg);
1134   *count = new_count;
1135 }
1136 
1137 void Arguments::build_jvm_args(const char* arg) {
1138   add_string(&_jvm_args_array, &_num_jvm_args, arg);
1139 }
1140 
1141 void Arguments::build_jvm_flags(const char* arg) {
1142   add_string(&_jvm_flags_array, &_num_jvm_flags, arg);
1143 }
1144 
1145 // utility function to return a string that concatenates all
1146 // strings in a given char** array
1147 const char* Arguments::build_resource_string(char** args, int count) {
1148   if (args == NULL || count == 0) {
1149     return NULL;
1150   }
1151   size_t length = 0;
1152   for (int i = 0; i < count; i++) {
1153     length += strlen(args[i]) + 1; // add 1 for a space or NULL terminating character
1154   }
1155   char* s = NEW_RESOURCE_ARRAY(char, length);
1156   char* dst = s;
1157   for (int j = 0; j < count; j++) {
1158     size_t offset = strlen(args[j]) + 1; // add 1 for a space or NULL terminating character
1159     jio_snprintf(dst, length, "%s ", args[j]); // jio_snprintf will replace the last space character with NULL character
1160     dst += offset;
1161     length -= offset;
1162   }
1163   return (const char*) s;
1164 }
1165 
1166 void Arguments::print_on(outputStream* st) {
1167   st->print_cr("VM Arguments:");
1168   if (num_jvm_flags() > 0) {
1169     st->print("jvm_flags: "); print_jvm_flags_on(st);
1170     st->cr();
1171   }
1172   if (num_jvm_args() > 0) {
1173     st->print("jvm_args: "); print_jvm_args_on(st);
1174     st->cr();
1175   }
1176   st->print_cr("java_command: %s", java_command() ? java_command() : "<unknown>");
1177   if (_java_class_path != NULL) {
1178     char* path = _java_class_path->value();
1179     st->print_cr("java_class_path (initial): %s", strlen(path) == 0 ? "<not set>" : path );
1180   }
1181   st->print_cr("Launcher Type: %s", _sun_java_launcher);
1182 }
1183 
1184 void Arguments::print_summary_on(outputStream* st) {
1185   // Print the command line.  Environment variables that are helpful for
1186   // reproducing the problem are written later in the hs_err file.
1187   // flags are from setting file
1188   if (num_jvm_flags() > 0) {
1189     st->print_raw("Settings File: ");
1190     print_jvm_flags_on(st);
1191     st->cr();
1192   }
1193   // args are the command line and environment variable arguments.
1194   st->print_raw("Command Line: ");
1195   if (num_jvm_args() > 0) {
1196     print_jvm_args_on(st);
1197   }
1198   // this is the classfile and any arguments to the java program
1199   if (java_command() != NULL) {
1200     st->print("%s", java_command());
1201   }
1202   st->cr();
1203 }
1204 
1205 void Arguments::print_jvm_flags_on(outputStream* st) {
1206   if (_num_jvm_flags > 0) {
1207     for (int i=0; i < _num_jvm_flags; i++) {
1208       st->print("%s ", _jvm_flags_array[i]);
1209     }
1210   }
1211 }
1212 
1213 void Arguments::print_jvm_args_on(outputStream* st) {
1214   if (_num_jvm_args > 0) {
1215     for (int i=0; i < _num_jvm_args; i++) {
1216       st->print("%s ", _jvm_args_array[i]);
1217     }
1218   }
1219 }
1220 
1221 bool Arguments::process_argument(const char* arg,
1222                                  jboolean ignore_unrecognized,
1223                                  Flag::Flags origin) {
1224   JDK_Version since = JDK_Version();
1225 
1226   if (parse_argument(arg, origin)) {
1227     return true;
1228   }
1229 
1230   // Determine if the flag has '+', '-', or '=' characters.
1231   bool has_plus_minus = (*arg == '+' || *arg == '-');
1232   const char* const argname = has_plus_minus ? arg + 1 : arg;
1233 
1234   size_t arg_len;
1235   const char* equal_sign = strchr(argname, '=');
1236   if (equal_sign == NULL) {
1237     arg_len = strlen(argname);
1238   } else {
1239     arg_len = equal_sign - argname;
1240   }
1241 
1242   // Only make the obsolete check for valid arguments.
1243   if (arg_len <= BUFLEN) {
1244     // Construct a string which consists only of the argument name without '+', '-', or '='.
1245     char stripped_argname[BUFLEN+1]; // +1 for '\0'
1246     jio_snprintf(stripped_argname, arg_len+1, "%s", argname); // +1 for '\0'
1247     if (is_obsolete_flag(stripped_argname, &since)) {
1248       char version[256];
1249       since.to_string(version, sizeof(version));
1250       warning("Ignoring option %s; support was removed in %s", stripped_argname, version);
1251       return true;
1252     }
1253 #ifndef PRODUCT
1254     else {
1255       const char* replacement;
1256       if ((replacement = removed_develop_logging_flag_name(stripped_argname)) != NULL){
1257         log_warning(arguments)("%s has been removed. Please use %s instead.",
1258                                stripped_argname,
1259                                replacement);
1260         return false;
1261       }
1262     }
1263 #endif //PRODUCT
1264   }
1265 
1266   // For locked flags, report a custom error message if available.
1267   // Otherwise, report the standard unrecognized VM option.
1268   Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true, true);
1269   if (found_flag != NULL) {
1270     char locked_message_buf[BUFLEN];
1271     Flag::MsgType msg_type = found_flag->get_locked_message(locked_message_buf, BUFLEN);
1272     if (strlen(locked_message_buf) == 0) {
1273       if (found_flag->is_bool() && !has_plus_minus) {
1274         jio_fprintf(defaultStream::error_stream(),
1275           "Missing +/- setting for VM option '%s'\n", argname);
1276       } else if (!found_flag->is_bool() && has_plus_minus) {
1277         jio_fprintf(defaultStream::error_stream(),
1278           "Unexpected +/- setting in VM option '%s'\n", argname);
1279       } else {
1280         jio_fprintf(defaultStream::error_stream(),
1281           "Improperly specified VM option '%s'\n", argname);
1282       }
1283     } else {
1284 #ifdef PRODUCT
1285       bool mismatched = ((msg_type == Flag::NOTPRODUCT_FLAG_BUT_PRODUCT_BUILD) ||
1286                          (msg_type == Flag::DEVELOPER_FLAG_BUT_PRODUCT_BUILD));
1287       if (ignore_unrecognized && mismatched) {
1288         return true;
1289       }
1290 #endif
1291       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
1292     }
1293   } else {
1294     if (ignore_unrecognized) {
1295       return true;
1296     }
1297     jio_fprintf(defaultStream::error_stream(),
1298                 "Unrecognized VM option '%s'\n", argname);
1299     Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true);
1300     if (fuzzy_matched != NULL) {
1301       jio_fprintf(defaultStream::error_stream(),
1302                   "Did you mean '%s%s%s'? ",
1303                   (fuzzy_matched->is_bool()) ? "(+/-)" : "",
1304                   fuzzy_matched->_name,
1305                   (fuzzy_matched->is_bool()) ? "" : "=<value>");
1306     }
1307   }
1308 
1309   // allow for commandline "commenting out" options like -XX:#+Verbose
1310   return arg[0] == '#';
1311 }
1312 
1313 bool Arguments::process_settings_file(const char* file_name, bool should_exist, jboolean ignore_unrecognized) {
1314   FILE* stream = fopen(file_name, "rb");
1315   if (stream == NULL) {
1316     if (should_exist) {
1317       jio_fprintf(defaultStream::error_stream(),
1318                   "Could not open settings file %s\n", file_name);
1319       return false;
1320     } else {
1321       return true;
1322     }
1323   }
1324 
1325   char token[1024];
1326   int  pos = 0;
1327 
1328   bool in_white_space = true;
1329   bool in_comment     = false;
1330   bool in_quote       = false;
1331   char quote_c        = 0;
1332   bool result         = true;
1333 
1334   int c = getc(stream);
1335   while(c != EOF && pos < (int)(sizeof(token)-1)) {
1336     if (in_white_space) {
1337       if (in_comment) {
1338         if (c == '\n') in_comment = false;
1339       } else {
1340         if (c == '#') in_comment = true;
1341         else if (!isspace(c)) {
1342           in_white_space = false;
1343           token[pos++] = c;
1344         }
1345       }
1346     } else {
1347       if (c == '\n' || (!in_quote && isspace(c))) {
1348         // token ends at newline, or at unquoted whitespace
1349         // this allows a way to include spaces in string-valued options
1350         token[pos] = '\0';
1351         logOption(token);
1352         result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1353         build_jvm_flags(token);
1354         pos = 0;
1355         in_white_space = true;
1356         in_quote = false;
1357       } else if (!in_quote && (c == '\'' || c == '"')) {
1358         in_quote = true;
1359         quote_c = c;
1360       } else if (in_quote && (c == quote_c)) {
1361         in_quote = false;
1362       } else {
1363         token[pos++] = c;
1364       }
1365     }
1366     c = getc(stream);
1367   }
1368   if (pos > 0) {
1369     token[pos] = '\0';
1370     result &= process_argument(token, ignore_unrecognized, Flag::CONFIG_FILE);
1371     build_jvm_flags(token);
1372   }
1373   fclose(stream);
1374   return result;
1375 }
1376 
1377 //=============================================================================================================
1378 // Parsing of properties (-D)
1379 
1380 const char* Arguments::get_property(const char* key) {
1381   return PropertyList_get_value(system_properties(), key);
1382 }
1383 
1384 bool Arguments::add_property(const char* prop, PropertyWriteable writeable, PropertyInternal internal) {
1385   const char* eq = strchr(prop, '=');
1386   const char* key;
1387   const char* value = "";
1388 
1389   if (eq == NULL) {
1390     // property doesn't have a value, thus use passed string
1391     key = prop;
1392   } else {
1393     // property have a value, thus extract it and save to the
1394     // allocated string
1395     size_t key_len = eq - prop;
1396     char* tmp_key = AllocateHeap(key_len + 1, mtArguments);
1397 
1398     jio_snprintf(tmp_key, key_len + 1, "%s", prop);
1399     key = tmp_key;
1400 
1401     value = &prop[key_len + 1];
1402   }
1403 
1404   if (strcmp(key, "java.compiler") == 0) {
1405     process_java_compiler_argument(value);
1406     // Record value in Arguments, but let it get passed to Java.
1407   } else if (strcmp(key, "sun.java.launcher.is_altjvm") == 0 ||
1408              strcmp(key, "sun.java.launcher.pid") == 0) {
1409     // sun.java.launcher.is_altjvm and sun.java.launcher.pid property are
1410     // private and are processed in process_sun_java_launcher_properties();
1411     // the sun.java.launcher property is passed on to the java application
1412   } else if (strcmp(key, "sun.boot.library.path") == 0) {
1413     // append is true, writable is true, internal is false
1414     PropertyList_unique_add(&_system_properties, key, value, AppendProperty,
1415                             WriteableProperty, ExternalProperty);
1416   } else {
1417     if (strcmp(key, "sun.java.command") == 0) {
1418       char *old_java_command = _java_command;
1419       _java_command = os::strdup_check_oom(value, mtArguments);
1420       if (old_java_command != NULL) {
1421         os::free(old_java_command);
1422       }
1423     } else if (strcmp(key, "java.vendor.url.bug") == 0) {
1424       const char* old_java_vendor_url_bug = _java_vendor_url_bug;
1425       // save it in _java_vendor_url_bug, so JVM fatal error handler can access
1426       // its value without going through the property list or making a Java call.
1427       _java_vendor_url_bug = os::strdup_check_oom(value, mtArguments);
1428       if (old_java_vendor_url_bug != DEFAULT_VENDOR_URL_BUG) {
1429         assert(old_java_vendor_url_bug != NULL, "_java_vendor_url_bug is NULL");
1430         os::free((void *)old_java_vendor_url_bug);
1431       }
1432     }
1433 
1434     // Create new property and add at the end of the list
1435     PropertyList_unique_add(&_system_properties, key, value, AddProperty, writeable, internal);
1436   }
1437 
1438   if (key != prop) {
1439     // SystemProperty copy passed value, thus free previously allocated
1440     // memory
1441     FreeHeap((void *)key);
1442   }
1443 
1444   return true;
1445 }
1446 
1447 #if INCLUDE_CDS
1448 void Arguments::check_unsupported_dumping_properties() {
1449   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
1450   const char* unsupported_properties[] = { "jdk.module.main",
1451                                            "jdk.module.limitmods",
1452                                            "jdk.module.path",
1453                                            "jdk.module.upgrade.path",
1454                                            "jdk.module.patch.0" };
1455   const char* unsupported_options[] = { "-m", // cannot use at dump time
1456                                         "--limit-modules", // ignored at dump time
1457                                         "--module-path", // ignored at dump time
1458                                         "--upgrade-module-path", // ignored at dump time
1459                                         "--patch-module" // ignored at dump time
1460                                       };
1461   assert(ARRAY_SIZE(unsupported_properties) == ARRAY_SIZE(unsupported_options), "must be");
1462   // If a vm option is found in the unsupported_options array with index less than the info_idx,
1463   // vm will exit with an error message. Otherwise, it will print an informational message if
1464   // -Xlog:cds is enabled.
1465   uint info_idx = 1;
1466   SystemProperty* sp = system_properties();
1467   while (sp != NULL) {
1468     for (uint i = 0; i < ARRAY_SIZE(unsupported_properties); i++) {
1469       if (strcmp(sp->key(), unsupported_properties[i]) == 0) {
1470         if (i < info_idx) {
1471           vm_exit_during_initialization(
1472             "Cannot use the following option when dumping the shared archive", unsupported_options[i]);
1473         } else {
1474           log_info(cds)("Info: the %s option is ignored when dumping the shared archive",
1475                         unsupported_options[i]);
1476         }
1477       }
1478     }
1479     sp = sp->next();
1480   }
1481 
1482   // Check for an exploded module build in use with -Xshare:dump.
1483   if (!has_jimage()) {
1484     vm_exit_during_initialization("Dumping the shared archive is not supported with an exploded module build");
1485   }
1486 }
1487 #endif
1488 
1489 //===========================================================================================================
1490 // Setting int/mixed/comp mode flags
1491 
1492 void Arguments::set_mode_flags(Mode mode) {
1493   // Set up default values for all flags.
1494   // If you add a flag to any of the branches below,
1495   // add a default value for it here.
1496   set_java_compiler(false);
1497   _mode                      = mode;
1498 
1499   // Ensure Agent_OnLoad has the correct initial values.
1500   // This may not be the final mode; mode may change later in onload phase.
1501   PropertyList_unique_add(&_system_properties, "java.vm.info",
1502                           VM_Version::vm_info_string(), AddProperty, UnwriteableProperty, ExternalProperty);
1503 
1504   UseInterpreter             = true;
1505   UseCompiler                = true;
1506   UseLoopCounter             = true;
1507 
1508   // Default values may be platform/compiler dependent -
1509   // use the saved values
1510   ClipInlining               = Arguments::_ClipInlining;
1511   AlwaysCompileLoopMethods   = Arguments::_AlwaysCompileLoopMethods;
1512   UseOnStackReplacement      = Arguments::_UseOnStackReplacement;
1513   BackgroundCompilation      = Arguments::_BackgroundCompilation;
1514   if (TieredCompilation) {
1515     if (FLAG_IS_DEFAULT(Tier3InvokeNotifyFreqLog)) {
1516       Tier3InvokeNotifyFreqLog = Arguments::_Tier3InvokeNotifyFreqLog;
1517     }
1518     if (FLAG_IS_DEFAULT(Tier4InvocationThreshold)) {
1519       Tier4InvocationThreshold = Arguments::_Tier4InvocationThreshold;
1520     }
1521   }
1522 
1523   // Change from defaults based on mode
1524   switch (mode) {
1525   default:
1526     ShouldNotReachHere();
1527     break;
1528   case _int:
1529     UseCompiler              = false;
1530     UseLoopCounter           = false;
1531     AlwaysCompileLoopMethods = false;
1532     UseOnStackReplacement    = false;
1533     break;
1534   case _mixed:
1535     // same as default
1536     break;
1537   case _comp:
1538     UseInterpreter           = false;
1539     BackgroundCompilation    = false;
1540     ClipInlining             = false;
1541     // Be much more aggressive in tiered mode with -Xcomp and exercise C2 more.
1542     // We will first compile a level 3 version (C1 with full profiling), then do one invocation of it and
1543     // compile a level 4 (C2) and then continue executing it.
1544     if (TieredCompilation) {
1545       Tier3InvokeNotifyFreqLog = 0;
1546       Tier4InvocationThreshold = 0;
1547     }
1548     break;
1549   }
1550 }
1551 
1552 // Conflict: required to use shared spaces (-Xshare:on), but
1553 // incompatible command line options were chosen.
1554 static void no_shared_spaces(const char* message) {
1555   if (RequireSharedSpaces) {
1556     jio_fprintf(defaultStream::error_stream(),
1557       "Class data sharing is inconsistent with other specified options.\n");
1558     vm_exit_during_initialization("Unable to use shared archive.", message);
1559   } else {
1560     FLAG_SET_DEFAULT(UseSharedSpaces, false);
1561   }
1562 }
1563 
1564 // Returns threshold scaled with the value of scale.
1565 // If scale < 0.0, threshold is returned without scaling.
1566 intx Arguments::scaled_compile_threshold(intx threshold, double scale) {
1567   if (scale == 1.0 || scale < 0.0) {
1568     return threshold;
1569   } else {
1570     return (intx)(threshold * scale);
1571   }
1572 }
1573 
1574 // Returns freq_log scaled with the value of scale.
1575 // Returned values are in the range of [0, InvocationCounter::number_of_count_bits + 1].
1576 // If scale < 0.0, freq_log is returned without scaling.
1577 intx Arguments::scaled_freq_log(intx freq_log, double scale) {
1578   // Check if scaling is necessary or if negative value was specified.
1579   if (scale == 1.0 || scale < 0.0) {
1580     return freq_log;
1581   }
1582   // Check values to avoid calculating log2 of 0.
1583   if (scale == 0.0 || freq_log == 0) {
1584     return 0;
1585   }
1586   // Determine the maximum notification frequency value currently supported.
1587   // The largest mask value that the interpreter/C1 can handle is
1588   // of length InvocationCounter::number_of_count_bits. Mask values are always
1589   // one bit shorter then the value of the notification frequency. Set
1590   // max_freq_bits accordingly.
1591   intx max_freq_bits = InvocationCounter::number_of_count_bits + 1;
1592   intx scaled_freq = scaled_compile_threshold((intx)1 << freq_log, scale);
1593   if (scaled_freq == 0) {
1594     // Return 0 right away to avoid calculating log2 of 0.
1595     return 0;
1596   } else if (scaled_freq > nth_bit(max_freq_bits)) {
1597     return max_freq_bits;
1598   } else {
1599     return log2_intptr(scaled_freq);
1600   }
1601 }
1602 
1603 void Arguments::set_tiered_flags() {
1604   // With tiered, set default policy to AdvancedThresholdPolicy, which is 3.
1605   if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) {
1606     FLAG_SET_DEFAULT(CompilationPolicyChoice, 3);
1607   }
1608   if (CompilationPolicyChoice < 2) {
1609     vm_exit_during_initialization(
1610       "Incompatible compilation policy selected", NULL);
1611   }
1612   // Increase the code cache size - tiered compiles a lot more.
1613   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1614     FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
1615                   MIN2(CODE_CACHE_DEFAULT_LIMIT, ReservedCodeCacheSize * 5));
1616   }
1617   // Enable SegmentedCodeCache if TieredCompilation is enabled and ReservedCodeCacheSize >= 240M
1618   if (FLAG_IS_DEFAULT(SegmentedCodeCache) && ReservedCodeCacheSize >= 240*M) {
1619     FLAG_SET_ERGO(bool, SegmentedCodeCache, true);
1620   }
1621   if (!UseInterpreter) { // -Xcomp
1622     Tier3InvokeNotifyFreqLog = 0;
1623     Tier4InvocationThreshold = 0;
1624   }
1625 
1626   if (CompileThresholdScaling < 0) {
1627     vm_exit_during_initialization("Negative value specified for CompileThresholdScaling", NULL);
1628   }
1629 
1630   // Scale tiered compilation thresholds.
1631   // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves compilation thresholds unchanged.
1632   if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
1633     FLAG_SET_ERGO(intx, Tier0InvokeNotifyFreqLog, scaled_freq_log(Tier0InvokeNotifyFreqLog));
1634     FLAG_SET_ERGO(intx, Tier0BackedgeNotifyFreqLog, scaled_freq_log(Tier0BackedgeNotifyFreqLog));
1635 
1636     FLAG_SET_ERGO(intx, Tier3InvocationThreshold, scaled_compile_threshold(Tier3InvocationThreshold));
1637     FLAG_SET_ERGO(intx, Tier3MinInvocationThreshold, scaled_compile_threshold(Tier3MinInvocationThreshold));
1638     FLAG_SET_ERGO(intx, Tier3CompileThreshold, scaled_compile_threshold(Tier3CompileThreshold));
1639     FLAG_SET_ERGO(intx, Tier3BackEdgeThreshold, scaled_compile_threshold(Tier3BackEdgeThreshold));
1640 
1641     // Tier2{Invocation,MinInvocation,Compile,Backedge}Threshold should be scaled here
1642     // once these thresholds become supported.
1643 
1644     FLAG_SET_ERGO(intx, Tier2InvokeNotifyFreqLog, scaled_freq_log(Tier2InvokeNotifyFreqLog));
1645     FLAG_SET_ERGO(intx, Tier2BackedgeNotifyFreqLog, scaled_freq_log(Tier2BackedgeNotifyFreqLog));
1646 
1647     FLAG_SET_ERGO(intx, Tier3InvokeNotifyFreqLog, scaled_freq_log(Tier3InvokeNotifyFreqLog));
1648     FLAG_SET_ERGO(intx, Tier3BackedgeNotifyFreqLog, scaled_freq_log(Tier3BackedgeNotifyFreqLog));
1649 
1650     FLAG_SET_ERGO(intx, Tier23InlineeNotifyFreqLog, scaled_freq_log(Tier23InlineeNotifyFreqLog));
1651 
1652     FLAG_SET_ERGO(intx, Tier4InvocationThreshold, scaled_compile_threshold(Tier4InvocationThreshold));
1653     FLAG_SET_ERGO(intx, Tier4MinInvocationThreshold, scaled_compile_threshold(Tier4MinInvocationThreshold));
1654     FLAG_SET_ERGO(intx, Tier4CompileThreshold, scaled_compile_threshold(Tier4CompileThreshold));
1655     FLAG_SET_ERGO(intx, Tier4BackEdgeThreshold, scaled_compile_threshold(Tier4BackEdgeThreshold));
1656   }
1657 }
1658 
1659 void set_object_alignment() {
1660   // Object alignment.
1661   assert(is_power_of_2(ObjectAlignmentInBytes), "ObjectAlignmentInBytes must be power of 2");
1662   MinObjAlignmentInBytes     = ObjectAlignmentInBytes;
1663   assert(MinObjAlignmentInBytes >= HeapWordsPerLong * HeapWordSize, "ObjectAlignmentInBytes value is too small");
1664   MinObjAlignment            = MinObjAlignmentInBytes / HeapWordSize;
1665   assert(MinObjAlignmentInBytes == MinObjAlignment * HeapWordSize, "ObjectAlignmentInBytes value is incorrect");
1666   MinObjAlignmentInBytesMask = MinObjAlignmentInBytes - 1;
1667 
1668   LogMinObjAlignmentInBytes  = exact_log2(ObjectAlignmentInBytes);
1669   LogMinObjAlignment         = LogMinObjAlignmentInBytes - LogHeapWordSize;
1670 
1671   // Oop encoding heap max
1672   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
1673 
1674   if (SurvivorAlignmentInBytes == 0) {
1675     SurvivorAlignmentInBytes = ObjectAlignmentInBytes;
1676   }
1677 }
1678 
1679 size_t Arguments::max_heap_for_compressed_oops() {
1680   // Avoid sign flip.
1681   assert(OopEncodingHeapMax > (uint64_t)os::vm_page_size(), "Unusual page size");
1682   // We need to fit both the NULL page and the heap into the memory budget, while
1683   // keeping alignment constraints of the heap. To guarantee the latter, as the
1684   // NULL page is located before the heap, we pad the NULL page to the conservative
1685   // maximum alignment that the GC may ever impose upon the heap.
1686   size_t displacement_due_to_null_page = align_up((size_t)os::vm_page_size(),
1687                                                   _conservative_max_heap_alignment);
1688 
1689   LP64_ONLY(return OopEncodingHeapMax - displacement_due_to_null_page);
1690   NOT_LP64(ShouldNotReachHere(); return 0);
1691 }
1692 
1693 void Arguments::set_use_compressed_oops() {
1694 #ifndef ZERO
1695 #ifdef _LP64
1696   // MaxHeapSize is not set up properly at this point, but
1697   // the only value that can override MaxHeapSize if we are
1698   // to use UseCompressedOops is InitialHeapSize.
1699   size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
1700 
1701   if (max_heap_size <= max_heap_for_compressed_oops()) {
1702 #if !defined(COMPILER1) || defined(TIERED)
1703     if (FLAG_IS_DEFAULT(UseCompressedOops)) {
1704       FLAG_SET_ERGO(bool, UseCompressedOops, true);
1705     }
1706 #endif
1707   } else {
1708     if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
1709       warning("Max heap size too large for Compressed Oops");
1710       FLAG_SET_DEFAULT(UseCompressedOops, false);
1711       FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1712     }
1713   }
1714 #endif // _LP64
1715 #endif // ZERO
1716 }
1717 
1718 
1719 // NOTE: set_use_compressed_klass_ptrs() must be called after calling
1720 // set_use_compressed_oops().
1721 void Arguments::set_use_compressed_klass_ptrs() {
1722 #ifndef ZERO
1723 #ifdef _LP64
1724   // UseCompressedOops must be on for UseCompressedClassPointers to be on.
1725   if (!UseCompressedOops) {
1726     if (UseCompressedClassPointers) {
1727       warning("UseCompressedClassPointers requires UseCompressedOops");
1728     }
1729     FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1730   } else {
1731     // Turn on UseCompressedClassPointers too
1732     if (FLAG_IS_DEFAULT(UseCompressedClassPointers)) {
1733       FLAG_SET_ERGO(bool, UseCompressedClassPointers, true);
1734     }
1735     // Check the CompressedClassSpaceSize to make sure we use compressed klass ptrs.
1736     if (UseCompressedClassPointers) {
1737       if (CompressedClassSpaceSize > KlassEncodingMetaspaceMax) {
1738         warning("CompressedClassSpaceSize is too large for UseCompressedClassPointers");
1739         FLAG_SET_DEFAULT(UseCompressedClassPointers, false);
1740       }
1741     }
1742   }
1743 #endif // _LP64
1744 #endif // !ZERO
1745 }
1746 
1747 void Arguments::set_conservative_max_heap_alignment() {
1748   // The conservative maximum required alignment for the heap is the maximum of
1749   // the alignments imposed by several sources: any requirements from the heap
1750   // itself, the collector policy and the maximum page size we may run the VM
1751   // with.
1752   size_t heap_alignment = GCArguments::arguments()->conservative_max_heap_alignment();
1753   _conservative_max_heap_alignment = MAX4(heap_alignment,
1754                                           (size_t)os::vm_allocation_granularity(),
1755                                           os::max_page_size(),
1756                                           CollectorPolicy::compute_heap_alignment());
1757 }
1758 
1759 #ifdef TIERED
1760 bool Arguments::compilation_mode_selected() {
1761  return !FLAG_IS_DEFAULT(TieredCompilation) || !FLAG_IS_DEFAULT(TieredStopAtLevel) ||
1762         !FLAG_IS_DEFAULT(UseAOT) JVMCI_ONLY(|| !FLAG_IS_DEFAULT(EnableJVMCI) || !FLAG_IS_DEFAULT(UseJVMCICompiler));
1763 
1764 }
1765 
1766 void Arguments::select_compilation_mode_ergonomically() {
1767 #if defined(_WINDOWS) && !defined(_LP64)
1768   if (FLAG_IS_DEFAULT(NeverActAsServerClassMachine)) {
1769     FLAG_SET_ERGO(bool, NeverActAsServerClassMachine, true);
1770   }
1771 #endif
1772   if (NeverActAsServerClassMachine) {
1773     set_client_compilation_mode();
1774   }
1775 }
1776 #endif //TIERED
1777 
1778 #if INCLUDE_JVMCI
1779 void Arguments::set_jvmci_specific_flags() {
1780   if (UseJVMCICompiler) {
1781     if (FLAG_IS_DEFAULT(TypeProfileWidth)) {
1782       FLAG_SET_DEFAULT(TypeProfileWidth, 8);
1783     }
1784     if (FLAG_IS_DEFAULT(OnStackReplacePercentage)) {
1785       FLAG_SET_DEFAULT(OnStackReplacePercentage, 933);
1786     }
1787     if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
1788       FLAG_SET_DEFAULT(ReservedCodeCacheSize, 64*M);
1789     }
1790     if (FLAG_IS_DEFAULT(InitialCodeCacheSize)) {
1791       FLAG_SET_DEFAULT(InitialCodeCacheSize, 16*M);
1792     }
1793     if (FLAG_IS_DEFAULT(MetaspaceSize)) {
1794       FLAG_SET_DEFAULT(MetaspaceSize, 12*M);
1795     }
1796     if (FLAG_IS_DEFAULT(NewSizeThreadIncrease)) {
1797       FLAG_SET_DEFAULT(NewSizeThreadIncrease, 4*K);
1798     }
1799     if (TieredStopAtLevel != CompLevel_full_optimization) {
1800       // Currently JVMCI compiler can only work at the full optimization level
1801       warning("forcing TieredStopAtLevel to full optimization because JVMCI is enabled");
1802       TieredStopAtLevel = CompLevel_full_optimization;
1803     }
1804     if (FLAG_IS_DEFAULT(TypeProfileLevel)) {
1805       FLAG_SET_DEFAULT(TypeProfileLevel, 0);
1806     }
1807   }
1808 }
1809 #endif
1810 
1811 jint Arguments::set_ergonomics_flags() {
1812 #ifdef TIERED
1813   if (!compilation_mode_selected()) {
1814     select_compilation_mode_ergonomically();
1815   }
1816 #endif
1817 
1818   jint gc_result = GCArguments::initialize();
1819   if (gc_result != JNI_OK) {
1820     return gc_result;
1821   }
1822 
1823 #if COMPILER2_OR_JVMCI
1824   // Shared spaces work fine with other GCs but causes bytecode rewriting
1825   // to be disabled, which hurts interpreter performance and decreases
1826   // server performance.  When -server is specified, keep the default off
1827   // unless it is asked for.  Future work: either add bytecode rewriting
1828   // at link time, or rewrite bytecodes in non-shared methods.
1829   if (is_server_compilation_mode_vm() && !DumpSharedSpaces && !RequireSharedSpaces &&
1830       (FLAG_IS_DEFAULT(UseSharedSpaces) || !UseSharedSpaces)) {
1831     no_shared_spaces("COMPILER2 default: -Xshare:auto | off, have to manually setup to on.");
1832   }
1833 #endif
1834 
1835 #if defined(IA32)
1836   // Only server compiler can optimize safepoints well enough.
1837   if (!is_server_compilation_mode_vm()) {
1838     FLAG_SET_ERGO_IF_DEFAULT(bool, ThreadLocalHandshakes, false);
1839   }
1840 #endif
1841 
1842   set_conservative_max_heap_alignment();
1843 
1844 #ifndef ZERO
1845 #ifdef _LP64
1846   set_use_compressed_oops();
1847 
1848   // set_use_compressed_klass_ptrs() must be called after calling
1849   // set_use_compressed_oops().
1850   set_use_compressed_klass_ptrs();
1851 
1852   // Also checks that certain machines are slower with compressed oops
1853   // in vm_version initialization code.
1854 #endif // _LP64
1855 #endif // !ZERO
1856 
1857   return JNI_OK;
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       SafepointSynchronize::set_defer_thr_suspend_loop_count();
2955       if (FLAG_SET_CMDLINE(bool, UseTLAB, false) != Flag::SUCCESS) {
2956         return JNI_EINVAL;
2957       }
2958       if (FLAG_SET_CMDLINE(size_t, NewSizeThreadIncrease, 16 * K) != Flag::SUCCESS) {  // 20Kb per thread added to new generation
2959         return JNI_EINVAL;
2960       }
2961 
2962       // -Xinternalversion
2963     } else if (match_option(option, "-Xinternalversion")) {
2964       jio_fprintf(defaultStream::output_stream(), "%s\n",
2965                   VM_Version::internal_vm_info_string());
2966       vm_exit(0);
2967 #ifndef PRODUCT
2968     // -Xprintflags
2969     } else if (match_option(option, "-Xprintflags")) {
2970       CommandLineFlags::printFlags(tty, false);
2971       vm_exit(0);
2972 #endif
2973     // -D
2974     } else if (match_option(option, "-D", &tail)) {
2975       const char* value;
2976       if (match_option(option, "-Djava.endorsed.dirs=", &value) &&
2977             *value!= '\0' && strcmp(value, "\"\"") != 0) {
2978         // abort if -Djava.endorsed.dirs is set
2979         jio_fprintf(defaultStream::output_stream(),
2980           "-Djava.endorsed.dirs=%s is not supported. Endorsed standards and standalone APIs\n"
2981           "in modular form will be supported via the concept of upgradeable modules.\n", value);
2982         return JNI_EINVAL;
2983       }
2984       if (match_option(option, "-Djava.ext.dirs=", &value) &&
2985             *value != '\0' && strcmp(value, "\"\"") != 0) {
2986         // abort if -Djava.ext.dirs is set
2987         jio_fprintf(defaultStream::output_stream(),
2988           "-Djava.ext.dirs=%s is not supported.  Use -classpath instead.\n", value);
2989         return JNI_EINVAL;
2990       }
2991       // Check for module related properties.  They must be set using the modules
2992       // options. For example: use "--add-modules=java.sql", not
2993       // "-Djdk.module.addmods=java.sql"
2994       if (is_internal_module_property(option->optionString + 2)) {
2995         needs_module_property_warning = true;
2996         continue;
2997       }
2998 
2999       if (!add_property(tail)) {
3000         return JNI_ENOMEM;
3001       }
3002       // Out of the box management support
3003       if (match_option(option, "-Dcom.sun.management", &tail)) {
3004 #if INCLUDE_MANAGEMENT
3005         if (FLAG_SET_CMDLINE(bool, ManagementServer, true) != Flag::SUCCESS) {
3006           return JNI_EINVAL;
3007         }
3008         // management agent in module jdk.management.agent
3009         if (!create_numbered_property("jdk.module.addmods", "jdk.management.agent", addmods_count++)) {
3010           return JNI_ENOMEM;
3011         }
3012 #else
3013         jio_fprintf(defaultStream::output_stream(),
3014           "-Dcom.sun.management is not supported in this VM.\n");
3015         return JNI_ERR;
3016 #endif
3017       }
3018     // -Xint
3019     } else if (match_option(option, "-Xint")) {
3020           set_mode_flags(_int);
3021     // -Xmixed
3022     } else if (match_option(option, "-Xmixed")) {
3023           set_mode_flags(_mixed);
3024     // -Xcomp
3025     } else if (match_option(option, "-Xcomp")) {
3026       // for testing the compiler; turn off all flags that inhibit compilation
3027           set_mode_flags(_comp);
3028     // -Xshare:dump
3029     } else if (match_option(option, "-Xshare:dump")) {
3030       if (FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true) != Flag::SUCCESS) {
3031         return JNI_EINVAL;
3032       }
3033       set_mode_flags(_int);     // Prevent compilation, which creates objects
3034     // -Xshare:on
3035     } else if (match_option(option, "-Xshare:on")) {
3036       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3037         return JNI_EINVAL;
3038       }
3039       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3040         return JNI_EINVAL;
3041       }
3042     // -Xshare:auto
3043     } else if (match_option(option, "-Xshare:auto")) {
3044       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3045         return JNI_EINVAL;
3046       }
3047       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3048         return JNI_EINVAL;
3049       }
3050     // -Xshare:off
3051     } else if (match_option(option, "-Xshare:off")) {
3052       if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, false) != Flag::SUCCESS) {
3053         return JNI_EINVAL;
3054       }
3055       if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false) != Flag::SUCCESS) {
3056         return JNI_EINVAL;
3057       }
3058     // -Xverify
3059     } else if (match_option(option, "-Xverify", &tail)) {
3060       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
3061         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, true) != Flag::SUCCESS) {
3062           return JNI_EINVAL;
3063         }
3064         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3065           return JNI_EINVAL;
3066         }
3067       } else if (strcmp(tail, ":remote") == 0) {
3068         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3069           return JNI_EINVAL;
3070         }
3071         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, true) != Flag::SUCCESS) {
3072           return JNI_EINVAL;
3073         }
3074       } else if (strcmp(tail, ":none") == 0) {
3075         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationLocal, false) != Flag::SUCCESS) {
3076           return JNI_EINVAL;
3077         }
3078         if (FLAG_SET_CMDLINE(bool, BytecodeVerificationRemote, false) != Flag::SUCCESS) {
3079           return JNI_EINVAL;
3080         }
3081       } else if (is_bad_option(option, args->ignoreUnrecognized, "verification")) {
3082         return JNI_EINVAL;
3083       }
3084     // -Xdebug
3085     } else if (match_option(option, "-Xdebug")) {
3086       // note this flag has been used, then ignore
3087       set_xdebug_mode(true);
3088     // -Xnoagent
3089     } else if (match_option(option, "-Xnoagent")) {
3090       // For compatibility with classic. HotSpot refuses to load the old style agent.dll.
3091     } else if (match_option(option, "-Xloggc:", &tail)) {
3092       // Deprecated flag to redirect GC output to a file. -Xloggc:<filename>
3093       log_warning(gc)("-Xloggc is deprecated. Will use -Xlog:gc:%s instead.", tail);
3094       _gc_log_filename = os::strdup_check_oom(tail);
3095     } else if (match_option(option, "-Xlog", &tail)) {
3096       bool ret = false;
3097       if (strcmp(tail, ":help") == 0) {
3098         fileStream stream(defaultStream::output_stream());
3099         LogConfiguration::print_command_line_help(&stream);
3100         vm_exit(0);
3101       } else if (strcmp(tail, ":disable") == 0) {
3102         LogConfiguration::disable_logging();
3103         ret = true;
3104       } else if (*tail == '\0') {
3105         ret = LogConfiguration::parse_command_line_arguments();
3106         assert(ret, "-Xlog without arguments should never fail to parse");
3107       } else if (*tail == ':') {
3108         ret = LogConfiguration::parse_command_line_arguments(tail + 1);
3109       }
3110       if (ret == false) {
3111         jio_fprintf(defaultStream::error_stream(),
3112                     "Invalid -Xlog option '-Xlog%s', see error log for details.\n",
3113                     tail);
3114         return JNI_EINVAL;
3115       }
3116     // JNI hooks
3117     } else if (match_option(option, "-Xcheck", &tail)) {
3118       if (!strcmp(tail, ":jni")) {
3119 #if !INCLUDE_JNI_CHECK
3120         warning("JNI CHECKING is not supported in this VM");
3121 #else
3122         CheckJNICalls = true;
3123 #endif // INCLUDE_JNI_CHECK
3124       } else if (is_bad_option(option, args->ignoreUnrecognized,
3125                                      "check")) {
3126         return JNI_EINVAL;
3127       }
3128     } else if (match_option(option, "vfprintf")) {
3129       _vfprintf_hook = CAST_TO_FN_PTR(vfprintf_hook_t, option->extraInfo);
3130     } else if (match_option(option, "exit")) {
3131       _exit_hook = CAST_TO_FN_PTR(exit_hook_t, option->extraInfo);
3132     } else if (match_option(option, "abort")) {
3133       _abort_hook = CAST_TO_FN_PTR(abort_hook_t, option->extraInfo);
3134     // Need to keep consistency of MaxTenuringThreshold and AlwaysTenure/NeverTenure;
3135     // and the last option wins.
3136     } else if (match_option(option, "-XX:+NeverTenure")) {
3137       if (FLAG_SET_CMDLINE(bool, NeverTenure, true) != Flag::SUCCESS) {
3138         return JNI_EINVAL;
3139       }
3140       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3141         return JNI_EINVAL;
3142       }
3143       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, markOopDesc::max_age + 1) != Flag::SUCCESS) {
3144         return JNI_EINVAL;
3145       }
3146     } else if (match_option(option, "-XX:+AlwaysTenure")) {
3147       if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3148         return JNI_EINVAL;
3149       }
3150       if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3151         return JNI_EINVAL;
3152       }
3153       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, 0) != Flag::SUCCESS) {
3154         return JNI_EINVAL;
3155       }
3156     } else if (match_option(option, "-XX:MaxTenuringThreshold=", &tail)) {
3157       uintx max_tenuring_thresh = 0;
3158       if (!parse_uintx(tail, &max_tenuring_thresh, 0)) {
3159         jio_fprintf(defaultStream::error_stream(),
3160                     "Improperly specified VM option \'MaxTenuringThreshold=%s\'\n", tail);
3161         return JNI_EINVAL;
3162       }
3163 
3164       if (FLAG_SET_CMDLINE(uintx, MaxTenuringThreshold, max_tenuring_thresh) != Flag::SUCCESS) {
3165         return JNI_EINVAL;
3166       }
3167 
3168       if (MaxTenuringThreshold == 0) {
3169         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3170           return JNI_EINVAL;
3171         }
3172         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, true) != Flag::SUCCESS) {
3173           return JNI_EINVAL;
3174         }
3175       } else {
3176         if (FLAG_SET_CMDLINE(bool, NeverTenure, false) != Flag::SUCCESS) {
3177           return JNI_EINVAL;
3178         }
3179         if (FLAG_SET_CMDLINE(bool, AlwaysTenure, false) != Flag::SUCCESS) {
3180           return JNI_EINVAL;
3181         }
3182       }
3183     } else if (match_option(option, "-XX:+DisplayVMOutputToStderr")) {
3184       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false) != Flag::SUCCESS) {
3185         return JNI_EINVAL;
3186       }
3187       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true) != Flag::SUCCESS) {
3188         return JNI_EINVAL;
3189       }
3190     } else if (match_option(option, "-XX:+DisplayVMOutputToStdout")) {
3191       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, false) != Flag::SUCCESS) {
3192         return JNI_EINVAL;
3193       }
3194       if (FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, true) != Flag::SUCCESS) {
3195         return JNI_EINVAL;
3196       }
3197     } else if (match_option(option, "-XX:+ExtendedDTraceProbes")) {
3198 #if defined(DTRACE_ENABLED)
3199       if (FLAG_SET_CMDLINE(bool, ExtendedDTraceProbes, true) != Flag::SUCCESS) {
3200         return JNI_EINVAL;
3201       }
3202       if (FLAG_SET_CMDLINE(bool, DTraceMethodProbes, true) != Flag::SUCCESS) {
3203         return JNI_EINVAL;
3204       }
3205       if (FLAG_SET_CMDLINE(bool, DTraceAllocProbes, true) != Flag::SUCCESS) {
3206         return JNI_EINVAL;
3207       }
3208       if (FLAG_SET_CMDLINE(bool, DTraceMonitorProbes, true) != Flag::SUCCESS) {
3209         return JNI_EINVAL;
3210       }
3211 #else // defined(DTRACE_ENABLED)
3212       jio_fprintf(defaultStream::error_stream(),
3213                   "ExtendedDTraceProbes flag is not applicable for this configuration\n");
3214       return JNI_EINVAL;
3215 #endif // defined(DTRACE_ENABLED)
3216 #ifdef ASSERT
3217     } else if (match_option(option, "-XX:+FullGCALot")) {
3218       if (FLAG_SET_CMDLINE(bool, FullGCALot, true) != Flag::SUCCESS) {
3219         return JNI_EINVAL;
3220       }
3221       // disable scavenge before parallel mark-compact
3222       if (FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false) != Flag::SUCCESS) {
3223         return JNI_EINVAL;
3224       }
3225 #endif
3226 #if !INCLUDE_MANAGEMENT
3227     } else if (match_option(option, "-XX:+ManagementServer")) {
3228         jio_fprintf(defaultStream::error_stream(),
3229           "ManagementServer is not supported in this VM.\n");
3230         return JNI_ERR;
3231 #endif // INCLUDE_MANAGEMENT
3232     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
3233       // Skip -XX:Flags= and -XX:VMOptionsFile= since those cases have
3234       // already been handled
3235       if ((strncmp(tail, "Flags=", strlen("Flags=")) != 0) &&
3236           (strncmp(tail, "VMOptionsFile=", strlen("VMOptionsFile=")) != 0)) {
3237         if (!process_argument(tail, args->ignoreUnrecognized, origin)) {
3238           return JNI_EINVAL;
3239         }
3240       }
3241     // Unknown option
3242     } else if (is_bad_option(option, args->ignoreUnrecognized)) {
3243       return JNI_ERR;
3244     }
3245   }
3246 
3247   // PrintSharedArchiveAndExit will turn on
3248   //   -Xshare:on
3249   //   -Xlog:class+path=info
3250   if (PrintSharedArchiveAndExit) {
3251     if (FLAG_SET_CMDLINE(bool, UseSharedSpaces, true) != Flag::SUCCESS) {
3252       return JNI_EINVAL;
3253     }
3254     if (FLAG_SET_CMDLINE(bool, RequireSharedSpaces, true) != Flag::SUCCESS) {
3255       return JNI_EINVAL;
3256     }
3257     LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(class, path));
3258   }
3259 
3260   // Change the default value for flags  which have different default values
3261   // when working with older JDKs.
3262 #ifdef LINUX
3263  if (JDK_Version::current().compare_major(6) <= 0 &&
3264       FLAG_IS_DEFAULT(UseLinuxPosixThreadCPUClocks)) {
3265     FLAG_SET_DEFAULT(UseLinuxPosixThreadCPUClocks, false);
3266   }
3267 #endif // LINUX
3268   fix_appclasspath();
3269   return JNI_OK;
3270 }
3271 
3272 void Arguments::add_patch_mod_prefix(const char* module_name, const char* path, bool* patch_mod_javabase) {
3273   // For java.base check for duplicate --patch-module options being specified on the command line.
3274   // This check is only required for java.base, all other duplicate module specifications
3275   // will be checked during module system initialization.  The module system initialization
3276   // will throw an ExceptionInInitializerError if this situation occurs.
3277   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
3278     if (*patch_mod_javabase) {
3279       vm_exit_during_initialization("Cannot specify " JAVA_BASE_NAME " more than once to --patch-module");
3280     } else {
3281       *patch_mod_javabase = true;
3282     }
3283   }
3284 
3285   // Create GrowableArray lazily, only if --patch-module has been specified
3286   if (_patch_mod_prefix == NULL) {
3287     _patch_mod_prefix = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<ModulePatchPath*>(10, true);
3288   }
3289 
3290   _patch_mod_prefix->push(new ModulePatchPath(module_name, path));
3291 }
3292 
3293 // Remove all empty paths from the app classpath (if IgnoreEmptyClassPaths is enabled)
3294 //
3295 // This is necessary because some apps like to specify classpath like -cp foo.jar:${XYZ}:bar.jar
3296 // in their start-up scripts. If XYZ is empty, the classpath will look like "-cp foo.jar::bar.jar".
3297 // Java treats such empty paths as if the user specified "-cp foo.jar:.:bar.jar". I.e., an empty
3298 // path is treated as the current directory.
3299 //
3300 // This causes problems with CDS, which requires that all directories specified in the classpath
3301 // must be empty. In most cases, applications do NOT want to load classes from the current
3302 // directory anyway. Adding -XX:+IgnoreEmptyClassPaths will make these applications' start-up
3303 // scripts compatible with CDS.
3304 void Arguments::fix_appclasspath() {
3305   if (IgnoreEmptyClassPaths) {
3306     const char separator = *os::path_separator();
3307     const char* src = _java_class_path->value();
3308 
3309     // skip over all the leading empty paths
3310     while (*src == separator) {
3311       src ++;
3312     }
3313 
3314     char* copy = os::strdup_check_oom(src, mtArguments);
3315 
3316     // trim all trailing empty paths
3317     for (char* tail = copy + strlen(copy) - 1; tail >= copy && *tail == separator; tail--) {
3318       *tail = '\0';
3319     }
3320 
3321     char from[3] = {separator, separator, '\0'};
3322     char to  [2] = {separator, '\0'};
3323     while (StringUtils::replace_no_expand(copy, from, to) > 0) {
3324       // Keep replacing "::" -> ":" until we have no more "::" (non-windows)
3325       // Keep replacing ";;" -> ";" until we have no more ";;" (windows)
3326     }
3327 
3328     _java_class_path->set_writeable_value(copy);
3329     FreeHeap(copy); // a copy was made by set_value, so don't need this anymore
3330   }
3331 }
3332 
3333 static bool has_jar_files(const char* directory) {
3334   DIR* dir = os::opendir(directory);
3335   if (dir == NULL) return false;
3336 
3337   struct dirent *entry;
3338   char *dbuf = NEW_C_HEAP_ARRAY(char, os::readdir_buf_size(directory), mtArguments);
3339   bool hasJarFile = false;
3340   while (!hasJarFile && (entry = os::readdir(dir, (dirent *) dbuf)) != NULL) {
3341     const char* name = entry->d_name;
3342     const char* ext = name + strlen(name) - 4;
3343     hasJarFile = ext > name && (os::file_name_strcmp(ext, ".jar") == 0);
3344   }
3345   FREE_C_HEAP_ARRAY(char, dbuf);
3346   os::closedir(dir);
3347   return hasJarFile ;
3348 }
3349 
3350 static int check_non_empty_dirs(const char* path) {
3351   const char separator = *os::path_separator();
3352   const char* const end = path + strlen(path);
3353   int nonEmptyDirs = 0;
3354   while (path < end) {
3355     const char* tmp_end = strchr(path, separator);
3356     if (tmp_end == NULL) {
3357       if (has_jar_files(path)) {
3358         nonEmptyDirs++;
3359         jio_fprintf(defaultStream::output_stream(),
3360           "Non-empty directory: %s\n", path);
3361       }
3362       path = end;
3363     } else {
3364       char* dirpath = NEW_C_HEAP_ARRAY(char, tmp_end - path + 1, mtArguments);
3365       memcpy(dirpath, path, tmp_end - path);
3366       dirpath[tmp_end - path] = '\0';
3367       if (has_jar_files(dirpath)) {
3368         nonEmptyDirs++;
3369         jio_fprintf(defaultStream::output_stream(),
3370           "Non-empty directory: %s\n", dirpath);
3371       }
3372       FREE_C_HEAP_ARRAY(char, dirpath);
3373       path = tmp_end + 1;
3374     }
3375   }
3376   return nonEmptyDirs;
3377 }
3378 
3379 jint Arguments::finalize_vm_init_args(bool patch_mod_javabase) {
3380   // check if the default lib/endorsed directory exists; if so, error
3381   char path[JVM_MAXPATHLEN];
3382   const char* fileSep = os::file_separator();
3383   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sendorsed", Arguments::get_java_home(), fileSep, fileSep);
3384 
3385   if (CheckEndorsedAndExtDirs) {
3386     int nonEmptyDirs = 0;
3387     // check endorsed directory
3388     nonEmptyDirs += check_non_empty_dirs(path);
3389     // check the extension directories
3390     nonEmptyDirs += check_non_empty_dirs(Arguments::get_ext_dirs());
3391     if (nonEmptyDirs > 0) {
3392       return JNI_ERR;
3393     }
3394   }
3395 
3396   DIR* dir = os::opendir(path);
3397   if (dir != NULL) {
3398     jio_fprintf(defaultStream::output_stream(),
3399       "<JAVA_HOME>/lib/endorsed is not supported. Endorsed standards and standalone APIs\n"
3400       "in modular form will be supported via the concept of upgradeable modules.\n");
3401     os::closedir(dir);
3402     return JNI_ERR;
3403   }
3404 
3405   jio_snprintf(path, JVM_MAXPATHLEN, "%s%slib%sext", Arguments::get_java_home(), fileSep, fileSep);
3406   dir = os::opendir(path);
3407   if (dir != NULL) {
3408     jio_fprintf(defaultStream::output_stream(),
3409       "<JAVA_HOME>/lib/ext exists, extensions mechanism no longer supported; "
3410       "Use -classpath instead.\n.");
3411     os::closedir(dir);
3412     return JNI_ERR;
3413   }
3414 
3415   // This must be done after all arguments have been processed
3416   // and the container support has been initialized since AggressiveHeap
3417   // relies on the amount of total memory available.
3418   if (AggressiveHeap) {
3419     jint result = set_aggressive_heap_flags();
3420     if (result != JNI_OK) {
3421       return result;
3422     }
3423   }
3424 
3425   // This must be done after all arguments have been processed.
3426   // java_compiler() true means set to "NONE" or empty.
3427   if (java_compiler() && !xdebug_mode()) {
3428     // For backwards compatibility, we switch to interpreted mode if
3429     // -Djava.compiler="NONE" or "" is specified AND "-Xdebug" was
3430     // not specified.
3431     set_mode_flags(_int);
3432   }
3433 
3434   // CompileThresholdScaling == 0.0 is same as -Xint: Disable compilation (enable interpreter-only mode),
3435   // but like -Xint, leave compilation thresholds unaffected.
3436   // With tiered compilation disabled, setting CompileThreshold to 0 disables compilation as well.
3437   if ((CompileThresholdScaling == 0.0) || (!TieredCompilation && CompileThreshold == 0)) {
3438     set_mode_flags(_int);
3439   }
3440 
3441   // eventually fix up InitialTenuringThreshold if only MaxTenuringThreshold is set
3442   if (FLAG_IS_DEFAULT(InitialTenuringThreshold) && (InitialTenuringThreshold > MaxTenuringThreshold)) {
3443     FLAG_SET_ERGO(uintx, InitialTenuringThreshold, MaxTenuringThreshold);
3444   }
3445 
3446 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3447   // Don't degrade server performance for footprint
3448   if (FLAG_IS_DEFAULT(UseLargePages) &&
3449       MaxHeapSize < LargePageHeapSizeThreshold) {
3450     // No need for large granularity pages w/small heaps.
3451     // Note that large pages are enabled/disabled for both the
3452     // Java heap and the code cache.
3453     FLAG_SET_DEFAULT(UseLargePages, false);
3454   }
3455 
3456 #elif defined(COMPILER2)
3457   if (!FLAG_IS_DEFAULT(OptoLoopAlignment) && FLAG_IS_DEFAULT(MaxLoopPad)) {
3458     FLAG_SET_DEFAULT(MaxLoopPad, OptoLoopAlignment-1);
3459   }
3460 #endif
3461 
3462 #if !defined(COMPILER2) && !INCLUDE_JVMCI
3463   UNSUPPORTED_OPTION(ProfileInterpreter);
3464   NOT_PRODUCT(UNSUPPORTED_OPTION(TraceProfileInterpreter));
3465 #endif
3466 
3467 #ifndef TIERED
3468   // Tiered compilation is undefined.
3469   UNSUPPORTED_OPTION(TieredCompilation);
3470 #endif
3471 
3472 #if INCLUDE_JVMCI
3473   if (EnableJVMCI &&
3474       !create_numbered_property("jdk.module.addmods", "jdk.internal.vm.ci", addmods_count++)) {
3475     return JNI_ENOMEM;
3476   }
3477 #endif
3478 
3479   if (!check_vm_args_consistency()) {
3480     return JNI_ERR;
3481   }
3482 
3483 #if INCLUDE_JVMCI
3484   if (UseJVMCICompiler) {
3485     Compilation_mode = CompMode_server;
3486   }
3487 #endif
3488 
3489 #if INCLUDE_CDS
3490   if (DumpSharedSpaces) {
3491     // Disable biased locking now as it interferes with the clean up of
3492     // the archived Klasses and Java string objects (at dump time only).
3493     UseBiasedLocking = false;
3494   }
3495   if (UseSharedSpaces && patch_mod_javabase) {
3496     no_shared_spaces("CDS is disabled when " JAVA_BASE_NAME " module is patched.");
3497   }
3498 #endif
3499 
3500   return JNI_OK;
3501 }
3502 
3503 // Helper class for controlling the lifetime of JavaVMInitArgs
3504 // objects.  The contents of the JavaVMInitArgs are guaranteed to be
3505 // deleted on the destruction of the ScopedVMInitArgs object.
3506 class ScopedVMInitArgs : public StackObj {
3507  private:
3508   JavaVMInitArgs _args;
3509   char*          _container_name;
3510   bool           _is_set;
3511   char*          _vm_options_file_arg;
3512 
3513  public:
3514   ScopedVMInitArgs(const char *container_name) {
3515     _args.version = JNI_VERSION_1_2;
3516     _args.nOptions = 0;
3517     _args.options = NULL;
3518     _args.ignoreUnrecognized = false;
3519     _container_name = (char *)container_name;
3520     _is_set = false;
3521     _vm_options_file_arg = NULL;
3522   }
3523 
3524   // Populates the JavaVMInitArgs object represented by this
3525   // ScopedVMInitArgs object with the arguments in options.  The
3526   // allocated memory is deleted by the destructor.  If this method
3527   // returns anything other than JNI_OK, then this object is in a
3528   // partially constructed state, and should be abandoned.
3529   jint set_args(GrowableArray<JavaVMOption>* options) {
3530     _is_set = true;
3531     JavaVMOption* options_arr = NEW_C_HEAP_ARRAY_RETURN_NULL(
3532         JavaVMOption, options->length(), mtArguments);
3533     if (options_arr == NULL) {
3534       return JNI_ENOMEM;
3535     }
3536     _args.options = options_arr;
3537 
3538     for (int i = 0; i < options->length(); i++) {
3539       options_arr[i] = options->at(i);
3540       options_arr[i].optionString = os::strdup(options_arr[i].optionString);
3541       if (options_arr[i].optionString == NULL) {
3542         // Rely on the destructor to do cleanup.
3543         _args.nOptions = i;
3544         return JNI_ENOMEM;
3545       }
3546     }
3547 
3548     _args.nOptions = options->length();
3549     _args.ignoreUnrecognized = IgnoreUnrecognizedVMOptions;
3550     return JNI_OK;
3551   }
3552 
3553   JavaVMInitArgs* get()             { return &_args; }
3554   char* container_name()            { return _container_name; }
3555   bool  is_set()                    { return _is_set; }
3556   bool  found_vm_options_file_arg() { return _vm_options_file_arg != NULL; }
3557   char* vm_options_file_arg()       { return _vm_options_file_arg; }
3558 
3559   void set_vm_options_file_arg(const char *vm_options_file_arg) {
3560     if (_vm_options_file_arg != NULL) {
3561       os::free(_vm_options_file_arg);
3562     }
3563     _vm_options_file_arg = os::strdup_check_oom(vm_options_file_arg);
3564   }
3565 
3566   ~ScopedVMInitArgs() {
3567     if (_vm_options_file_arg != NULL) {
3568       os::free(_vm_options_file_arg);
3569     }
3570     if (_args.options == NULL) return;
3571     for (int i = 0; i < _args.nOptions; i++) {
3572       os::free(_args.options[i].optionString);
3573     }
3574     FREE_C_HEAP_ARRAY(JavaVMOption, _args.options);
3575   }
3576 
3577   // Insert options into this option list, to replace option at
3578   // vm_options_file_pos (-XX:VMOptionsFile)
3579   jint insert(const JavaVMInitArgs* args,
3580               const JavaVMInitArgs* args_to_insert,
3581               const int vm_options_file_pos) {
3582     assert(_args.options == NULL, "shouldn't be set yet");
3583     assert(args_to_insert->nOptions != 0, "there should be args to insert");
3584     assert(vm_options_file_pos != -1, "vm_options_file_pos should be set");
3585 
3586     int length = args->nOptions + args_to_insert->nOptions - 1;
3587     GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments)
3588               GrowableArray<JavaVMOption>(length, true);    // Construct new option array
3589     for (int i = 0; i < args->nOptions; i++) {
3590       if (i == vm_options_file_pos) {
3591         // insert the new options starting at the same place as the
3592         // -XX:VMOptionsFile option
3593         for (int j = 0; j < args_to_insert->nOptions; j++) {
3594           options->push(args_to_insert->options[j]);
3595         }
3596       } else {
3597         options->push(args->options[i]);
3598       }
3599     }
3600     // make into options array
3601     jint result = set_args(options);
3602     delete options;
3603     return result;
3604   }
3605 };
3606 
3607 jint Arguments::parse_java_options_environment_variable(ScopedVMInitArgs* args) {
3608   return parse_options_environment_variable("_JAVA_OPTIONS", args);
3609 }
3610 
3611 jint Arguments::parse_java_tool_options_environment_variable(ScopedVMInitArgs* args) {
3612   return parse_options_environment_variable("JAVA_TOOL_OPTIONS", args);
3613 }
3614 
3615 jint Arguments::parse_options_environment_variable(const char* name,
3616                                                    ScopedVMInitArgs* vm_args) {
3617   char *buffer = ::getenv(name);
3618 
3619   // Don't check this environment variable if user has special privileges
3620   // (e.g. unix su command).
3621   if (buffer == NULL || os::have_special_privileges()) {
3622     return JNI_OK;
3623   }
3624 
3625   if ((buffer = os::strdup(buffer)) == NULL) {
3626     return JNI_ENOMEM;
3627   }
3628 
3629   jio_fprintf(defaultStream::error_stream(),
3630               "Picked up %s: %s\n", name, buffer);
3631 
3632   int retcode = parse_options_buffer(name, buffer, strlen(buffer), vm_args);
3633 
3634   os::free(buffer);
3635   return retcode;
3636 }
3637 
3638 jint Arguments::parse_vm_options_file(const char* file_name, ScopedVMInitArgs* vm_args) {
3639   // read file into buffer
3640   int fd = ::open(file_name, O_RDONLY);
3641   if (fd < 0) {
3642     jio_fprintf(defaultStream::error_stream(),
3643                 "Could not open options file '%s'\n",
3644                 file_name);
3645     return JNI_ERR;
3646   }
3647 
3648   struct stat stbuf;
3649   int retcode = os::stat(file_name, &stbuf);
3650   if (retcode != 0) {
3651     jio_fprintf(defaultStream::error_stream(),
3652                 "Could not stat options file '%s'\n",
3653                 file_name);
3654     os::close(fd);
3655     return JNI_ERR;
3656   }
3657 
3658   if (stbuf.st_size == 0) {
3659     // tell caller there is no option data and that is ok
3660     os::close(fd);
3661     return JNI_OK;
3662   }
3663 
3664   // '+ 1' for NULL termination even with max bytes
3665   size_t bytes_alloc = stbuf.st_size + 1;
3666 
3667   char *buf = NEW_C_HEAP_ARRAY_RETURN_NULL(char, bytes_alloc, mtArguments);
3668   if (NULL == buf) {
3669     jio_fprintf(defaultStream::error_stream(),
3670                 "Could not allocate read buffer for options file parse\n");
3671     os::close(fd);
3672     return JNI_ENOMEM;
3673   }
3674 
3675   memset(buf, 0, bytes_alloc);
3676 
3677   // Fill buffer
3678   // Use ::read() instead of os::read because os::read()
3679   // might do a thread state transition
3680   // and it is too early for that here
3681 
3682   ssize_t bytes_read = ::read(fd, (void *)buf, (unsigned)bytes_alloc);
3683   os::close(fd);
3684   if (bytes_read < 0) {
3685     FREE_C_HEAP_ARRAY(char, buf);
3686     jio_fprintf(defaultStream::error_stream(),
3687                 "Could not read options file '%s'\n", file_name);
3688     return JNI_ERR;
3689   }
3690 
3691   if (bytes_read == 0) {
3692     // tell caller there is no option data and that is ok
3693     FREE_C_HEAP_ARRAY(char, buf);
3694     return JNI_OK;
3695   }
3696 
3697   retcode = parse_options_buffer(file_name, buf, bytes_read, vm_args);
3698 
3699   FREE_C_HEAP_ARRAY(char, buf);
3700   return retcode;
3701 }
3702 
3703 jint Arguments::parse_options_buffer(const char* name, char* buffer, const size_t buf_len, ScopedVMInitArgs* vm_args) {
3704   GrowableArray<JavaVMOption> *options = new (ResourceObj::C_HEAP, mtArguments) GrowableArray<JavaVMOption>(2, true);    // Construct option array
3705 
3706   // some pointers to help with parsing
3707   char *buffer_end = buffer + buf_len;
3708   char *opt_hd = buffer;
3709   char *wrt = buffer;
3710   char *rd = buffer;
3711 
3712   // parse all options
3713   while (rd < buffer_end) {
3714     // skip leading white space from the input string
3715     while (rd < buffer_end && isspace(*rd)) {
3716       rd++;
3717     }
3718 
3719     if (rd >= buffer_end) {
3720       break;
3721     }
3722 
3723     // Remember this is where we found the head of the token.
3724     opt_hd = wrt;
3725 
3726     // Tokens are strings of non white space characters separated
3727     // by one or more white spaces.
3728     while (rd < buffer_end && !isspace(*rd)) {
3729       if (*rd == '\'' || *rd == '"') {      // handle a quoted string
3730         int quote = *rd;                    // matching quote to look for
3731         rd++;                               // don't copy open quote
3732         while (rd < buffer_end && *rd != quote) {
3733                                             // include everything (even spaces)
3734                                             // up until the close quote
3735           *wrt++ = *rd++;                   // copy to option string
3736         }
3737 
3738         if (rd < buffer_end) {
3739           rd++;                             // don't copy close quote
3740         } else {
3741                                             // did not see closing quote
3742           jio_fprintf(defaultStream::error_stream(),
3743                       "Unmatched quote in %s\n", name);
3744           delete options;
3745           return JNI_ERR;
3746         }
3747       } else {
3748         *wrt++ = *rd++;                     // copy to option string
3749       }
3750     }
3751 
3752     // steal a white space character and set it to NULL
3753     *wrt++ = '\0';
3754     // We now have a complete token
3755 
3756     JavaVMOption option;
3757     option.optionString = opt_hd;
3758     option.extraInfo = NULL;
3759 
3760     options->append(option);                // Fill in option
3761 
3762     rd++;  // Advance to next character
3763   }
3764 
3765   // Fill out JavaVMInitArgs structure.
3766   jint status = vm_args->set_args(options);
3767 
3768   delete options;
3769   return status;
3770 }
3771 
3772 void Arguments::set_shared_spaces_flags() {
3773   if (DumpSharedSpaces) {
3774     if (FailOverToOldVerifier) {
3775       // Don't fall back to the old verifier on verification failure. If a
3776       // class fails verification with the split verifier, it might fail the
3777       // CDS runtime verifier constraint check. In that case, we don't want
3778       // to share the class. We only archive classes that pass the split verifier.
3779       FLAG_SET_DEFAULT(FailOverToOldVerifier, false);
3780     }
3781 
3782     if (RequireSharedSpaces) {
3783       warning("Cannot dump shared archive while using shared archive");
3784     }
3785     UseSharedSpaces = false;
3786 #ifdef _LP64
3787     if (!UseCompressedOops || !UseCompressedClassPointers) {
3788       vm_exit_during_initialization(
3789         "Cannot dump shared archive when UseCompressedOops or UseCompressedClassPointers is off.", NULL);
3790     }
3791   } else {
3792     if (!UseCompressedOops || !UseCompressedClassPointers) {
3793       no_shared_spaces("UseCompressedOops and UseCompressedClassPointers must be on for UseSharedSpaces.");
3794     }
3795 #endif
3796   }
3797 }
3798 
3799 // Sharing support
3800 // Construct the path to the archive
3801 static char* get_shared_archive_path() {
3802   char *shared_archive_path;
3803   if (SharedArchiveFile == NULL) {
3804     char jvm_path[JVM_MAXPATHLEN];
3805     os::jvm_path(jvm_path, sizeof(jvm_path));
3806     char *end = strrchr(jvm_path, *os::file_separator());
3807     if (end != NULL) *end = '\0';
3808     size_t jvm_path_len = strlen(jvm_path);
3809     size_t file_sep_len = strlen(os::file_separator());
3810     const size_t len = jvm_path_len + file_sep_len + 20;
3811     shared_archive_path = NEW_C_HEAP_ARRAY(char, len, mtArguments);
3812     if (shared_archive_path != NULL) {
3813       jio_snprintf(shared_archive_path, len, "%s%sclasses.jsa",
3814         jvm_path, os::file_separator());
3815     }
3816   } else {
3817     shared_archive_path = os::strdup_check_oom(SharedArchiveFile, mtArguments);
3818   }
3819   return shared_archive_path;
3820 }
3821 
3822 #ifndef PRODUCT
3823 // Determine whether LogVMOutput should be implicitly turned on.
3824 static bool use_vm_log() {
3825   if (LogCompilation || !FLAG_IS_DEFAULT(LogFile) ||
3826       PrintCompilation || PrintInlining || PrintDependencies || PrintNativeNMethods ||
3827       PrintDebugInfo || PrintRelocations || PrintNMethods || PrintExceptionHandlers ||
3828       PrintAssembly || TraceDeoptimization || TraceDependencies ||
3829       (VerifyDependencies && FLAG_IS_CMDLINE(VerifyDependencies))) {
3830     return true;
3831   }
3832 
3833 #ifdef COMPILER1
3834   if (PrintC1Statistics) {
3835     return true;
3836   }
3837 #endif // COMPILER1
3838 
3839 #ifdef COMPILER2
3840   if (PrintOptoAssembly || PrintOptoStatistics) {
3841     return true;
3842   }
3843 #endif // COMPILER2
3844 
3845   return false;
3846 }
3847 
3848 #endif // PRODUCT
3849 
3850 bool Arguments::args_contains_vm_options_file_arg(const JavaVMInitArgs* args) {
3851   for (int index = 0; index < args->nOptions; index++) {
3852     const JavaVMOption* option = args->options + index;
3853     const char* tail;
3854     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3855       return true;
3856     }
3857   }
3858   return false;
3859 }
3860 
3861 jint Arguments::insert_vm_options_file(const JavaVMInitArgs* args,
3862                                        const char* vm_options_file,
3863                                        const int vm_options_file_pos,
3864                                        ScopedVMInitArgs* vm_options_file_args,
3865                                        ScopedVMInitArgs* args_out) {
3866   jint code = parse_vm_options_file(vm_options_file, vm_options_file_args);
3867   if (code != JNI_OK) {
3868     return code;
3869   }
3870 
3871   if (vm_options_file_args->get()->nOptions < 1) {
3872     return JNI_OK;
3873   }
3874 
3875   if (args_contains_vm_options_file_arg(vm_options_file_args->get())) {
3876     jio_fprintf(defaultStream::error_stream(),
3877                 "A VM options file may not refer to a VM options file. "
3878                 "Specification of '-XX:VMOptionsFile=<file-name>' in the "
3879                 "options file '%s' in options container '%s' is an error.\n",
3880                 vm_options_file_args->vm_options_file_arg(),
3881                 vm_options_file_args->container_name());
3882     return JNI_EINVAL;
3883   }
3884 
3885   return args_out->insert(args, vm_options_file_args->get(),
3886                           vm_options_file_pos);
3887 }
3888 
3889 // Expand -XX:VMOptionsFile found in args_in as needed.
3890 // mod_args and args_out parameters may return values as needed.
3891 jint Arguments::expand_vm_options_as_needed(const JavaVMInitArgs* args_in,
3892                                             ScopedVMInitArgs* mod_args,
3893                                             JavaVMInitArgs** args_out) {
3894   jint code = match_special_option_and_act(args_in, mod_args);
3895   if (code != JNI_OK) {
3896     return code;
3897   }
3898 
3899   if (mod_args->is_set()) {
3900     // args_in contains -XX:VMOptionsFile and mod_args contains the
3901     // original options from args_in along with the options expanded
3902     // from the VMOptionsFile. Return a short-hand to the caller.
3903     *args_out = mod_args->get();
3904   } else {
3905     *args_out = (JavaVMInitArgs *)args_in;  // no changes so use args_in
3906   }
3907   return JNI_OK;
3908 }
3909 
3910 jint Arguments::match_special_option_and_act(const JavaVMInitArgs* args,
3911                                              ScopedVMInitArgs* args_out) {
3912   // Remaining part of option string
3913   const char* tail;
3914   ScopedVMInitArgs vm_options_file_args(args_out->container_name());
3915 
3916   for (int index = 0; index < args->nOptions; index++) {
3917     const JavaVMOption* option = args->options + index;
3918     if (ArgumentsExt::process_options(option)) {
3919       continue;
3920     }
3921     if (match_option(option, "-XX:Flags=", &tail)) {
3922       Arguments::set_jvm_flags_file(tail);
3923       continue;
3924     }
3925     if (match_option(option, "-XX:VMOptionsFile=", &tail)) {
3926       if (vm_options_file_args.found_vm_options_file_arg()) {
3927         jio_fprintf(defaultStream::error_stream(),
3928                     "The option '%s' is already specified in the options "
3929                     "container '%s' so the specification of '%s' in the "
3930                     "same options container is an error.\n",
3931                     vm_options_file_args.vm_options_file_arg(),
3932                     vm_options_file_args.container_name(),
3933                     option->optionString);
3934         return JNI_EINVAL;
3935       }
3936       vm_options_file_args.set_vm_options_file_arg(option->optionString);
3937       // If there's a VMOptionsFile, parse that
3938       jint code = insert_vm_options_file(args, tail, index,
3939                                          &vm_options_file_args, args_out);
3940       if (code != JNI_OK) {
3941         return code;
3942       }
3943       args_out->set_vm_options_file_arg(vm_options_file_args.vm_options_file_arg());
3944       if (args_out->is_set()) {
3945         // The VMOptions file inserted some options so switch 'args'
3946         // to the new set of options, and continue processing which
3947         // preserves "last option wins" semantics.
3948         args = args_out->get();
3949         // The first option from the VMOptionsFile replaces the
3950         // current option.  So we back track to process the
3951         // replacement option.
3952         index--;
3953       }
3954       continue;
3955     }
3956     if (match_option(option, "-XX:+PrintVMOptions")) {
3957       PrintVMOptions = true;
3958       continue;
3959     }
3960     if (match_option(option, "-XX:-PrintVMOptions")) {
3961       PrintVMOptions = false;
3962       continue;
3963     }
3964     if (match_option(option, "-XX:+IgnoreUnrecognizedVMOptions")) {
3965       IgnoreUnrecognizedVMOptions = true;
3966       continue;
3967     }
3968     if (match_option(option, "-XX:-IgnoreUnrecognizedVMOptions")) {
3969       IgnoreUnrecognizedVMOptions = false;
3970       continue;
3971     }
3972     if (match_option(option, "-XX:+PrintFlagsInitial")) {
3973       CommandLineFlags::printFlags(tty, false);
3974       vm_exit(0);
3975     }
3976     if (match_option(option, "-XX:NativeMemoryTracking", &tail)) {
3977 #if INCLUDE_NMT
3978       // The launcher did not setup nmt environment variable properly.
3979       if (!MemTracker::check_launcher_nmt_support(tail)) {
3980         warning("Native Memory Tracking did not setup properly, using wrong launcher?");
3981       }
3982 
3983       // Verify if nmt option is valid.
3984       if (MemTracker::verify_nmt_option()) {
3985         // Late initialization, still in single-threaded mode.
3986         if (MemTracker::tracking_level() >= NMT_summary) {
3987           MemTracker::init();
3988         }
3989       } else {
3990         vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL);
3991       }
3992       continue;
3993 #else
3994       jio_fprintf(defaultStream::error_stream(),
3995         "Native Memory Tracking is not supported in this VM\n");
3996       return JNI_ERR;
3997 #endif
3998     }
3999 
4000 #ifndef PRODUCT
4001     if (match_option(option, "-XX:+PrintFlagsWithComments")) {
4002       CommandLineFlags::printFlags(tty, true);
4003       vm_exit(0);
4004     }
4005 #endif
4006 
4007     if (match_option(option, "-XX:+UseAppCDS")) {
4008       Flag* flag = Flag::find_flag("SharedArchiveFile", 17, true, true);
4009       if (flag->is_diagnostic()) {
4010         flag->clear_diagnostic();
4011       }
4012       continue;
4013     }
4014   }
4015   return JNI_OK;
4016 }
4017 
4018 static void print_options(const JavaVMInitArgs *args) {
4019   const char* tail;
4020   for (int index = 0; index < args->nOptions; index++) {
4021     const JavaVMOption *option = args->options + index;
4022     if (match_option(option, "-XX:", &tail)) {
4023       logOption(tail);
4024     }
4025   }
4026 }
4027 
4028 bool Arguments::handle_deprecated_print_gc_flags() {
4029   if (PrintGC) {
4030     log_warning(gc)("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead.");
4031   }
4032   if (PrintGCDetails) {
4033     log_warning(gc)("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead.");
4034   }
4035 
4036   if (_gc_log_filename != NULL) {
4037     // -Xloggc was used to specify a filename
4038     const char* gc_conf = PrintGCDetails ? "gc*" : "gc";
4039 
4040     LogTarget(Error, logging) target;
4041     LogStream errstream(target);
4042     return LogConfiguration::parse_log_arguments(_gc_log_filename, gc_conf, NULL, NULL, &errstream);
4043   } else if (PrintGC || PrintGCDetails) {
4044     LogConfiguration::configure_stdout(LogLevel::Info, !PrintGCDetails, LOG_TAGS(gc));
4045   }
4046   return true;
4047 }
4048 
4049 void Arguments::handle_extra_cms_flags(const char* msg) {
4050   SpecialFlag flag;
4051   const char *flag_name = "UseConcMarkSweepGC";
4052   if (lookup_special_flag(flag_name, flag)) {
4053     handle_aliases_and_deprecation(flag_name, /* print warning */ true);
4054     warning("%s", msg);
4055   }
4056 }
4057 
4058 // Parse entry point called from JNI_CreateJavaVM
4059 
4060 jint Arguments::parse(const JavaVMInitArgs* initial_cmd_args) {
4061   assert(verify_special_jvm_flags(), "deprecated and obsolete flag table inconsistent");
4062 
4063   // Initialize ranges, constraints and writeables
4064   CommandLineFlagRangeList::init();
4065   CommandLineFlagConstraintList::init();
4066   CommandLineFlagWriteableList::init();
4067 
4068   // If flag "-XX:Flags=flags-file" is used it will be the first option to be processed.
4069   const char* hotspotrc = ".hotspotrc";
4070   bool settings_file_specified = false;
4071   bool needs_hotspotrc_warning = false;
4072   ScopedVMInitArgs initial_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4073   ScopedVMInitArgs initial_java_options_args("env_var='_JAVA_OPTIONS'");
4074 
4075   // Pointers to current working set of containers
4076   JavaVMInitArgs* cur_cmd_args;
4077   JavaVMInitArgs* cur_java_options_args;
4078   JavaVMInitArgs* cur_java_tool_options_args;
4079 
4080   // Containers for modified/expanded options
4081   ScopedVMInitArgs mod_cmd_args("cmd_line_args");
4082   ScopedVMInitArgs mod_java_tool_options_args("env_var='JAVA_TOOL_OPTIONS'");
4083   ScopedVMInitArgs mod_java_options_args("env_var='_JAVA_OPTIONS'");
4084 
4085 
4086   jint code =
4087       parse_java_tool_options_environment_variable(&initial_java_tool_options_args);
4088   if (code != JNI_OK) {
4089     return code;
4090   }
4091 
4092   code = parse_java_options_environment_variable(&initial_java_options_args);
4093   if (code != JNI_OK) {
4094     return code;
4095   }
4096 
4097   code = expand_vm_options_as_needed(initial_java_tool_options_args.get(),
4098                                      &mod_java_tool_options_args,
4099                                      &cur_java_tool_options_args);
4100   if (code != JNI_OK) {
4101     return code;
4102   }
4103 
4104   code = expand_vm_options_as_needed(initial_cmd_args,
4105                                      &mod_cmd_args,
4106                                      &cur_cmd_args);
4107   if (code != JNI_OK) {
4108     return code;
4109   }
4110 
4111   code = expand_vm_options_as_needed(initial_java_options_args.get(),
4112                                      &mod_java_options_args,
4113                                      &cur_java_options_args);
4114   if (code != JNI_OK) {
4115     return code;
4116   }
4117 
4118   const char* flags_file = Arguments::get_jvm_flags_file();
4119   settings_file_specified = (flags_file != NULL);
4120 
4121   if (IgnoreUnrecognizedVMOptions) {
4122     cur_cmd_args->ignoreUnrecognized = true;
4123     cur_java_tool_options_args->ignoreUnrecognized = true;
4124     cur_java_options_args->ignoreUnrecognized = true;
4125   }
4126 
4127   // Parse specified settings file
4128   if (settings_file_specified) {
4129     if (!process_settings_file(flags_file, true,
4130                                cur_cmd_args->ignoreUnrecognized)) {
4131       return JNI_EINVAL;
4132     }
4133   } else {
4134 #ifdef ASSERT
4135     // Parse default .hotspotrc settings file
4136     if (!process_settings_file(".hotspotrc", false,
4137                                cur_cmd_args->ignoreUnrecognized)) {
4138       return JNI_EINVAL;
4139     }
4140 #else
4141     struct stat buf;
4142     if (os::stat(hotspotrc, &buf) == 0) {
4143       needs_hotspotrc_warning = true;
4144     }
4145 #endif
4146   }
4147 
4148   if (PrintVMOptions) {
4149     print_options(cur_java_tool_options_args);
4150     print_options(cur_cmd_args);
4151     print_options(cur_java_options_args);
4152   }
4153 
4154   // Parse JavaVMInitArgs structure passed in, as well as JAVA_TOOL_OPTIONS and _JAVA_OPTIONS
4155   jint result = parse_vm_init_args(cur_java_tool_options_args,
4156                                    cur_java_options_args,
4157                                    cur_cmd_args);
4158 
4159   if (result != JNI_OK) {
4160     return result;
4161   }
4162 
4163   // Call get_shared_archive_path() here, after possible SharedArchiveFile option got parsed.
4164   SharedArchivePath = get_shared_archive_path();
4165   if (SharedArchivePath == NULL) {
4166     return JNI_ENOMEM;
4167   }
4168 
4169   // Set up VerifySharedSpaces
4170   if (FLAG_IS_DEFAULT(VerifySharedSpaces) && SharedArchiveFile != NULL) {
4171     VerifySharedSpaces = true;
4172   }
4173 
4174   // Delay warning until here so that we've had a chance to process
4175   // the -XX:-PrintWarnings flag
4176   if (needs_hotspotrc_warning) {
4177     warning("%s file is present but has been ignored.  "
4178             "Run with -XX:Flags=%s to load the file.",
4179             hotspotrc, hotspotrc);
4180   }
4181 
4182   if (needs_module_property_warning) {
4183     warning("Ignoring system property options whose names match the '-Djdk.module.*'."
4184             " names that are reserved for internal use.");
4185   }
4186 
4187 #if defined(_ALLBSD_SOURCE) || defined(AIX)  // UseLargePages is not yet supported on BSD and AIX.
4188   UNSUPPORTED_OPTION(UseLargePages);
4189 #endif
4190 
4191   ArgumentsExt::report_unsupported_options();
4192 
4193 #ifndef PRODUCT
4194   if (TraceBytecodesAt != 0) {
4195     TraceBytecodes = true;
4196   }
4197   if (CountCompiledCalls) {
4198     if (UseCounterDecay) {
4199       warning("UseCounterDecay disabled because CountCalls is set");
4200       UseCounterDecay = false;
4201     }
4202   }
4203 #endif // PRODUCT
4204 
4205   if (ScavengeRootsInCode == 0) {
4206     if (!FLAG_IS_DEFAULT(ScavengeRootsInCode)) {
4207       warning("Forcing ScavengeRootsInCode non-zero");
4208     }
4209     ScavengeRootsInCode = 1;
4210   }
4211 
4212   if (!handle_deprecated_print_gc_flags()) {
4213     return JNI_EINVAL;
4214   }
4215 
4216   // Set object alignment values.
4217   set_object_alignment();
4218 
4219 #if !INCLUDE_CDS
4220   if (DumpSharedSpaces || RequireSharedSpaces) {
4221     jio_fprintf(defaultStream::error_stream(),
4222       "Shared spaces are not supported in this VM\n");
4223     return JNI_ERR;
4224   }
4225   if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) ||
4226       log_is_enabled(Info, cds)) {
4227     warning("Shared spaces are not supported in this VM");
4228     FLAG_SET_DEFAULT(UseSharedSpaces, false);
4229     LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(cds));
4230   }
4231   no_shared_spaces("CDS Disabled");
4232 #endif // INCLUDE_CDS
4233 
4234   return JNI_OK;
4235 }
4236 
4237 jint Arguments::apply_ergo() {
4238   // Set flags based on ergonomics.
4239   jint result = set_ergonomics_flags();
4240   if (result != JNI_OK) return result;
4241 
4242 #if INCLUDE_JVMCI
4243   set_jvmci_specific_flags();
4244 #endif
4245 
4246   set_shared_spaces_flags();
4247 
4248   // Check the GC selections again.
4249   if (!check_gc_consistency()) {
4250     return JNI_EINVAL;
4251   }
4252 
4253   if (TieredCompilation) {
4254     set_tiered_flags();
4255   } else {
4256     int max_compilation_policy_choice = 1;
4257 #ifdef COMPILER2
4258     if (is_server_compilation_mode_vm()) {
4259       max_compilation_policy_choice = 2;
4260     }
4261 #endif
4262     // Check if the policy is valid.
4263     if (CompilationPolicyChoice >= max_compilation_policy_choice) {
4264       vm_exit_during_initialization(
4265         "Incompatible compilation policy selected", NULL);
4266     }
4267     // Scale CompileThreshold
4268     // CompileThresholdScaling == 0.0 is equivalent to -Xint and leaves CompileThreshold unchanged.
4269     if (!FLAG_IS_DEFAULT(CompileThresholdScaling) && CompileThresholdScaling > 0.0) {
4270       FLAG_SET_ERGO(intx, CompileThreshold, scaled_compile_threshold(CompileThreshold));
4271     }
4272   }
4273 
4274 #ifdef COMPILER2
4275 #ifndef PRODUCT
4276   if (PrintIdealGraphLevel > 0) {
4277     FLAG_SET_ERGO(bool, PrintIdealGraph, true);
4278   }
4279 #endif
4280 #endif
4281 
4282   // Set heap size based on available physical memory
4283   set_heap_size();
4284 
4285   GCArguments::arguments()->initialize_flags();
4286 
4287   // Initialize Metaspace flags and alignments
4288   Metaspace::ergo_initialize();
4289 
4290   // Set bytecode rewriting flags
4291   set_bytecode_flags();
4292 
4293   // Set flags if Aggressive optimization flags (-XX:+AggressiveOpts) enabled
4294   jint code = set_aggressive_opts_flags();
4295   if (code != JNI_OK) {
4296     return code;
4297   }
4298 
4299   // Turn off biased locking for locking debug mode flags,
4300   // which are subtly different from each other but neither works with
4301   // biased locking
4302   if (UseHeavyMonitors
4303 #ifdef COMPILER1
4304       || !UseFastLocking
4305 #endif // COMPILER1
4306 #if INCLUDE_JVMCI
4307       || !JVMCIUseFastLocking
4308 #endif
4309     ) {
4310     if (!FLAG_IS_DEFAULT(UseBiasedLocking) && UseBiasedLocking) {
4311       // flag set to true on command line; warn the user that they
4312       // can't enable biased locking here
4313       warning("Biased Locking is not supported with locking debug flags"
4314               "; ignoring UseBiasedLocking flag." );
4315     }
4316     UseBiasedLocking = false;
4317   }
4318 
4319 #ifdef CC_INTERP
4320   // Clear flags not supported on zero.
4321   FLAG_SET_DEFAULT(ProfileInterpreter, false);
4322   FLAG_SET_DEFAULT(UseBiasedLocking, false);
4323   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedOops, false));
4324   LP64_ONLY(FLAG_SET_DEFAULT(UseCompressedClassPointers, false));
4325 #endif // CC_INTERP
4326 
4327 #ifdef COMPILER2
4328   if (!EliminateLocks) {
4329     EliminateNestedLocks = false;
4330   }
4331   if (!Inline) {
4332     IncrementalInline = false;
4333   }
4334 #ifndef PRODUCT
4335   if (!IncrementalInline) {
4336     AlwaysIncrementalInline = false;
4337   }
4338 #endif
4339   if (!UseTypeSpeculation && FLAG_IS_DEFAULT(TypeProfileLevel)) {
4340     // nothing to use the profiling, turn if off
4341     FLAG_SET_DEFAULT(TypeProfileLevel, 0);
4342   }
4343 #endif
4344 
4345   if (PrintAssembly && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
4346     warning("PrintAssembly is enabled; turning on DebugNonSafepoints to gain additional output");
4347     DebugNonSafepoints = true;
4348   }
4349 
4350   if (FLAG_IS_CMDLINE(CompressedClassSpaceSize) && !UseCompressedClassPointers) {
4351     warning("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used");
4352   }
4353 
4354   if (UseOnStackReplacement && !UseLoopCounter) {
4355     warning("On-stack-replacement requires loop counters; enabling loop counters");
4356     FLAG_SET_DEFAULT(UseLoopCounter, true);
4357   }
4358 
4359 #ifndef PRODUCT
4360   if (!LogVMOutput && FLAG_IS_DEFAULT(LogVMOutput)) {
4361     if (use_vm_log()) {
4362       LogVMOutput = true;
4363     }
4364   }
4365 #endif // PRODUCT
4366 
4367   if (PrintCommandLineFlags) {
4368     CommandLineFlags::printSetFlags(tty);
4369   }
4370 
4371   // Apply CPU specific policy for the BiasedLocking
4372   if (UseBiasedLocking) {
4373     if (!VM_Version::use_biased_locking() &&
4374         !(FLAG_IS_CMDLINE(UseBiasedLocking))) {
4375       UseBiasedLocking = false;
4376     }
4377   }
4378 #ifdef COMPILER2
4379   if (!UseBiasedLocking || EmitSync != 0) {
4380     UseOptoBiasInlining = false;
4381   }
4382 #endif
4383 
4384   // ThreadLocalHandshakesConstraintFunc handles the constraints.
4385   if (FLAG_IS_DEFAULT(ThreadLocalHandshakes) || !SafepointMechanism::supports_thread_local_poll()) {
4386     log_debug(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
4387   } else {
4388     log_info(ergo)("ThreadLocalHandshakes %s", ThreadLocalHandshakes ? "enabled." : "disabled.");
4389   }
4390 
4391   return JNI_OK;
4392 }
4393 
4394 jint Arguments::adjust_after_os() {
4395   if (UseNUMA) {
4396     if (!FLAG_IS_DEFAULT(AllocateHeapAt)) {
4397       FLAG_SET_ERGO(bool, UseNUMA, false);
4398     } else if (UseParallelGC || UseParallelOldGC) {
4399       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
4400          FLAG_SET_DEFAULT(MinHeapDeltaBytes, 64*M);
4401       }
4402     }
4403     // UseNUMAInterleaving is set to ON for all collectors and
4404     // platforms when UseNUMA is set to ON. NUMA-aware collectors
4405     // such as the parallel collector for Linux and Solaris will
4406     // interleave old gen and survivor spaces on top of NUMA
4407     // allocation policy for the eden space.
4408     // Non NUMA-aware collectors such as CMS, G1 and Serial-GC on
4409     // all platforms and ParallelGC on Windows will interleave all
4410     // of the heap spaces across NUMA nodes.
4411     if (FLAG_IS_DEFAULT(UseNUMAInterleaving)) {
4412       FLAG_SET_ERGO(bool, UseNUMAInterleaving, true);
4413     }
4414   }
4415   return JNI_OK;
4416 }
4417 
4418 int Arguments::PropertyList_count(SystemProperty* pl) {
4419   int count = 0;
4420   while(pl != NULL) {
4421     count++;
4422     pl = pl->next();
4423   }
4424   return count;
4425 }
4426 
4427 // Return the number of readable properties.
4428 int Arguments::PropertyList_readable_count(SystemProperty* pl) {
4429   int count = 0;
4430   while(pl != NULL) {
4431     if (pl->is_readable()) {
4432       count++;
4433     }
4434     pl = pl->next();
4435   }
4436   return count;
4437 }
4438 
4439 const char* Arguments::PropertyList_get_value(SystemProperty *pl, const char* key) {
4440   assert(key != NULL, "just checking");
4441   SystemProperty* prop;
4442   for (prop = pl; prop != NULL; prop = prop->next()) {
4443     if (strcmp(key, prop->key()) == 0) return prop->value();
4444   }
4445   return NULL;
4446 }
4447 
4448 // Return the value of the requested property provided that it is a readable property.
4449 const char* Arguments::PropertyList_get_readable_value(SystemProperty *pl, const char* key) {
4450   assert(key != NULL, "just checking");
4451   SystemProperty* prop;
4452   // Return the property value if the keys match and the property is not internal or
4453   // it's the special internal property "jdk.boot.class.path.append".
4454   for (prop = pl; prop != NULL; prop = prop->next()) {
4455     if (strcmp(key, prop->key()) == 0) {
4456       if (!prop->internal()) {
4457         return prop->value();
4458       } else if (strcmp(key, "jdk.boot.class.path.append") == 0) {
4459         return prop->value();
4460       } else {
4461         // Property is internal and not jdk.boot.class.path.append so return NULL.
4462         return NULL;
4463       }
4464     }
4465   }
4466   return NULL;
4467 }
4468 
4469 const char* Arguments::PropertyList_get_key_at(SystemProperty *pl, int index) {
4470   int count = 0;
4471   const char* ret_val = NULL;
4472 
4473   while(pl != NULL) {
4474     if(count >= index) {
4475       ret_val = pl->key();
4476       break;
4477     }
4478     count++;
4479     pl = pl->next();
4480   }
4481 
4482   return ret_val;
4483 }
4484 
4485 char* Arguments::PropertyList_get_value_at(SystemProperty* pl, int index) {
4486   int count = 0;
4487   char* ret_val = NULL;
4488 
4489   while(pl != NULL) {
4490     if(count >= index) {
4491       ret_val = pl->value();
4492       break;
4493     }
4494     count++;
4495     pl = pl->next();
4496   }
4497 
4498   return ret_val;
4499 }
4500 
4501 void Arguments::PropertyList_add(SystemProperty** plist, SystemProperty *new_p) {
4502   SystemProperty* p = *plist;
4503   if (p == NULL) {
4504     *plist = new_p;
4505   } else {
4506     while (p->next() != NULL) {
4507       p = p->next();
4508     }
4509     p->set_next(new_p);
4510   }
4511 }
4512 
4513 void Arguments::PropertyList_add(SystemProperty** plist, const char* k, const char* v,
4514                                  bool writeable, bool internal) {
4515   if (plist == NULL)
4516     return;
4517 
4518   SystemProperty* new_p = new SystemProperty(k, v, writeable, internal);
4519   PropertyList_add(plist, new_p);
4520 }
4521 
4522 void Arguments::PropertyList_add(SystemProperty *element) {
4523   PropertyList_add(&_system_properties, element);
4524 }
4525 
4526 // This add maintains unique property key in the list.
4527 void Arguments::PropertyList_unique_add(SystemProperty** plist, const char* k, const char* v,
4528                                         PropertyAppendable append, PropertyWriteable writeable,
4529                                         PropertyInternal internal) {
4530   if (plist == NULL)
4531     return;
4532 
4533   // If property key exist then update with new value.
4534   SystemProperty* prop;
4535   for (prop = *plist; prop != NULL; prop = prop->next()) {
4536     if (strcmp(k, prop->key()) == 0) {
4537       if (append == AppendProperty) {
4538         prop->append_value(v);
4539       } else {
4540         prop->set_value(v);
4541       }
4542       return;
4543     }
4544   }
4545 
4546   PropertyList_add(plist, k, v, writeable == WriteableProperty, internal == InternalProperty);
4547 }
4548 
4549 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
4550 // Returns true if all of the source pointed by src has been copied over to
4551 // the destination buffer pointed by buf. Otherwise, returns false.
4552 // Notes:
4553 // 1. If the length (buflen) of the destination buffer excluding the
4554 // NULL terminator character is not long enough for holding the expanded
4555 // pid characters, it also returns false instead of returning the partially
4556 // expanded one.
4557 // 2. The passed in "buflen" should be large enough to hold the null terminator.
4558 bool Arguments::copy_expand_pid(const char* src, size_t srclen,
4559                                 char* buf, size_t buflen) {
4560   const char* p = src;
4561   char* b = buf;
4562   const char* src_end = &src[srclen];
4563   char* buf_end = &buf[buflen - 1];
4564 
4565   while (p < src_end && b < buf_end) {
4566     if (*p == '%') {
4567       switch (*(++p)) {
4568       case '%':         // "%%" ==> "%"
4569         *b++ = *p++;
4570         break;
4571       case 'p':  {       //  "%p" ==> current process id
4572         // buf_end points to the character before the last character so
4573         // that we could write '\0' to the end of the buffer.
4574         size_t buf_sz = buf_end - b + 1;
4575         int ret = jio_snprintf(b, buf_sz, "%d", os::current_process_id());
4576 
4577         // if jio_snprintf fails or the buffer is not long enough to hold
4578         // the expanded pid, returns false.
4579         if (ret < 0 || ret >= (int)buf_sz) {
4580           return false;
4581         } else {
4582           b += ret;
4583           assert(*b == '\0', "fail in copy_expand_pid");
4584           if (p == src_end && b == buf_end + 1) {
4585             // reach the end of the buffer.
4586             return true;
4587           }
4588         }
4589         p++;
4590         break;
4591       }
4592       default :
4593         *b++ = '%';
4594       }
4595     } else {
4596       *b++ = *p++;
4597     }
4598   }
4599   *b = '\0';
4600   return (p == src_end); // return false if not all of the source was copied
4601 }