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