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