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