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