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