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