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