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