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