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