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