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