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