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