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