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