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