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