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