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