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