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